美文网首页
安卓8.0之后开启服务问题

安卓8.0之后开启服务问题

作者: 有爱的梦_大东 | 来源:发表于2020-03-27 18:07 被阅读0次

1.安卓8.0之后开启服务google规定只能是前台服务,不能后台偷做后台工作,所以需要的是startForegroundService(intent)

1.开启时机代码

Intent intent = new Intent(LaunchActivity.this, YourService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
} else {
           startService(intent);
 }

2.service中onCreate代码

if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            val nm =  getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            //数字是随便写的“2”,
            nm.createNotificationChannel(NotificationChannel("2", "App Service", NotificationManager.IMPORTANCE_DEFAULT))
            val notification =  NotificationCompat.Builder(this, "2")
//          .setContentTitle("New Message")//可以不用
//          .setContentText("You've received new messages.")//可以不用
//          .setSmallIcon(R.drawable.ic_launcher_foreground)//可以不用
//          .setChannelId("2")//可以不用
                    .build()


            //其中的2,是也随便写的
            startForeground(2 ,notification)
        }

3.注意事项

1.在安卓9.0后有服务权限请求,需要在manifest加权限

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

2.在服务中的代码里加入了Notification会在有通知存在。想要去掉可以使用stopForeground(true)

相关文章

网友评论

      本文标题:安卓8.0之后开启服务问题

      本文链接:https://www.haomeiwen.com/subject/ntlruhtx.html