表象
Service中可以正常显示Toast,IntentService中不能正常显示Toast,在2.3系统上,不显示toast,在4.3系统上,toast显示,但是不会消失。
原因
Toast要求运行在UI主线程中。
Service运行在主线程中,因此Toast是正常的。
IntentService运行在独立的线程中,因此Toast不正常。在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();
}
});
}
toast 在IntentService中不消失
最新推荐文章于 2023-07-19 09:53:24 发布