Search code examples
javaandroidandroid-activityandroid-lifecyclejobintentservice

Handling the Activity and Service Lifecycle


I am developing an app which will be performing some background function within a JobIntentService.

The user initiates action from Screen A. A background Intent Service is started. After the Intent service finishes its work it sends a callback to the Screen A and then Screen Sartes Screen B which utilizes the results of Intent Service.

My issue is that suppose the user starts the Action and then minimizes the app and then the Android OS clears the Screen A due to running on low Memory and then the Service sends back the callback.

My question is Now since Screen A no longer exists will it receive the callback? Is it possible to figure out that Screen A has to be cleared by Android OS so that my service can directly start Screen B?

Also, how can such a scenario be handled?

Any suggestion would be grateful.


Solution

  • The better approach is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In this case you can check in service activity is still alive or not. then take decision on that.

    Use the below method with your package name. It will return true if any of your activities is in foreground.

    public boolean isForeground(String myPackage) {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1); 
        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        return componentInfo.getPackageName().equals(myPackage);
    }