4

According to the background execution limits introduced in Android Oreo, calling startService when the app is in background should throw an IllegalArgumentException. Check this question: Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent.

I created a sample app targetting Android Oreo that does the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            startService(new Intent(MainActivity.this, MyService.class));
        }
    }, 5000);
}

Then I start the app and after press the home button immediately bringing the app to the background state. But the exception is not thrown. How can it be? I expect the app to crash in this case.

16
  • Are you running the app on an Oreo device? Commented Sep 13, 2018 at 15:21
  • @TheWanderer I'm running the app on a Pixel 2 with Android 9 (Pie) installed. Commented Sep 13, 2018 at 15:29
  • 1
    I think there is some timeout (maybe 15s). Try to set that delay to 20000. Commented Sep 13, 2018 at 15:31
  • OK, so it should be happening. Can you point to where the docs say it should throw that Exception? Commented Sep 13, 2018 at 15:31
  • @egoldx that's a different timeout. This Exception should apparently be thrown as soon as startService() is called. Commented Sep 13, 2018 at 15:31

1 Answer 1

3

According to Google's documentation on background service limitations:

While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services.

Generally I've found the window to be something around a minute, but that can certainly be different for others.

Take a look at your overall device logs (run adb logcat from the command line or turn off filters in Android Studio's Logcat window) after you've backgrounded the app and look for something like:

09-26 13:25:37.150 4741 4756 W ActivityManager: Stopping service due to app idle: u0a267 -1m12s700ms com.example/.MyService

Any request to start a service after that should cause the exception. I'm guessing you'll need to up the timeout to something closer to a minute or two.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.