我希望用户能够通过点击按钮取消注册/注册广播接收器。
第一次按下该按钮时,广播接收器会被注册,并且在连接设备时会出现干杯。
我的问题是当我再次按下按钮时,广播接收器没有像我指定的那样取消注册。
有人可以检查mylogic是否有问题,或者向我解释是否有其他方法可以检测usb拔出/插入的时间?
谢谢。
btn.setOnClickListener(new View.OnClickListener() {
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int plugged = intent.getIntExtra(
BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(),
"Connected to USB", Toast.LENGTH_SHORT).show();
}
if (plugged != BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(),
"Disconnected from USB", Toast.LENGTH_SHORT)
.show();
}
}
};
@Override
public void onClick(View v) {
int mReceiver = 0;
mReceiver++;
if (mReceiver % 2 == 1) {
IntentFilter filter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
}
if (mReceiver % 2 == 0) {
unregisterReceiver(receiver);
Toast.makeText(getApplicationContext(),
"Should be unregistered", Toast.LENGTH_LONG).show();
}
}
});
答案 0 :(得分:3)
由于以下几行,您的mReceiver值始终等于1:
int mReceiver = 0;
mReceiver++;
我假设mReceiver是一个实例变量,在这种情况下它应该只是:
mReceiver++;
更好的是,创建一个名为isRegistered
的布尔值。
@Override
public void onClick(View v) {
if (!isRegistered) {
IntentFilter filter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
isRegistered = true;
}
else {
unregisterReceiver(receiver);
isRegistered = false;
}
}