Android开发中避免应用无响应的方法(Application Not Responding、ANR)

2019-12-10 20:01:49刘景俊

            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }
 
    // This is called each time you call publishProgress()
    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }
 
    // This is called when doInBackground() is finished
    protected void onPostExecute(Long result) {
        showNotification("Downloaded " + result + " bytes");
    }
}

 

执行这个工作线程,只需要创建一个实例,调用 execute():

 

复制代码 new DownloadFilesTask().execute(url1, url2, url3);

 

尽管比AsyncTask更复杂,你可能还是想创建自己的线程或者HandlerThread类,如果这么做,你应该调用Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND) 设置线程优先线为”background”.如果没有,线程仍然会拖慢应用,因为它跟UI线程优先级相同。

如果你实现Thread或HandlerThread,确保UI线程没有因为等待工作线程执行完而阻塞。不要调用Thread.wait()或Thread.sleep(),而是提供一个Handler,供任务执行完后回调。如此设计,UI线程会保持响应,避免出现ANR对话框。

特别强调BroadcastReceiver的执行时间,意味着你要:分散工作到后台线程里,像保存设置或者注册Notification。执行密集任务(intensive tasks),应该用IntentService。

提示:你可以用StrictMode帮你找到在UI线程上潜在的耗时操作