Android 穩(wěn)定運行的服務(wù) 前臺服務(wù)

由于Android8.0版本開始,應(yīng)用的后臺功能被大幅削減,服務(wù)隨便可能被系統(tǒng)殺死,為了能保持服務(wù)長期運行,使用前臺服務(wù)。

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", "前臺服務(wù)通知", 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)
    }
}

這樣,在服務(wù)創(chuàng)建的時候就會在手機狀態(tài)欄出現(xiàn)服務(wù)通知,不會被系統(tǒng)不明不白殺死,又能讓用戶自己控制。

另外在Android9.0開始,使用前臺服務(wù)需要進行權(quán)限聲明。

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容