简体   繁体   中英

How to send data from IntentService to a paused Activity?

The snippets below works when the activity is at the foreground. However, MainActivity will fail to receive the broadcast when MainActivity is at the background.

How do I make sure that MainActivity will always receive the broadcast? Is there any other way to send data from IntentService to a paused activity?

In my IntentService, I'm sending data back to MainActivity like this

Intent intent = new Intent();
intent.setAction(MY_SERVICE_RESULT);
intent.putExtra(MY_SERVICE_VALUE, "hello from service");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

In my activity, I'm using BroadcastReceiver like this

public class MainActivity extends AppCompatActivity{

  BroadcastReceiver receiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    receiver = new BroadcastReceiver(){
      @Override
      public void onReceive(Context context, Intent intent) {
        String value = intent.getStringExtra(MY_SERVICE_VALUE);
      }
    };

    @Override
    protected void onResume() {
      super.onResume();
      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction(MY_SERVICE_RESULT);
      LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onPause() {
      super.onPause();
      LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }
  }
}

How do I make sure that MainActivity will always receive the broadcast?

You can't.

However you could work around it by storing the data that the IntentService wants to send to the MainActivity somewhere temporarily (eg SharedPreferences), and have MainActivity check that storage in onResume.

Possible scenario
IntentService does its thing. Checks if MainActivity is active*. If it is -> send broadcast. If it's not -> store somewhere and let MainActivity check that storage in onResume.

*you can use Application's lifecyclecallbacks to monitor activity's states to see if an activity is running and if so which one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM