即使应用程序被终止,我也想开始一项活动。低于 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)
}
}
}
}
答案 0 :(得分:0)
您可以在此处使用 PendingIntent。
它带有像这样的不同用例。
您可以在互联网上找到大量关于它的示例。只需谷歌它 & 它会让你完成工作。 :)