问题:
项目中有个锁屏service,间隔30秒屏幕黑屏,向右滑动解锁,防止误操作的,最近客户反馈崩溃次数有点多
查看崩溃日志如下


java.lang.IllegalStateException
Not allowed to start service Intent { xxx.xxxService }: app is in background uid UidRecord{91b7553 u0a119 CAC bg:+21m20s281ms idle procs:2 seq(0,0,0)}
xxx(xxx:124)

分析:
android 8.0(O)以后后台服务做了限制

解决:
1,在manifests.xml加入权限


<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

2,启动服务startService改动


public static boolean isServiceRunning(Context ctx, final String className) {
        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> info = am.getRunningServices(200);
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo aInfo : info) {
            if (className.equals(aInfo.service.getClassName())) return true;
        }
        return false;
    }

    //启动service
    public static void startService(Context ctx, Class<?> cls) {
        if (!isServiceRunning(ctx, cls.getName())) {
            Intent intent = new Intent(ctx, cls);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                ctx.startForegroundService(intent);
            } else {
                ctx.startService(intent);
            }
        }
    }
    

3,开启通知,否则报错如下:


Context.startForegroundService() did not then call Service.startForeground()

意思是5秒内必须调用startForeground,可参考


 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null) {            
            startServiceForeground()
        }
        return START_STICKY
    }
    
  //开启通知
  @SuppressLint("NewApi")
  private fun startServiceForeground() {
        val ns: String = Context.NOTIFICATION_SERVICE
        val nm: NotificationManager = getSystemService(ns) as NotificationManager
        var nc: NotificationChannel? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            nc = NotificationChannel(
                "CoverService", "锁屏",
                NotificationManager.IMPORTANCE_LOW
            )
            nm.createNotificationChannel(nc);
            val notification = Notification.Builder(
                applicationContext, "CoverService"
            ).setContentTitle("锁屏服务中...")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.icon_logo).build()

            startForeground(2, notification)
        }
    }

 //关闭通知
 private fun stopServiceForeground() {
        stopForeground(true)
    }

 override fun onDestroy() {
        stopServiceForeground()
        super.onDestroy()
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐