Dynamically registering a broadcast receiver [duplicate]

跟風遠走 提交于 2019-12-06 04:46:51

问题


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



来源:https://stackoverflow.com/questions/5776165/dynamically-registering-a-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!