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
}



 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值