赞
踩
Android O开始,系统不允许后台应用创建后台服务,要改为使用前台服务,并且应用5S内要调用该服务的startForeground()方法,否则系统将停止服务并报ANR异常:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceStartIntent)
} else {
startService(serviceStartIntent)
}
调用startForeground(),需要传一个notification对象,在API 26以上中要使用Notification.Builder(Context, String) ,并且要指明 NotificationChannel 的Id. 如果不加则会提示:Developer warning for package xxx,Failed to post notification on channel “null”
/**
* @see Service.onStartCommand
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "001"
val channelName = "myChannel"
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
channel.lightColor = Color.BLUE
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
val notification: Notification
notification = Notification.Builder(applicationContext, channelId)
.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
} else {
startForeground(101, Notification())
}
return START_STICKY
}
/**
* @see Service.onDestroy
*/
override fun onDestroy() {
stopForeground(true)
super.onDestroy()
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。