根据点击推送通知的具体内容选择startActivity活动可以通过以下步骤实现(使用Kotlin语言):
class NotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// 在这里处理推送通知的点击事件
val extras = intent?.extras
val notificationId = extras?.getInt("notification_id", 0)
val notificationType = extras?.getString("notification_type", "")
// 根据具体内容选择启动的Activity
when (notificationType) {
"type1" -> {
val activityIntent = Intent(context, Activity1::class.java)
context?.startActivity(activityIntent)
}
"type2" -> {
val activityIntent = Intent(context, Activity2::class.java)
context?.startActivity(activityIntent)
}
// 其他推送通知类型的处理
// ...
}
// 清除点击的推送通知
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(notificationId)
}
}
<manifest>
<uses-permission android:name="android.permission.VIBRATE" />
<application>
<receiver android:name=".NotificationReceiver" />
<!-- 声明Notification点击的IntentFilter -->
<activity
android:name=".Activity1"
android:exported="true">
<intent-filter>
<action android:name="com.example.NOTIFICATION_ACTION_TYPE1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Activity2"
android:exported="true">
<intent-filter>
<action android:name="com.example.NOTIFICATION_ACTION_TYPE2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- 其他Activity的声明 -->
<!-- ... -->
</application>
</manifest>
// 设置点击通知时的Intent
val clickIntent1 = Intent("com.example.NOTIFICATION_ACTION_TYPE1")
clickIntent1.putExtra("notification_id", notificationId)
clickIntent1.putExtra("notification_type", "type1")
val clickPendingIntent1 = PendingIntent.getBroadcast(context, 0, clickIntent1, PendingIntent.FLAG_UPDATE_CURRENT)
val clickIntent2 = Intent("com.example.NOTIFICATION_ACTION_TYPE2")
clickIntent2.putExtra("notification_id", notificationId)
clickIntent2.putExtra("notification_type", "type2")
val clickPendingIntent2 = PendingIntent.getBroadcast(context, 0, clickIntent2, PendingIntent.FLAG_UPDATE_CURRENT)
// 构建推送通知
val notificationBuilder = NotificationCompat.Builder(context, "channel_id")
.setContentTitle("Notification Title")
.setContentText("Notification Content")
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(clickPendingIntent1) // 设置通知点击事件
.addAction(R.drawable.icon1, "Action 1", clickPendingIntent1) // 设置通知上的按钮1
.addAction(R.drawable.icon2, "Action 2", clickPendingIntent2) // 设置通知上的按钮2
// 发送推送通知
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(notificationId, notificationBuilder.build())
通过以上步骤,可以根据推送通知的具体内容选择启动对应的Activity,并实现相应的点击事件。在步骤2中,需要在AndroidManifest.xml文件中注册所有可能用到的Activity,并为它们声明相应的IntentFilter,以便能够接收到推送通知的点击事件。
领取专属 10元无门槛券
手把手带您无忧上云