Dhaval Patel
Dhaval Patel

Reputation: 340

Android 13 ForegroundServiceDidNotStartInTimeException

Fatal Exception: android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{f294fe6 u0 file_path}
   at android.app.ActivityThread.generateForegroundServiceDidNotStartInTimeException(ActivityThread.java:2272)
   at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2243)
   at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException()
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2522)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loopOnce(Looper.java:223)
   at android.os.Looper.loop(Looper.java:324)
   at android.app.ActivityThread.main(ActivityThread.java:8634)
   at java.lang.reflect.Method.invoke(Method.java)

Getting this crash for few users after app target sdk was updated to 33

enter image description here

All for android 13 and mostly happens when app is in background, not device specific

I have startForeground(id, notification) soon after getting intent at onStartCommand

Upvotes: 4

Views: 6272

Answers (2)

Hpsaturn
Hpsaturn

Reputation: 2742

I found that the problem could be because the service takes long time to start your internal task. For this, is better try to run it, in an sub thread, like this:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    notificationSetup(); // here, don't forget perform startForeground()

    new Thread(new Runnable() {
        @Override
        public void run() {
            // your intensive code
        }
    }).start();


    return START_STICKY;  
}

and in your MainActivity, something like this:

public void startMyForegroundService() {
  Intent service = new Intent(this, RecordTrackService.class);
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(service);
  } else {
    startService(service);
  }
}

Upvotes: 0

Mohammad Azizi
Mohammad Azizi

Reputation: 31

This happens when you call startForegroundService(intent) and then you call startForeground(int,notification) in onCreate when the operation takes more time to execute then it throw this exeption or you start and stop service immediately ...

Try to call startForeground in onCreate because you have only 5s to call it otherwise system will stop service and don't start and stop service immediately.

Use startForegroundService() for both stopping and starting service to ensure that we are stopping service when service is completely started

MyApplication.returnContext().startForegroundService(new Intent(MyApplication.returnContext(), IndicatorService.class).putExtra("stops",true));

And then add check in onStartCommand

if(intent.getBooleanExtra("stops",false)){
                stopSelf();
            }

Hope this help you.

Upvotes: 2

Related Questions