Android主线程中延时处理

Android对UI主线程开启了实时监听,Activity Manager和WindowManager系统服务一旦监听到主线程超过10秒没有响应操作,就会抛出ANR,所以,在UI主线程中不能直接调用Thread.sleep方法去延时,超过10秒就根本不会执行后面的操作,当有必要在主线程中增加延时处理时,可以通过开启子线程的方法:

new Thread(new Runnable(){   

                    public void run(){   
                        try {
                            Thread.sleep(70000);
                        } catch (InterruptedException e) {
                            Log.e(TAG, "SLEEP throw e: "+ e.toString());
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.arg1 = 1;
                        handler.sendMessage(msg); 
                    }   

                }).start();

然后通过Handler将‘睡’的结果反馈给主线程:

private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg) {
            case 0:
            //TODO
            case 1:
            //TODO
            }

        }
    };

你可能感兴趣的:(apk应用开发)