android - Broadcast receiver not unregistering -


i want give user ability unregister/register broadcast receiver click of button.

when button pressed first time, broadcast receiver registered , toast comes when device connected.

my problem when press button again, broadcast reciever not unregistering specified.

can please check if there wrong mylogic, or explain me if there approach detecting when usb 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 usb", toast.length_short).show();                      }                     if (plugged != batterymanager.battery_plugged_usb) {                         toast.maketext(getapplicationcontext(),                                 "disconnected 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 unregistered", toast.length_long).show();                 }              }         }); 

your mreceiver value equal 1 because of these lines:

            int mreceiver = 0;             mreceiver++; 

i assume mreceiver instance variable, in case should be:

            mreceiver++; 

better still, create 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;             }          } 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -