Toast的显示,需要looper! 如果在没有looper的情况下可以调用Looper.prepare() 来准备looper。但是在Service中,显示Toast的方法就是必须要将Toast的显示放在主线程中,即UI线程,所以,这里就要通过Looper.getMainLooper(),将主线程的Looper给Handler,然后通过Handler发送给UI线程,getApplicationContext(),即当前正在执行的UI线程。
Handler handler2=new Handler(Looper.getMainLooper()); // 这里是得到主界面程序的Looper
handler2.post(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(), getString(R.string.Toast_msg_versioncheck), Toast.LENGTH_LONG).show();
}
});
本文介绍了如何在Android Service中正确地显示Toast消息。通常Service运行在后台,不在UI线程中,因此直接显示Toast会失败。文章提供了一个解决方案,通过获取主线程的Looper并使用Handler传递任务到UI线程来实现。

被折叠的 条评论
为什么被折叠?



