Send string from service to activity

前端 未结 3 2062
情话喂你
情话喂你 2020-12-09 18:29

I\'m trying to send string from service to my main activity with broadcast. I have read in a few forums that there are 2 ways to use broadcast. One is to register the activi

3条回答
  •  隐瞒了意图╮
    2020-12-09 19:16

    You can use LocalBroadcastManager to achieve what you want. Like in your service call this method when you want to send the data.

    private static void sendMessageToActivity(String msg) {
      Intent intent = new Intent("intentKey");
      // You can also include some extra data.
      intent.putExtra("key", msg);
      LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
    

    In your Activity register a Receiver in onCreate()

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, new IntentFilter("intentKey"));
    

    And out of onCreate() this code.

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          // Get extra data included in the Intent
          String message = intent.getStringExtra("key");
          tvStatus.setText(message);
          // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
      }
    };
    

提交回复
热议问题