Android开发:Can't create handler inside thread that has not called Looper.prepare() 异常的解决方案

时间:2022-08-14 20:44:49

在开发中,有时候会在使用Handler的时候,遇到以下的异常:

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

出现这种异常是因为在非主线程创建Handler或者静态Handler所触发的,可以通过初始化Handler时指定主线程解决,如下:

mHandler = new Handler (mContext.getMainLooper())