1. Representation
Toast can be displayed normally in Service, but Toast cannot be displayed normally in IntentService. toast is not displayed in system 2.3, but does not disappear in system 4.3.
2. Cause
Toast needs to run in the main UI thread. Service runs in the main thread, SO Toast is normal. IntentService runs in an independent thread, SO Toast is not normal.
3. Display Toast in IntentService
Use Handler to display the work of Toast and put it in the main thread. There are two implementation methods.
The post method of Handler is simple.
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(); } }); }
The implementation of Handler's msg method is complicated.
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. Time-consuming operationsIf there are time-consuming operations in the Service, you need to enable a Thread. IntentService is in an independent thread, so you can perform some time-consuming operations.
5.
Consider the differences between AsyncTask and ServiceIf you are working in the background, you can use the Service, and the Notification can be used for result prompts. If the job is asynchronous and the UI needs to be updated after the job ends, it is best to use Thread or AsyncTask.
6. Reference
Android Handler Mechanism
Http://developer.android.com/reference/android/ OS /Handler.html deeply understand ANDROID Message Processing System-lofter, HANDLER, THREAD7. Address of this ArticleHttp://blog.csdn.net/xiaodongrush/article/details/9628849