Android 8.0 后台Service限制

Android O 后台启动Service崩溃问题

  • 在 Android 8.0 (API26)之前,创建前台服务的方式通常是先创建一个后台服务,然后将该服务推到前台。
  • Android 8.0 (API26)有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。
  • 在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。
  • 如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

解决方法

  • 将 调用 startService启动Service 改为调用 startForegroundService
public static void start() {
        Intent intent = new Intent(AppContext.me(), ScoreRefreshServer.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            AppContext.me().startForegroundService(intent);
        } else {
            AppContext.me().startService(intent);
        }
}
  • 在service的onCreate方法中调用startForeground()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
               //NotificationCompat.Builder builder =
               //new NotificationCompat.Builder(this, CHANNEL_ID)
               //         .setContentTitle("")
               //         .setContentText("");
            NotificationChannel channel = new NotificationChannel(AppEnv.UMENG_CHANNEL, getString(R.string.yoyo_name), NotificationManager.IMPORTANCE_MIN);
            channel.enableVibration(false);//去除振动

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) manager.createNotificationChannel(channel);

            Notification.Builder builder = new Notification.Builder(getApplicationContext(), AppEnv.UMENG_CHANNEL)
//                    .setContentTitle("正在后台运行")
                    .setSmallIcon(R.mipmap.logo);
            startForeground(1, builder.build());//id must not be 0,即禁止是0
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转载请注明出处:https://www.jianshu.com/p/77fe505e2287github:http...
    rushjs阅读 7,872评论 2 26
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,509评论 2 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,257评论 25 708
  • 【Android Service】 Service 简介(★★★) 很多情况下,一些与用户很少需要产生交互的应用程...
    Rtia阅读 3,272评论 1 21
  • 大学生活中深入你骨髓里那些摸不着抹不去的记忆是什么?是夏天的傍晚走过浴室时飘来的洗发水味道?还是路上成群结队闪瞎直...
    范儿青年阅读 986评论 6 1

友情链接更多精彩内容