Im creating an app in which i do a task when i receive a call (detect RINGING state with a BROADCASTRECEIVER ).My question is that,can I register and unregister (literally;ON and OFF) his broadcastreceiver from an activity having 2 buttons;say one for ON and another for OFF?
Does it require the BROADCASTRECEIVER to be declared inside the activity?If I do so,can i register and unregister it,via the activity?
this is the way i would do it:
ReplyDeleteI define a separate BroadcastReceiver and define it in android manifest rather than using it in your activity. Doing this allows my broadcast receiver to work independent of activity
Write an activity with two buttons (On/Off) and save its action as a flag in shared preferences
update the broadcastreceiver's onReceive method and check if a flag in preference is set to true then handle the intent, otherwise ignore it
//use to enable the broadcast receiver
ReplyDeletepackageManager.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
//use to disable the broadcast receiver
packageManager.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
please try this subru