Android源码分析_looper死循环

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值