Android 稳定运行的服务 前台服务

由于Android8.0版本开始,应用的后台功能被大幅削减,服务随便可能被系统杀死,为了能保持服务长期运行,使用前台服务。

class MyService : Service(){

    override fun onCreate() {
        super.onCreate()
        
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val notificationChannel = NotificationChannel("my_service", "前台服务通知", NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(notificationChannel)
        }
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
        val notification = NotificationCompat.Builder(this, "my_service")
                .setContentTitle("this is content title")
                .setContentText("this is content text")
                .setSmallIcon(R.drawable.small_icon)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.large_icon))
                .setContentIntent(pendingIntent)
                .build()
        startForeground(1,notification)
    }
}

这样,在服务创建的时候就会在手机状态栏出现服务通知,不会被系统不明不白杀死,又能让用户自己控制。

另外在Android9.0开始,使用前台服务需要进行权限声明。

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容