prijin prijin - 3 years ago 131
Android Question

Dynamically registering a broadcast receiver

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);
}
}

Answer Source

Check out this question. The answer includes an appropriate example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download