本文主要是介绍android四大组件之Service(二):前台服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Android前台服务是指可以与用户交互的服务,典型示例是音乐播放器,用户可以通过开发者在通知栏设置的自定义通知来操作播放暂停上一首下一首等操作。前台服务创建示例:
class ForegroundService : Service() {override fun onBind(intent: Intent) = MyBinder()override fun onCreate() {super.onCreate()setForeground()Log.d(javaClass.simpleName, "onCreate......")}private fun setForeground() {val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagerval builder = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {var channel = manager.getNotificationChannel("MyChannel")if (channel == null) {val importance = NotificationManager.IMPORTANCE_DEFAULTchannel = NotificationChannel("MyChannel", "MyChannel", importance)manager.createNotificationChannel(channel)}Notification.Builder(this, channel.id)} else {Notification.Builder(this)}val intent = Intent(this, MainActivity::class.java)intent.flags = Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOPval pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)builder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle("这是标题").setContentText("这是内容文字").setContentIntent(pendingIntent)val notification: Notification = builder.build()manager.notify(0, notification)startForeground(0, notification)}inner class MyBinder : Binder() {fun getService(): ForegroundService = this@ForegroundService}
}
前台服务的优先级比后台服务高,系统不会轻易销毁前台服务。
这篇关于android四大组件之Service(二):前台服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!