Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

broadcastreceiver - Android - how to unregister a receiver created in the manifest?

I know about using registerReceiver and unregisterReceiver in Java code for dealing with receivers, but let's say I have the following in my manifest:

    <receiver android:name=".headsetHook">
        <intent-filter android:priority="99999999999">
            <action android:name="android.intent.action.ACTION_HEADSET_PLUG" />
        </intent-filter>
    </receiver>

Is there a way I could unregister this somewhere in Java code? Could I give it an id attribute or something and then get it and unregister it? I ask because I want my app to do something only on the first time this action happens, then unregister it and re-register it later in Java.

Hope I made that clear, thanks for any help.

question from:https://stackoverflow.com/questions/6529276/android-how-to-unregister-a-receiver-created-in-the-manifest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the PackageManager to enable/disable a BroadcastReceiver in declared in the Manifest. The Broadcast Receiver will get fired only when it is enabled.

Use this to create a Component

ComponentName component = new ComponentName(context, MyReceiver.class);

Check if the Component is enabled or disabled

int status = context.getPackageManager().getComponentEnabledSetting(component);
if(status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
    Log.d("receiver is enabled");
} else if(status == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
    Log.d("receiver is disabled");
}

Enable/Disable the component(Broadcast Receiver in your case)

//Disable
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);
//Enable
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED , PackageManager.DONT_KILL_APP);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...