我这个context为空出现的情景是 我已经在applicaiton 获取context 开始我是这样写的
看起来是没有什么问题,但是还是要用地方还是获取不到context,然后我把Context改为静态变量
这样写是可以获取到Context但还是会报一个
Can't toast on a thread that has not called Looper.prepare()
这个问题大家都知道 Toast 不能在子线程中直接创建,但是我们又需要这样写,接下来我实现一下
我们先调用Looper.prepare,然后toast弹出,然后Looper.loop() 就可以了
调用的地方直接用
这样写就可以了。
还有一个是在子线程中使用Handler
new Thread (new Runnable {
@Override
public void run(){
Looper.prepare();
new Handler.post(runnable);
Looper.loop(); // 这种情况Runnable是运行在子线程中,是不能更新Ui操作的
}
}).start();