5

I'm building a music app, everything is alright but recently, app will be crashed. When see my crash list on fabric so notice that only happens on os 9.

Fatal Exception: java.lang.RuntimeException Unable to start activity ComponentInfo{android.store/android.store.MusicPlayerActivity}: java.lang.IllegalStateException: Not allowed to start service Intent { act=android.store.mediaservice.PLAY_PLAYLIST cmp=android.store/.mediaservice.MediaService (has extras) }: app is in background uid UidRecord{1aba0fa u0a192 SVC bg:+5m42s914ms idle change:uncached procs:1 seq(0,0,0)}

I couldn't reproduce that issue because it rarely happen. These following code cause crash :

if (intent.hasExtra(MediaService.EXTRAS_INDEX)) {
    Intent i = new Intent(getApplicationContext(), MediaService.class);
    i.setAction(MediaService.ACTION_PLAY_PLAYLIST);             i.putExtra(MediaService.EXTRAS_INDEX, intent.getIntExtra(MediaService.EXTRAS_INDEX, 0));
    i.putExtra(MediaService.EXTRAS_TRACK_IDLIST, intent.getStringArrayExtra(MediaService.EXTRAS_TRACK_IDLIST));     startService(i);
} else if (intent.hasExtra(EXTRAS_SHUFFLE)) {
    Intent i = new Intent(getApplicationContext(), MediaService.class);
    i.setAction(MediaService.ACTION_PLAY_SHUFFLE);
    i.putExtra(MediaService.EXTRAS_TRACK_IDLIST, intent.getStringArrayExtra(MediaService.EXTRAS_TRACK_IDLIST));
    startService(i);
}

So what's the main reason cause crash and solution for this ?

shizhen
  • 12,251
  • 9
  • 52
  • 88
Le Minh
  • 135
  • 1
  • 1
  • 12
  • 2
    https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexception-not-allowed-to-start-service-inten – ADM Jul 12 '19 at 04:58
  • 2
    @Le Minh , android O and above does not allow to run service in background . You need to use startForegroundService(i) instead of StartService(i) and attach a notification to the foreground service – Ashish singh Jul 12 '19 at 04:59
  • so why that issue is occur on android Pie not android O ? – Le Minh Jul 12 '19 at 06:41
  • 1
    Possible duplicate of [Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent](https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexception-not-allowed-to-start-service-inten) – Adam Higgins Oct 21 '19 at 11:45

1 Answers1

6

For pre Oreo devices, you have to use startService(), but from Oreo onwards devices, you have to use startForgroundService(). Check the below sample code.

   ContextCompat.startForegroundService(new Intent(context, MyService.class));

Background Execution Limits in Android Oreo. ContextCompat makes Build.Version check inside and calls right method

To show the notification to the user use below code in your service.

@Override
public void onCreate() {
    super.onCreate();
    startForeground(NOTIFICATION_ID,new Notification());
}
Kirill Vashilo
  • 1,559
  • 1
  • 18
  • 27
Sabyasachi
  • 3,499
  • 2
  • 14
  • 21