要实现从通知启动活动,你需要以下步骤:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "channel_id";
String channelName = "Channel Name";
String channelDescription = "Channel Description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
channel.setDescription(channelDescription);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private NotificationCompat.Builder createNotificationBuilder(String channelId, String title, String content) {
Intent intent = new Intent(this, YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
return new NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
}
private void sendNotification(NotificationCompat.Builder builder, int notificationId) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
}
在你的应用中,你可以按照下面的步骤使用以上代码:
createNotificationChannel() 方法创建通知通道。createNotificationBuilder() 方法创建通知构建器,并设置标题、内容等属性。sendNotification() 方法发送通知,指定通知构建器和通知的唯一标识符。当用户点击通知时,会启动指定的活动(在 YourActivity.class 中指定),你可以在该活动中处理用户的操作。
希望以上代码示例对你有帮助!