I want to give the user the ability to unregister/register the broadcast receiver with the click of the button.
When the button is pressed for the first time, the broadcast receiver is registered and a toast comes up when the device is connected.
My problem is when I press the button again, the broadcast reciever is not unregistering like I specified.
Can somebody please check if there is something wrong with mylogic, or explain to me if there is another approach to detecting when usb is unplugged/plugged in?
Thank You.
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();
}
}
});
Your mReceiver value will always be equal to 1 because of these lines:
int mReceiver = 0;
mReceiver++;
I assume that mReceiver is an instance variable, in which case it should just be:
mReceiver++;
Better still, create a boolean value called 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;
}
}