【Android】ANR 应用无响应的情况 - 介绍,以及出现缘由和对应的解决方式

背景

在对项目进行处理的时候发现出现应用无响应的问题,原来是拷贝文件的操作放在主线程走了!
那么有时候就直接卡住了。

思路

What is ANR?

When the UI thread of an Android app is blocked for too long, an “Application Not Responding” (ANR) error is triggered. If the app is in the foreground, Android will display the ANR dialog for a particular application when it detects one of the following conditions:
No response to an input event (such as key press or screen touch events) within 5 seconds.
A BroadcastReceiver hasn’t finished executing within 10 seconds.

How to avoid ANR?

By keeping your application’s main thread responsive, you can prevent ANR dialogs from being shown to users.

一般缘由

The app is doing slow operations involving I/O on the main thread.
The app is doing a long calculation on the main thread.
The main thread is doing a synchronous binder call to another process, and that other process is taking a long time to return.
The main thread is blocked waiting for a synchronized block for a long operation that is happening on another thread.
The main thread is in a deadlock with another thread, either in your process or via a binder call.
StrictMode is a developer tool which detects accidental disk or network access on the application’s main thread, where UI operations are received and animations take place. You can use StrictMode at the application or activity level.

  • 读写操作过频繁,暂居资源
  • 主线程长运算操作
  • 死锁了

解决方法:

In particular, activities should do as little as possible to set up in key life-cycle methods such as onCreate() and onResume().
Potentially long running operations such as network or database operations, or computationally expensive calculations such as resizing bitmaps should be done in a worker thread like AsyncTask
Diagnosing ANRs:

  • 在起步的生命周期中不要做太多事。
  • 暂居资源的一些事,如网络请求、数据库操作、高运算操作等等都不要挂在主线程走,放在其他线程走,例如AsyncTask
    -【Android】ANR 应用无响应的情况 - 介绍,以及出现缘由和对应的解决方式_第1张图片

你可能感兴趣的:(android代码小结,知识分享,android)