简体   繁体   中英

Pass data from Application to the Activity

My android Application class instance is listening to the third-party service for the event. Then the event is coming out, I need to notice my Activity about it. What is the right way to do that? I know about startActivity() method, but my Activity is running yet!

If the communication is local to your app you can use local broadcasts .

For communication between components you can also use EventBus (Android-library). It is really easy to use and implement (takes less than a minute to understand how it works) and is great in performance.

Use Local broadcast events with LocalBroadcastManager - see this tutorial for more information.

I have copied relevant bits of code from the above tutorial for your convenience.

To notify your already running activity about your event, try the following:

  1. Send a broadcast intent from your Application class when you receive the event.

     Intent intent = new Intent("my-event"); // add data intent.putExtra("message", "data"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
  2. Register a BroadcastReceiver in your Activity which will handle the received Intents for your event. Add the following code to your Activity:

     @Override public void onResume() { super.onResume(); // Register mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("my-event")); } // handler for received Intents for the "my-event" event private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getStringExtra("message"); Log.d("receiver", "Got message: " + message); } }; @Override protected void onPause() { // Unregister since the activity is not visible LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); super.onPause(); } 

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