前景与背景应用程序状态

时间:2019-01-29 16:28:52

标签: android

由于Android O的限制,我们不能再从后台启动服务,也无法在清单中注册Implicit BroadcastReceiver,因此我们必须在代码中进行操作:

Context.registerReceiver()

尽管该主题不再是一个新话题,但我仍然不知道确定应用程序是在前台还是在后台的可靠方法。我已经看到了一些解决方案,例如:

  • 创建一个变量并将其切换到Activity的onStart(),onStop()
  • 我也看到了ActivityManager用于此目的,但这是不建议使用的解决方案

那么,有什么方法可以确定当前应用程序处于什么状态? 我问这个问题是因为最近我在某些设备上遇到了一个奇怪的错误,我无法启动服务,这是堆栈:

java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.vc.receivers.RunTimeReceiver@299a843
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_54441(LoadedApk.java:1369)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.$m$7(Unknown Source:4)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.run(Unknown Source:39)
at android.os.Handler.handleCallback(Handler.java:795)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:6861)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:450)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.trueconf.videochat/com.vc.service.AppNotificationService }: app is in background uid UidRecord{621583 u0a323 CEM  idle change:cached procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1525)
at android.app.ContextImpl.startService(ContextImpl.java:1481)
at android.content.ContextWrapper.startService(ContextWrapper.java:650)
at com.vc.data.NotificationsStorage.updateAppStateNotify(NotificationsStorage.java:285)
at com.vc.model.NetworkStateHandler.getNetworkTypeForUsage(NetworkStateHandler.java:292)
at com.vc.model.NetworkStateHandler.performRefreshConnectionInfo(NetworkStateHandler.java:137)
at com.vc.model.NetworkStateHandler.refreshConnectionInfo(NetworkStateHandler.java:104)
at com.vc.receivers.RunTimeReceiver.onReceive(RunTimeReceiver.java:54)
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_54441(LoadedApk.java:1356)
... 9 more

我在Application的onCreate()方法之后注册了BroadcastReceiver,然后它将立即接收CONNECTIVITY_CHANGE Intent并启动服务。我以为在调用应用程序的onCreate()之后,应用程序状态为“前台”,但显然不是。

0 个答案:

没有答案