NativeScript / sample-android-background-services

Using Android Background Services in NativeScript
63 stars 10 forks source link

App not working with Android O #21

Closed Plamen5kov closed 6 years ago

Plamen5kov commented 6 years ago

problem application error when ran and set in background on android O:

AndroidRuntime: Process: org.nativescript.bgservice, PID: 26535
AndroidRuntime: java.lang.RuntimeException: Unable to start receiver com.tns.broadcastreceivers.NotificationEventReceiver: com.tns.NativeScriptException: 
AndroidRuntime: Calling js method onReceive failed
AndroidRuntime: 
AndroidRuntime: Error: java.lang.IllegalStateException: Not allowed to start service Intent { act=ACTION_START cmp=org.nativescript.bgservice/com.tns.notifications.NotificationIntentService (has extras) }: app is in background uid UidRecord{c7b6e4b u0a93 RCVR idle procs:1 seq(0,0,0)}
AndroidRuntime:     android.app.ContextImpl.startServiceCommon(ContextImpl.java:1505)
AndroidRuntime:     android.app.ContextImpl.startService(ContextImpl.java:1461)
AndroidRuntime:     android.content.ContextWrapper.startService(ContextWrapper.java:644)
AndroidRuntime:     android.content.ContextWrapper.startService(ContextWrapper.java:644)

why this happens in android O there are new background restrictions

solution We need to replace WakefulBroadcastReceiver with JobScheduler as is recommended in the docs:

This class was deprecated in API level 26.1.0.
As of Android O, background check restrictions make this class no longer generally useful. (It is 
generally not safe to start a service from the receipt of a broadcast, because you don't have any 
guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, 
developers should use android.app.job.JobScheduler to schedule a job, and this does not require that 
the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).