现在的位置: 首页 > 综合 > 正文

Android ANR

2017年11月28日 ⁄ 综合 ⁄ 共 1750字 ⁄ 字号 评论关闭

下面是我从Google Android Reference里查看到的关于ANR事件资料里截取的比较重要的信息。原文给出,翻译的不太好,请多多包涵。原文的地址:http://developer.android.com/intl/zh-cn/training/articles/perf-anr.html#Reinforcing

Android will display the ANR dialog for a particular application when it detects one of the following conditions:

当Android系统检测到以下状况,将会弹出ANR的对话框。
1 No response to an input event (such as key press or screen touch events) within 5 seconds.
1. 5秒内对输入没有反馈(如点击屏幕或按下按键)
2 A BroadcastReceiver hasn't finished executing within 10 seconds.
2. BroadcastReceiver不能在10秒内结束。

Android applications normally run entirely on a single thread by default the "UI thread" or "main thread"). This means anything your application is doing in the UI thread that takes a long time to complete can trigger the ANR dialog because your application
is not giving itself a chance to handle the input event or intent broadcasts.
一般情况下,Android应用是运行在主(UI)线程中。这意味着如果你在主线程中进行任何花费大量时间的工作,都会导致系统无法响应输入时间,从而导致ANR。

Although it's more complicated than AsyncTask, you might want to instead create your own Thread or HandlerThread class. If you do, you should set the thread priority to "background" priority by calling Process.setThreadPriority() and passing THREAD_PRIORITY_BACKGROUND.
If you don't set the thread to a lower priority this way, then the thread could still slow down your app because it operates at the same priority as the UI thread by default.
尽管Thread和HandlerThread用起来要比AsyncTask复杂得多,但仍有可能使用到。这时,应该调用Process.setThreadPriority()将Thread的优先级设置成THREAD_PRIORITY_BACKGROUND。如若不然,Thread将默认和UIThread处于同一优先级,仍会降低程序的灵敏度。

So as with other methods called in the UI thread, applications should avoid potentially long-running operations or calculations in a broadcast receiver. But instead of doing intensive tasks via worker threads, your application should start an IntentService
if a potentially long running action needs to be taken in response to an intent broadcast.
同UIThread一样,在BroadcastReceiver里也需要避免长时间的运算。如果需要,则应该新建一个IntentService,并在该Service里进行处理。

抱歉!评论已关闭.