i want to enable and disable broadcast receiver for boot complete on button click.. The receiver shouldn't respond until button is clicked once. i did see some similar questions but non of the answers worked.. please help...
i tried this code but didn't work..
PackageManager pm = getApplicationContext().getPackageManager();
ComponentName componentName = new ComponentName("mypackage", ".receivername");
pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
Try this
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PackageManager pm = Re_editActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(currentActivity.this, name_of_your_receiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "activated", Toast.LENGTH_LONG).show();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PackageManager pm = Re_editActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(currentActivity.this, name_of_your_receiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "cancelled", Toast.LENGTH_LONG).show();
}
});
here button1 is used to activate broadcast receiver and button2 to deactivate it Also u need to register your broadcast receiver in manifest file and set
<receiver android:name="name_of_your_receiver" android:enabled="false">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Sample Code where you can register your receiver inside onCreate Method and onDestroy Method you unregister it,
private BroadcastReceiver receiver;
@Overrride
public void onCreate(Bundle savedInstanceState){
// your oncreate code
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
filter.addAction("SOME_OTHER_ACTION");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
}
registerReceiver(receiver, filter);
}
Remember to run this in the onDestroy method:
@Override
protected void onDestroy() {
unregisterReceiver(receiver); //unregisterReceiver can be anywhere based on your requirement
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With