使用Handler线程避免在SCREEN_ON上发生ANR



获取ANR执行Intent.ACTION_SCREEN_ON的阻塞/重调用。下面是代码

private static BroadcastReceiver mScreenOnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_ON)) {              
// Blocking operation
}
}
}

为了避免ANR,我计划在工作线程内移动阻塞操作。以下代码是否有助于避免ANR?

private static BroadcastReceiver mScreenOnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_ON)) {              
new Handler().post(new Runnable() {
@Override
public void run() {
//Blocking operation
}
});
}
}
}

No。BroadcastReceiver是短命的。不能保证承载BroadcastReceiver的操作系统进程能够运行足够长的时间来执行这些代码。不仅如此,你将在Main (UI)线程上运行这段代码,你不能阻塞(你的Runnable不会在"工作线程"中运行,它将在Main (UI)线程中运行)。

你的BroadcastReceiver应该启动一个Service,它可以运行一个后台(工作)线程,可以执行你的阻塞操作。或者你可以使用JobScheduler来调度这个操作(如果它适合你的目的)。

最新更新