Android:检查活动是否被系统从服务中销毁 [英] Android: Check if activity is destroyed by a system from service
问题描述
我有一项服务可以监听服务器中的某些事件. 服务具有START_STICKY标志,使该标志在被操作系统杀死后重新启动. 服务收到事件时,我有两种情况. 首先,如果没有杀死活动,我需要将结果发送到本地广播接收器并更新UI. 其次,如果它被操作系统杀死,我想重新创建它并捆绑发送数据.
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.
但是我不知道如何识别android杀死了我的活动. 在这种情况下,不会发生onDestroy活动事件.
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);
}
推荐答案
听起来您正在使用LocalBroadcastManager
.那挺好的.其 sendBroadcast()方法返回一个布尔值,指示是否找到了已注册的接收者.您可以使用该结果来确定您的接收活动(MainActivity)是否存在并且已注册接收广播.
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.
当您的服务有要发送给MainActivity的事件时,请首先尝试使用sendBroadcast()
发送事件.如果返回true,则完成.如果返回false,则该活动未注册,必须使用startActivity()
创建,并附加传递事件,如您发布的代码所示.
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.
这篇关于Android:检查活动是否被系统从服务中销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!