我知道这是一个重复的问题,但仍然没有答案对我有用。crashlytics中有一些设备导致此致命崩溃。
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e16921e u0 com.abc.MyService}
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1760)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
我研究了很多关于在服务的 onCreate 中调用 startForeground(2,通知)的答案。
我已经做到了,但是崩溃没有得到解决。我无法在可用设备中复制此崩溃。
这是我的代码。
MyService.kt
class MyService : IntentService("MyService") {
init {
setIntentRedelivery(true)
}
private val wakeLock : PowerManager.WakeLock by lazy {
(getSystemService(Context.POWER_SERVICE) as PowerManager)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyService:Wakelock")
}
override fun onCreate() {
super.onCreate()
Timber.i("service created")
wakeLock.acquire(30 * 60 * 60)
Timber.i("Wake lock acquired")
// show notification
val notification = NotificationUtil.newNotification
startForeground(2, notification)
}
override fun onHandleIntent(intent: Intent?) {
//>>>>>>>>> Code Here <<<<
}
private fun finish() {
if(wakeLock.isHeld) {
wakeLock.release()
}
stopSelf()
}
override fun onDestroy() {
if(wakeLock.isHeld) {
wakeLock.release()
}
Timber.i("Wakelock released")
super.onDestroy()
Timber.i("Service finished")
}
}
在应用程序类的onCreate中启动服务。
val intent = Intent(this, MyService::class.java)
ContextCompat.startForegroundService(appContext, intent)