Service中使用Toast出现问题及解决方法
最新推荐文章于 2023-02-17 20:48:57 发布
转载
最新推荐文章于 2023-02-17 20:48:57 发布
·
9.6k 阅读
·
3
·
0
文章标签:
#service
#thread
#null
本文详细解析了Android应用中遇到Toast无法显示问题的原因,并提供了简单有效的解决方案。通过理解Toast显示机制,我们了解到需要在特定线程中使用Looper.prepare()、Toast.makeText()和Looper.loop()来确保Toast能够在正确环境下显示。
前几次碰到这个问题,确实郁闷了很久... log -- java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()解决办法很简单: Looper.prepare();Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();Looper.loop();为什么要加这两句,看了源码就了解了Toast public void show() { ... service.enqueueToast(pkg, tn, mDuration); //把这个toast插入到一个队列里面 ... }Looperpublic static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper()); //在当前线程中创建一个Looper }private Looper() { mQueue = new MessageQueue(); //关键在这,创建Looper都干了什么。 其实是创建了消息队列 mRun = true; mThread = Thread.currentThread(); }一般如果不是在主线程中又开启了新线程的话,一般都会碰到这个问题。原因是在创建新线程的时候默认情况下不会去创建新的MessageQueue。总结下:Toast 显示的必要条件:1:Toast 显示需要出现在一个线程的消息队列中.... 很隐蔽