国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android Service中使用Toast無法正常顯示問題的解決方法

2019-10-23 20:08:55
字體:
來源:轉載
供稿:網友

本文實例講述了Android Service中使用Toast無法正常顯示問題的解決方法。分享給大家供大家參考,具體如下:

在做Service簡單練習時,在Service中的OnCreate、OnStart、OnDestroy三個方法中都像在Activity中同樣的方法調用了Toast.makeText,并在Acitivy中通過兩個按鈕來調用該服務的onStart和onDestroy方法:

DemoService代碼如下:

@Overridepublic void onCreate(){    super.onCreate();    Toast.makeText(getApplicationContext(), "Service is created!", Toast.LENGTH_LONG).show();}@Overridepublic void onStart(Intent intent,int startId){    super.onStart(intent, startId);    Toast.makeText(getApplicationContext(), "Service is on!", Toast.LENGTH_LONG).show();}@Overridepublic void onDestroy(){    super.onDestroy();    Toast.makeText(getApplicationContext(), "Service is off!", Toast.LENGTH_LONG).show();}

運行之后,DemoService中的信息都沒有顯示出來。

剛開始以為所得到的Context不正確,在Service直接調用getApplicationContext()得到的是Service的Context,但是細究來看,Toast應該得到主UI的Context才能顯示,所以找了一下,Google對Toast的說明中,有一句:

“A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service,it appears in front of the Activity currently in focus.”
(http://developer.Android.com/guide/topics/ui/notifiers/toasts.html)

那么按照這句來看,service中創建的toast會在Acivity的UI前面聚焦顯示。但為什么運行沒有效果呢?再來查看一下makeText方法。

Android,Service,Toast,無法正常顯示問題,解決方法

果然還是Context的問題,所以想要toast能夠正常工作,需要在Activity的主線程上運行才行,那么如何得到主線程UI的Context呢?可以通過Handler將一個自定義的線程運行于主線程之上。

再來看一下Toast.show方法的src:

public void show() {    ...    service.enqueueToast(pkg, tn, mDuration);  //將該toast插入到一個消息隊列中    ...}

原理上看,Android中大致上是消息隊列和消息循環,主線程從消息隊列中取得消息并處理。而Handler看作是一個工具類,用來向消息隊列中插入消息。所以我們重構原來的代碼:

@Overridepublic void onCreate(){    super.onCreate();    handler=new Handler(Looper.getMainLooper());    handler.post(new Runnable(){      public void run(){        Toast.makeText(getApplicationContext(), "Service is created!", Toast.LENGTH_LONG).show();      }    });}@Overridepublic void onStart(Intent intent,int startId){    super.onStart(intent, startId);    handler=new Handler(Looper.getMainLooper());    handler.post(new Runnable(){      public void run(){        Toast.makeText(getApplicationContext(), "Service is on!", Toast.LENGTH_LONG).show();      }    });}@Overridepublic void onDestroy(){    super.onDestroy();    handler=new Handler(Looper.getMainLooper());    handler.post(new Runnable(){      public void run(){        Toast.makeText(getApplicationContext(), "Service is off!", Toast.LENGTH_LONG).show();      }    });}

運行之后的效果如下:

Android,Service,Toast,無法正常顯示問題,解決方法

總結:在Android的Framework中使用Toast,要將Toast添加到主線程里才能正常工作。

希望本文所述對大家Android程序設計有所幫助。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 馆陶县| 通州市| 屏南县| 清徐县| 巴塘县| 垦利县| 乐至县| 肥西县| 利川市| 赫章县| 泊头市| 西峡县| 惠来县| 运城市| 永靖县| 广灵县| 若尔盖县| 启东市| 神池县| 会东县| 如皋市| 清丰县| 咸阳市| 林西县| 南靖县| 嘉鱼县| 桃江县| 陆良县| 济南市| 哈密市| 景洪市| 新邵县| 闽清县| 垣曲县| 双牌县| 澄城县| 天峨县| 灌南县| 河南省| 象州县| 抚松县|