Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

踩坑筆記:Android Service 中 Toast 不顯示的原因與解法

編輯:關於 Android 程式設計

做 Service 練習時,我在 onCreate、onStart、onDestroy 三個方法裡都像 Activity 那樣呼叫了 Toast.makeText,並用兩個按鈕觸發服務的啟動與銷毀,結果卻發現——Toast 一條都沒跳出來。這個問題值得細細拆解。

DemoService 代碼如下:

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

運行之後,這幾條信息全都沒顯示。

一開始我以為是 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.”
(https://developer.Android.com/guide/topics/ui/notifiers/toasts.html)

照這句話看,Service 中建立的 Toast 應該會顯示在 Activity 的前景上,那為什麼沒效果呢?再來看看 makeText 方法,果然還是 Context 的問題——Toast 需要在 Activity 的主線程上運行才能正常工作。

那如何拿到主線程 UI 的 Context 呢?可以透過 Handler 把任務運行於主線程之上。再來看 Toast.show 方法的源碼:

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

原理上,Android 大致是「消息隊列 + 消息循環」的架構:主線程從消息隊列取消息並處理,而 Handler 就是一個向隊列插入消息的工具類。於是我重構了原本的代碼:

 @Override public 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(); } }); } @Override public 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(); } }); } @Override public 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 裡使用 Toast,必須把它放到主線程中才能正常顯示。用 Handler 綁定 Looper.getMainLooper() 就是最直接的辦法。希望這篇踩坑記錄能幫你少走一點彎路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved