looper死循环为什么不阻塞主线程,造成ANR?
1.要保证程序一直活着,必须是一个死循环。while(true)是程序活着的必须条件
2.死循环主线程怎么玩儿?回到上篇文章代码
public static void main(String[] args) {
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = new Handler();
}
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看到prepareMainLooper()之后创建了一个Handler()给主线程
这个handler就是处理主线程那些方法,比如生命周期、触摸时间等等。
while(ture) 不会让主线程死掉,因为它就是主线程,主线程所有方法都在这里处理
ps:如果再onCreat()方法里面执行了一个网络操作,长时间没处理完,下个消息就取不出来了,阻塞住了,就发生了ANR