我正在构建一个应用程序,在后台做一些处理。
我的代码:-
@RequiresApi(Build.VERSION_CODES.N)
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Intent notificationIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("Welcome To TestApp")
.setContentIntent(pendingIntent).build();
// startForeground(105, builder.setNotificationSilent().build())
// Handler
eventLoop = object : Runnable {
override fun run() {
println("Inside Run.") // does not prints when `startForeground` is commented, and the code is broken.
handler.postDelayed(this, 1000) // Subsequent runs
}
}
CoroutineScope(IO).launch {
handler.post(eventLoop) // first launch
}
return START_STICKY
}
当startForeground
没有注释时,上面的代码可以正常工作。这是显示sticky通知的函数。我在文档中读到了这一点,从它的外观来看,如果我的服务被杀死以回收更多内存,我可以接受。我已经设置了我的工作管理器,如果被杀死,它会自动启动服务。
run
功能不会在移动应用程序到后台或杀死它时执行,即使通知栏被拉下。
这是抛出的异常。
I/in.zoffers(20132): Wrote stack traces to tombstoned
F/crash_dump64(21223): crash_dump.cpp:465] failed to attach to thread 567: Permission denied
D/AndroidRuntime(20132): Shutting down VM
E/AndroidRuntime(20132): FATAL EXCEPTION: main
E/AndroidRuntime(20132): Process: in.zoffers, PID: 20132
E/AndroidRuntime(20132): android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{737e848 u0 in.zoffers/.AutoOffersService}
E/AndroidRuntime(20132): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2151)
E/AndroidRuntime(20132): at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(20132): at android.os.Looper.loop(Looper.java:228)
E/AndroidRuntime(20132): at android.app.ActivityThread.main(ActivityThread.java:7782)
E/AndroidRuntime(20132): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(20132): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/AndroidRuntime(20132): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
W/MixpanelAPI.SysInfo(20132): Permission READ_PHONE_STATE not granted. Property $radio will not be available.
Lost connection to device.
这里到底发生了什么?因为,我可以接受我的服务在内存管理时被杀死,所以我不需要startForeground
。
我在文档中看到了它,从它的外观来看,如果我的服务被杀死以回收更多内存,我可以接受
在Android 8.0+上它将在60秒内被杀死,除非你将它设置为startForeground()
的前台服务。
这里到底发生了什么?
您呼叫startForegroundService()
启动服务。这意味着您需要在ANR时间段(约15秒IIRC)内调用startForeground()
。如果您不想调用startForeground()
,请不要使用startForegroundService()
启动服务。