felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.78k stars 581 forks source link

IllegalStateException when restarting the app #330

Open uvindu9412 opened 3 years ago

uvindu9412 commented 3 years ago

If the serial connection is active and if the mobile screen locks once the user unlock the app and come back to the app it crashes with the below exception. Happens after android 9 versions

java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.myapp.ser\/com.myapp.beam.usbSerial.UsbService }: app is in background uid UidRecord{9bd2493 u0a736 TPSL idle procs:1 seq(0,0,0)} android.app.ContextImpl.startServiceCommon(ContextImpl.java:1795) at android.app.ContextImpl.startService(ContextImpl.java:1740) at android.content.ContextWrapper.startService(ContextWrapper.java:738) at android.content.ContextWrapper.startService(ContextWrapper.java:738) at com.ackcio.beam.DashboardActivity$startService$1.run(DashboardActivity.kt:1271) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:246) at android.app.ActivityThread.main(ActivityThread.java:8506) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

SimonWilks commented 3 years ago

@uvindu9412 I had the same issue for a while and spent some time looking into it today. In my case this was also happening after the screen locked after which the activity manager would eventually shutdown my services.

When you go to unlock the phone it will immediately resume your activity which will try to start the service but until your phone is unlocked the app will still be in background mode. This triggers the IllegalStateException.

In my case all I needed to do was the catch this exception where it fails (context.startService) and abort trying to connect and my app is already retrying should the connection not be established, so once the app is in the foreground it will connect as usual.

If you want to keep the service running you need to look into background vs foreground services etc.