gpt4 book ai didi

java - 使用蓝牙服务时如何避免出现 "Are you missing a call to unregisterReceiver()?"错误?

转载 作者:行者123 更新时间:2023-12-02 10:31:49 25 4
gpt4 key购买 nike

我收到以下错误:

12-02 13:35:55.990 10977-10977/com.example.btpdemo76 E/ActivityThread: Activity com.zkc.pinter.activity.MainActivity 已泄露 IntentReceiver com.zkc.helper.printer.BlueToothService$1@4179571最初是在这里注册的。您是否错过了对 unregisterReceiver() 的调用? android.app.IntentReceiverLeaked:Activity com.zkc.pinter.activity.MainActivity 已泄露最初在此处注册的 IntentReceiver com.zkc.helper.printer.BlueToothService$1@4179571。您是否错过了对 unregisterReceiver() 的调用? 在 android.app.LoadedApk$ReceiverDispatcher。(LoadedApk.java:1351) 在 android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:1132) 在 android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1421) 在 android.app.ContextImpl.registerReceiver(ContextImpl.java:1394) 在 android.app.ContextImpl.registerReceiver(ContextImpl.java:1382) 在 android.content.ContextWrapper.registerReceiver(ContextWrapper.java:609) 在 com.zkc.helper.printer.BlueToothService.ScanDevice(BlueToothService.java:87) 在 com.zkc.helper.printer.bt.BtService$2.run(BtService.java:86)

这是我的代码

公共(public)无效扫描(){

    if (!mBTService.IsOpen()) {
mBTService.OpenDevice();
return;
}
if (mBTService.getState() == STATE_SCANING)
return;

new Thread() {
public void run() {
mBTService.ScanDevice();
}
}.start();
}









public void ScanDevice() {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver, filter); //showing error here

filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
context.registerReceiver(mReceiver, filter);
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
}
setState(PrinterClass.STATE_SCANING);
// Request discover from BluetoothAdapter
adapter.startDiscovery();
}

最佳答案

当您动态添加接收器时,请记住在 onPause() 方法中取消注册同一接收器:

@Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}

注意:不要将以上代码放在 onStop() 方法中,因为:

this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

关于java - 使用蓝牙服务时如何避免出现 "Are you missing a call to unregisterReceiver()?"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com