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!
Asked
Active
Viewed 34 times
0
-
Are you talking about broadcasts? If so check this. https://developer.android.com/reference/android/content/BroadcastReceiver.html – Malith Lakshan May 21 '16 at 13:21
2 Answers
1
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.
1
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:
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);
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(); }

Clive Seebregts
- 2,004
- 14
- 18