【发布时间】:2021-10-12 19:21:26
【问题描述】:
我有一个广播接收器,可以检测 USB 设备何时连接/分离。该应用程序在设备连接时打开,但是当我多次断开/连接设备到我的 android 时,我收到以下 ANR 错误:有谁知道是什么原因造成的? ANR error
这是我的广播接收器代码:
String USB_TAG = "USB_TAG";
String BROADCAST_TAG = "BROADCAST_TAG";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(BROADCAST_TAG, "BroadcastReceiver Event");
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
Log.d(BROADCAST_TAG, "BroadcastReceiver DEVICE ATTACHED");
Toast.makeText(context, "Device Detected", Toast.LENGTH_SHORT).show();
new Thread(() -> {
try {
if(MainActivity.eMRO_Backend != null) {
if (MainActivity.eMRO_Backend.threadsClosed) {
MainActivity.eMRO_Backend = new eMRO_Backend(context);
}
}
} catch (Exception e){
Log.d(BROADCAST_TAG, "BroadcastReceiver attach ex: " + e.getMessage());
}
}).start();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
Toast.makeText(context, "Device Not Detected", Toast.LENGTH_SHORT).show();
new Thread(() -> {
Looper.prepare();
try {
MainActivity.powerStatusQueue.put(false);
MainActivity.laserKeyStatusQueue.put(false);
if(MainActivity.eMRO_Backend != null)
MainActivity.eMRO_Backend.shutDownThreads();
} catch (Exception e) {
Log.d(BROADCAST_TAG, "BroadcastReceiver detach ex: " + e.getMessage());
}
}).start();
}
}
}
【问题讨论】:
-
Looper.prepare()看起来很吓人。 -
没有意义。 ANR 表示
onReceive()运行时间过长。您的代码看起来根本不应该运行很长时间。添加一些日志以查看来自onReceive()的入口和出口。此外,这是不好的做法。您不应该在广播接收器中启动线程。您应该改为启动服务。 -
@CommonsWare OP 在一个新的
Thread中调用Looper.prepare()。一般来说,这没有什么问题。 -
@DavidWasser 我也尝试使用 AsyncTask ,但遇到了同样的错误。当我得到 ANR 时,我在 onReceive 方法中看不到任何日志语句。
-
@DavidWasser 你是对的,这是我的主要活动中的一个功能导致了这个问题。谢谢!!
标签: android broadcastreceiver android-pendingintent android-anr-dialog