Pass a value from activity to broadcastreceiver and start a service from the broadcast receiver

后端 未结 2 908
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 15:21

I have an activity. It contains a button whose text changes dynamically. I would like to pass this text to my broadcast receiver which receives the sms. Now my broadcast rece

2条回答
  •  醉话见心
    2021-01-22 15:37

    if your BroadcastReceiver is defined in a separate class file, then you may simply broadcast the value to that receiver. Once the value is received, do the magic for service by using receiver's context

    Update:

    in your activity:

    Intent in = new Intent("my.action.string");
    in.putExtra("state", "activated");
    sendBroadcast(in);
    

    in your receiver:

    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
    
      Log.i("Receiver", "Broadcast received: " + action);
    
      if(action.equals("my.action.string")){
         String state = intent.getExtras().getString("state");
         //do your stuff
      }
    }
    

    in manifest xml:

    
        
            
            
            
        
    
    

提交回复
热议问题