Dynamic broadcast receiver registration

I registered my broadcast receiver, like this one (below) in the manifest file. his work 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 he remains registered. Those. whenever the phone boots up, my application launches. But I want only once.

I realized that if it is registered dynamically, we can achieve this. that is, we can cancel it in the onPause () or onDestroy () method. If possible, please give me the code for this. I am new to this. Any help would be greatly appreciated. Thanks.

I tried the following code, but it was useless:

 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); } } 
+4
source share
2 answers

Pay attention to this question. The answer includes an appropriate example.

0
source

Steps

  • Create an intent filter. IntentFilter intentFilter = new IntentFilter (CUSTOM_INTENT)
  • Creating a broadcast receiver Receiver receiver = new receiver (), where the Reciever class extends the BroadcastReciever class
  • Register BroadcastReceiver with registerReceiver ():

    LocalBroadcastManager: to get local intentions in the same application.

    Context: also for remote intentions.

  • Call unRegisterReceiver () to unregister BroadcastReceiver

    Refer to this guide for more details and source code: Create simple dynamic receivers

0
source

All Articles