Dynamically registering a broadcast receiver [dupl

2020-07-18 03:25发布

问题:

I registered my broadcast receiver like this(given below) in the manifest file. its working fine.

<receiver android:name="MyIntentReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.HOME" />
    </intent-filter>
</receiver>

But it stays registered through out. Ie whenever the phone is booting my application starts. But I want only one time.

I've understood that if it is registered dynamically, we can achieve this. i.e. we can unregister it in onPause() or onDestroy() method. If it's possible, please give me the code to do that. I am a newbie in this. Any help would be appreciated. Thank you.

I tried the following code, but it was of no use:

public class BeforeReboot extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.beforereboot);
    }
    private BroadcastReceiver myBroadcastReceiver =  new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent startupBootIntent = new Intent(context,
                AfterRebootDynamic.class);//new class to be launched
            startupBootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(startupBootIntent);
        }
    };

    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.BOOT_COMPLETED");
        filter.addCategory("android.intent.category.HOME");
        registerReceiver(myBroadcastReceiver, filter);
    }

    public void onPause() {
        super.onPause();
        unregisterReceiver(myBroadcastReceiver);
    }
}

回答1:

Steps

  1. Create a Intent Filter. IntentFilter intentFilter = new IntentFilter(CUSTOM_INTENT)
  2. Create a Broadcast Reciever Receiver receiver = new Receiver() where Reciever class extends BroadcastReciever Class
  3. Register BroadcastReceiver using registerReceiver() by :

    LocalBroadcastManager : For Recieving local intents i.e within the same application.

    Context : For Recieving remote intents also .

  4. Call unRegisterReceiver() to unregister BroadcastReceiver

    Refer this tutorial for more details & source code :Create Simple Dynamic Recievers