Android App在线程中创建handler的方法讲解

2019-12-10 18:37:43于海丽

源码中:
主线程:
在程序启动的时候,系统已经帮我们自动调用了Looper.prepare()方法。查看ActivityThread中的main()

public static void main(String[] args) { 
SamplingProfilerIntegration.start(); 
CloseGuard.setEnabled(false); 
Environment.initForCurrentUser(); 
EventLogger.setReporter(new EventLoggingReporter()); 
Process.setArgV0("<pre-initialized>"); 
Looper.prepareMainLooper(); 
ActivityThread thread = new ActivityThread(); 
thread.attach(false); 
if (sMainThreadHandler == null) { 
  sMainThreadHandler = thread.getHandler(); 
} 
AsyncTask.init(); 
if (false) { 
  Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); 
} 
Looper.loop(); 
throw new RuntimeException("Main thread loop unexpectedly exited"); 
} 

请注意Looper.prepareMainLooper():

public static final void prepareMainLooper() { 
prepare(); 
setMainLooper(myLooper()); 
if (Process.supportsProcesses()) { 
  myLooper().mQueue.mQuitAllowed = false; 
} 
} 

子线程:

new Thread(new Runnable() { 
    @Override 
    public void run() { 
      Looper.prepare()
      handler2 = new Handler(); 
      Looper.loop() 
    } 
  }).start();

如果没有Looper.prepare().会报错:

Can't create handler inside thread that has not called Looper.prepare() 
因为没looper对象创建

looper.prepare()源码:

public static final void prepare() { 
if (sThreadLocal.get() != null) { 
  throw new RuntimeException("Only one Looper may be created per thread"); 
} 
sThreadLocal.set(new Looper()); 
}