The application may be doing too much work on its main thread.

最近学习handler中的回调:handler.callback。出现异常

I/Choreographer: Skipped 179 frames!  The application may be doing too much work on its main thread.

意思是:主线程中有耗时操作,主线程受不了了。原因是我在重写callback的handleMessage方法时,模拟了延时操作。实际在开发中,这种情况是万万不可的,解决办法是实现android的两大原则:

1. 不要!不要在主线程(UI线程)中执行耗时操作,如网络请求,数据库操作等。应另开线程操作,实现方式有1) 自开线程new Thread;2) runOnUIThread; 3) post方法以及4) 异步AsyncTask

2. 一定!一定要在主线程(UI线程)中修改控件的状态。否则会报:Only the original thread that created a view hierarchy can touch its views

 

这里顺便给出handler的回调机制实现

代码实现:

1. 实例化消息message

1         // declare a message
2         Message message = new Message();
3         message.obj = "Don't call me, I'll call you";

2. 实例化Handler.Callback,重写handleMessage方法

 1         // declare a callback obj
 2         Handler.Callback callback = new Handler.Callback() {
 3             @Override
 4             public boolean handleMessage(Message msg) {
 5                 // make a pause
 6                 SystemClock.sleep(3_000); // 就是这里出了问题,这是个耗时操作,应扔到另一个线程中
 7 
 8                 // <code to be executed during callback>
 9                 Log.d("TOM", "Don't call me, I'll call you");
10                 return true;
11             }
12         };    

3. 发送消息

1         // send message
2         new Handler(callback).sendMessage(message);

参考链接:

http://stackoverflow.com/questions/14678593/the-application-may-be-doing-too-much-work-on-its-main-thread

posted on 2016-04-28 22:45  了明  阅读(25370)  评论(1编辑  收藏

导航