前台服务不启动活动

时间:2021-07-03 17:23:15

标签: android android-activity service broadcastreceiver foreground-service

即使应用程序被终止,我也想开始一项活动。低于 API 29 没有问题,但高于 29 即使在后台触发服务 startActivity 不工作。

这是我的服务类

class MyService : Service() {

override fun onBind(intent: Intent?): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {


    if (Build.VERSION.SDK_INT >= 26) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            CHANNEL_NAME,
            NotificationManager.IMPORTANCE_DEFAULT
        )
        val manager = getSystemService(NotificationManager::class.java)
        manager.createNotificationChannel(channel)
    }

    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setContentTitle("setContentTitle")
        .setContentText("setContentText")
        .build()


    val mIntent = Intent(applicationContext, MyActivity::class.java)
    mIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    startActivity(mIntent)

    startForeground(NOTIFICATION_ID, notificationBuilder)

    return START_NOT_STICKY

}



companion object {
    const val CHANNEL_ID = "channel_id"
    const val NOTIFICATION_ID = 5
    const val CHANNEL_NAME = "channel_name"
}

}

在清单中我添加了 FOREGROUND_SERVICE 权限

 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<service android:name=".service.MyService" />
<receiver android:name=".receiver.MyReceiver" />

这是我的接收器类,在 API 29 以上我想启动一个服务

class MyReceiver : BroadcastReceiver() {


override fun onReceive(context: Context?, intent: Intent?) {

    intent?.let {
        if (Build.VERSION.SDK_INT >= 29) {
            context?.startForegroundService(Intent(context, MyService::class.java))
        } else {
            val intentActivity = Intent(context, MyActivity::class.java)
            intentActivity.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context?.startActivity(intentActivity)
        }
    }


}

}

1 个答案:

答案 0 :(得分:0)

您可以在此处使用 PendingIntent。

  • PendingIntent 是稍后执行的意图,或者换句话说,PendingIntent 指定了将来要采取的操作。 pendingIntent 和常规 Intent 之间的主要区别在于,pendingIntent 将在稍后执行,而 Normal/Regular Intent 会立即开始。

它带有像这样的不同用例。

  • PendingIntent.getActivity() — 这将启动一个 Activity,例如调用 context.startActivity()
  • PendingIntent.getBroadcast() — 这将执行广播,如调用 context.sendBroadcast()
  • PendingIntent.getService() — 这将启动一个服务,比如调用 context.startService()
  • PendingIntent.getForegroundService() — 这将启动一个前台服务,例如调用 context.startForegroundService()

您可以在互联网上找到大量关于它的示例。只需谷歌它 & 它会让你完成工作。 :)