1. 表象
Service中可以正常顯示Toast,IntentService中不能正常顯示Toast,在2.3系統上,不顯示toast,在4.3系統上,toast顯示,但是不會消失。
2. 原因
Toast要求運行在UI主線程中。 Service運行在主線程中,因此Toast是正常的。 IntentService運行在獨立的線程中,因此Toast不正常。
3. 在IntentService中顯示Toast
利用Handler,將顯示Toast的工作,放在主線程中來做。具體有兩個實現方式。
Handler的post方式實現,這個方式比較簡單。
private void showToastByRunnable(final IntentService context, final CharSequence text, final int duration) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { Toast.makeText(context, text, duration).show(); } }); }
Handler的msg方式實現,這個方式比較複雜。
Handler msgHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { Toast.makeText(ToastIntentService.this, msg.getData().getString("Text"), Toast.LENGTH_SHORT).show(); super.handleMessage(msg); } }; private void showToastByMsg(final IntentService context, final CharSequence text, final int duration) { Bundle data = new Bundle(); data.putString("Text", text.toString()); Message msg = new Message(); msg.setData(data); msgHandler.sendMessage(msg); }
4. 關於耗時操作 Service中如果有耗時的操作,要開啟一個Thread來做。 IntentService是在獨立的線程中,所以可以進行一些耗時操作。
5.
考慮AsyncTask與Service的使用區別 如果是全背景工作,使用Service,結果的提示可以使用Notification。 如果是非同步工作,工作結束後需要更新UI,那麼最好使用Thread或者AsyncTask。
6. 參考
Android Handler機制詳解
http://developer.android.com/reference/android/os/Handler.html 深入理解ANDROID訊息處理系統——LOOPER、HANDLER、THREAD7. 本文地址 http://blog.csdn.net/xiaodongrush/article/details/9628849