android8.0对后台进程开启服务以及广播的影响

桌面部件需要开启服务请求后台数据,刷新桌面部件view

//权限申请
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    
   //开启服务   android8.0开启和不在前台进程中
    val intentService = Intent(context, xxxService::class.java)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !AppUtils.isAppForeground()) {
        context?.startForegroundService(intentService)
    } else {
        context?.startService(intentService)
    }


//
class xxxxService : Service() {
  ...
    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !AppUtils.isAppForeground()) {
            val builder = NotificationBuilder(this)
            val notification = builder.buildNotification()
            startForeground(NotificationBuilder.NOTIFICATION_ID, notification)
        }
    }
    ....
    }
    //
        <service android:name=".widget.s6.service.xxxxService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.xxxx.xxxx.xxx"/>
            </intent-filter>
        </service>
        //
        
class NotificationBuilder(private val mContext: Context) {

    private val mNotificationManager: NotificationManager
    fun buildNotification(): Notification {
        if (shouldCreateNowPlayingChannel()) {
            createNowPlayingChannel()
        }
        val builder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
        return builder.setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle("xxxxtitle")
            .setOnlyAlertOnce(true)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build()
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun nowPlayingChannelExists(): Boolean {
        return mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID) != null
    }

    private fun shouldCreateNowPlayingChannel(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !nowPlayingChannelExists()
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun createNowPlayingChannel() {
        val channel = NotificationChannel(
            NOTIFICATION_CHANNEL_ID,
            "当前播放",
            NotificationManager.IMPORTANCE_LOW
        )
        channel.description &
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值