Reputation: 53
I have a service listening to some events from server. A service has START_STICKY flag that makes him restart when it's killed by OS. When service receive an event i have two scenarios. First, if activity isn't killed i need to send result to local broadcast receiver and update UI. Second, if it's killed by OS i want to recreate it and send data in bundle.
But i don't know how to recognize that android killed my activity. onDestroy activity event doesn't come in this situation.
@Override
public void onComplete(CurrentOrdersResponse response) {
if (response == null) {
return;
}
boolean isActivityDestroyed = mPreferences.getBoolean(MainActivity.IS_MAIN_ACTIVITY_DESTROYED_PREF_KEY, false);
if (!isActivityDestroyed)
sendResult(response.getResJSONStr(), CURRENT_ORDERS_ACTION);
else {
Intent intent = new Intent(this, MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(extras);
startActivity(intent);
}
int resCode = response.getResCode();
Log.i(LOG_TAG, "Service resCode" + " " + resCode);
}
Upvotes: 2
Views: 2668
Reputation: 38309
It sounds like you are using LocalBroadcastManager
. That's good. Its sendBroadcast() method returns a boolean indicating if a registered receiver was found. You can use that result to determine if your receiving activity (MainActivity) exists and has registered to receive the broadcast.
When your service has an event to send to MainActivity, first try to send the event using sendBroadcast()
. If it returns true, your done. If it returns false, the activity is not registered and must be created using startActivity()
, with the event passed as an extra, as shown in your posted code.
Upvotes: 5