在线程中调用包含创建handler方法的时候,会报错,提示:

“need call Looper.prepare()” -- 在创建之前,调用Looper.prepare()方法来创建一个looper

但是这个包含创建handler的方法,可能在主线程中调用,也可能在子线程中调用。

在主线程中调用的时候,你给它加上looper.prepare()方法,它可能会报错,提示:

“Only one Looper may be created per thread” -- 每个线程之中,只能有一个Looper

解决的办法:

        	if (Looper.myLooper() == null) {
			Looper.prepare();
		}

 其中,Looper.myLooper()方法的返回值是当前线程的Looper对象,返回的是Null的时候,则需要通过Looper.prepare()方法创建Looper

 可以对照Looper类的源码查看一下,即可。

相关文章:

  • 2021-04-19
  • 2021-10-20
  • 2022-12-23
  • 2021-06-08
  • 2021-11-08
  • 2022-12-23
  • 2021-11-25
猜你喜欢
  • 2022-02-01
  • 2021-07-24
  • 2021-12-30
  • 2022-03-09
  • 2021-09-06
  • 2022-01-14
相关资源
相似解决方案