Android: Check if activity is destroyed by a system from service

会有一股神秘感。 提交于 2019-12-20 02:55:12

问题


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);
    }

回答1:


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.



来源:https://stackoverflow.com/questions/34294812/android-check-if-activity-is-destroyed-by-a-system-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!