ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

android – Context.startForegroundService()然后没有调用Service.startForeground

2019-07-10 18:23:09  阅读:173  来源: 互联网

标签:android foreground-service


我的应用程序将在MainActivity的onCreate中调用startForegroundService(intent).我在服务的onCreate和startCommand中放入了startForeground(ON_SERVICE_CONNECTION_NID,notification).
但我偶尔也会收到这个错误.

Exception android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1775)
android.os.Handler.dispatchMessage (Handler.java:105)
android.os.Looper.loop (Looper.java:164)
android.app.ActivityThread.main (ActivityThread.java:6541)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:240)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767)

怎么会发生这种情况?
是否有可能在5秒内没有调用onCreate或startCommand?
如果是这样,我们应该如何调用startForegroundService而没有错误?

更新2017-12-09

我不知道为什么每个人都说这和这个问题一样:Context.startForegroundService() did not then call Service.startForeground()
你甚至可以在那里找到我的评论.

它的不同之处在于你可以在这个问题的第一行看到的.我已将startForegroundService和startForeground放在正确的位置,但它仍然随机显示此错误.

以下是Google问题跟踪器:https://issuetracker.google.com/issues/67920140

Stopping the service before this happens will cause a crash.

这是关于服务生命周期的另一个问题.
服务关闭后,可能会错误地触发断言.

解决方法:

我面临同样的问题,花了很长时间找到解决方案,你可以尝试下面的代码.如果您使用Service然后将此代码放入onCreate,则使用Intent Service,然后将此代码放在onHandleIntent中.

if (Build.VERSION.SDK_INT >= 26) {
    String CHANNEL_ID = "my_app";
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
            "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("")
            .setContentText("").build();
    startForeground(1, notification);
}

并称之为

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(getSyncIntent(context));
    } else {
        context.startService(getSyncIntent(context));
    }

标签:android,foreground-service
来源: https://codeday.me/bug/20190710/1426792.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有