Start context.startService(intent) on Android Pie

Viewed 2466

I start a service on my activity's onResume, it worked fine on oreo but lately I have been seeing crashes for Android P, which says "Unable to resume Activity.... Not allowed to start service intent ... app is in background..". Has anyone seen this before and where able to apply fix, any input would be much appreciated.

@Override
public void onResume() {
    super.onResume();
    Timber.v("onResume");
    Intent intent = new Intent(context, Token.class);
    intent.setAction(ACTION_FETCH_TOKEN);
    context.startService(intent);
}

just to add more context, I have not been able to reproduce the crash myself.

2 Answers

On Oreo8+ you cannot start a background service if your application is not "shown", to do that you need to edit your code like below:

    protected void onResume() {
        super.onResume(); context.startForegroundService(intent);
 } 

In onCreate() method of your service class you also need to add:

*EDITED* 2018-09-18 18:15

PendingIntent pIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("My App")
                .setContentText("Doing some work...")
                .setContentIntent(pIntent).build();
startForeground(1000, notification);

I faced the same Problem with a small Service which i didn't want to change to a ForegroundService. Then i found this workaround provided by Google for starting services in onResume:

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
    if (runningAppProcesses != null) {
        int importance = runningAppProcesses.get(0).importance;
        // higher importance has lower number (?)
        if (importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            //start your service the same way you did before in here
            startService(serviceIntent);
        }
    }

The issue has been addressed in future Android release.

There is a workaround to avoid application crash. Applications can get the process state in Activity.onResume() by calling ActivityManager.getRunningAppProcesses() and avoid starting Service if the importance level is lower than ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND. If the device hasn’t fully awake, activities would be paused immediately and eventually be resumed again after its fully awake.

Related