How to send a custom broadcast action to receivers in manifest?

前端 未结 6 539
心在旅途
心在旅途 2020-12-15 07:48

MyReceiver.java

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
            


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 08:34

    The string itself does not matter, just need to be the same in all places and unique, I use fully qualified name of the constant.

    
        
            
        
    
    

    The receiver:

    package com.mypackage.receivers;
    
    public class MyBroadcastReceiver extends BroadcastReceiver {
        public static final String ACTION_CUSTOM = "com.mypackage.receivers.MyBroadcastReceiver.ACTION_CUSTOM";
    @Override
        public void onReceive(Context context, Intent intent) {
          if (ACTION_CUSTOM.equals(intent.getAction())) {
                // do custom action
            }
        }
    }
    

    To broadcast the intent:

    sendBroadcast(new Intent(MyBroadcastReceiver.ACTION_CUSTOM));
    

提交回复
热议问题