1

I have a Broadcast Receiver in my app:

public class Ringmodechange extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}

My AndroidManifest.xml:

<receiver
    android:name=".Ringmodechange"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.media.RINGER_MODE_CHANGED" />
    </intent-filter>
</receiver>

Is it possible to register and unregister a BroadcastReceiver with java code? This receiver is working in the background.

Actually, I want to register and unregister the receiver everytime a user clicks a button.

erfan
  • 81
  • 1
  • 11

2 Answers2

2

Yes, it is possible using a ComponentName and the PackageManager.


Enabling your BroadcastReceiver:

ComponentName component = new ComponentName(context, Ringmodechange.class)
context.getPackageManager().setComponentEnabledSetting(component, PackageManager. COMPONENT_ENABLED_STATE_ENABLED , PackageManager.DONT_KILL_APP);

To disable it:

ComponentName component = new ComponentName(context, Ringmodechange.class)
context.getPackageManager().setComponentEnabledSetting(component, PackageManager. COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);
Evin1_
  • 12,292
  • 9
  • 45
  • 47
  • thank you bro so i should remove the manifest code and use this code or this codes is for register and unregister reciver?? can you more explane for me?? – erfan Jun 11 '16 at 16:38
  • Nope, keep the code in the Manifest and use the snippets when you receive a user click. – Evin1_ Jun 11 '16 at 16:40
  • 1
    Thanks this is work perfectly. but can you just explane for me what does this code work?? unregister the reciver or ...... – erfan Jun 11 '16 at 17:06
0

There are a couple of good posts covering this topic.

Essentially, in your onStart and onStop lifecycle methods is where you should be making your changes.

In the documentation for BroadcastReceivers, they discuss the lifecycle of the broadcasts as well as security implications.

Community
  • 1
  • 1
SQLiteNoob
  • 2,958
  • 3
  • 29
  • 44