正确处理Toast异常, Unable to add window -- token ..... is not valid; is your activity running?

解决办法

new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(Activity.this, “内容”, Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();

问题原因,参考这篇文章:Toast源码深度分析
https://blog.csdn.net/m0_37700275/article/details/83038714#commentBox

发现新问题,使用以上解决方案出现异常
Caused by: java.lang.RuntimeException: Only one Looper may be created per thread
解决办法为
new Thread(new Runnable() {
@Override
public void run() {
if(Looper.myLooper() == null) { // check already Looper is associated or not.
Looper.prepare(); // No Looper is defined So define a new one
}

     Toast.makeText(Activity.this, "内容", Toast.LENGTH_SHORT).show();
    
            Looper.loop();
}

}).start();

你可能感兴趣的:(android)