Service和IntentService中显示Toast的区别
2013-07-30 15:48
471 查看
本文链接 http://blog.csdn.net/xiaodongrush/article/details/9628849
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方式实现,这个方式比较简单。
Handler的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、THREAD
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、THREAD
相关文章推荐
- Service和IntentService中显示Toast的区别
- Android开发之Service和IntentService中显示Toast的区别
- [Android] Service和IntentService中显示Toast的区别
- Service和IntentService中显示Toast的区别
- Service和IntentService中显示Toast的有什么区别
- IntentService和AsyncTask的区别
- IntentService和Service的区别
- java中的回车符(\r)----在cmd和eclipse(Version: Kepler Service Release 2)中显示区别
- Android中IntentService与Service的区别
- Service中使用Toast显示问题
- 在IntentService中使用Toast与在Service中使用Toast的异同
- IntentService和Service的区别
- Service中使用Toast显示问题
- Android中IntentService与Service的区别
- Service与 IntentService 的区别与使用场景(源代码剖析)
- Android Service中使用Toast无法正常显示问题的解决方法
- IntentService和Service的区别
- 显示Intent和隐式Intent的区别
- Android Service与IntentService区别
- android中IntentService和Service有什么区别