首页 > 解决方案 > 如何通过通知进入活动?

问题描述

如何通过通知进入活动?我最近做了一个媒体播放器活动,当我按下播放按钮时,会弹出一个通知并说正在播放音乐。我对编码有点陌生,我阅读了有关此主题的 android 开发人员页面,但我不了解“应用程序的 Activity 层次结构”以及如何使 Intent 在我的代码中工作。

我对每首音乐都有一个单独的活动,它为每首音乐制作自己的通知。我需要他们的通知来打开他们的活动,而不是主要或任何其他活动。(例如:music1 创建通知 1,退出应用程序后,如果我按下通知 1,它应该让我进入音乐 1)。

班上:

public void createNotification(Context context, Track track, int playButton, int pos, int size) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
        MediaSessionCompat mediaSessionCompat = new MediaSessionCompat(context, "tag");

        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), track.getImage());

        notification = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.diligent_transparent_logo)
                .setContentTitle(track.getTitle())
                .setContentText(track.getText())
                .setLargeIcon(icon)
                .setOnlyAlertOnce(true)
                .setShowWhen(false)

                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();

        notificationManagerCompat.notify(1, notification);
    }
}

我的大部分代码:

 populateTracks();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        createChannel();
    }

 private void createChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel channel = new NotificationChannel(CreateNotification.CHANNEL_ID,
                "Diligent", NotificationManager.IMPORTANCE_LOW);

        notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}


private void populateTracks() {
    tracks = new ArrayList<>();

    tracks.add(new Track("You are watching Getting started meditation", "Press here to enter the app", R.drawable.diligent_transparent_logo));
}

我的清单:

        <activity android:name=".meditation.m4" />

如果有人让我了解如何完成这项工作,我将不胜感激。

标签: javaandroidandroid-activitynotificationsandroid-notifications

解决方案


首先为要打开的activity类新建一个Intent,比如我要打开MainActivity,我会用

Intent intent = new Intent(this , MainActivity.class);

然后创建带有上下文的待处理 Intent,Integer 中的 Request Code,intent 和 Flags。

PendingIntent pendingIntent = PendingIntent.getActivity(this , REQUEST_CODE , intent , 0);

然后像这样在通知生成器中使用这个pendingIntent,

NotificationCompat.Builder(this, "Foreground Service Notification")
        .setSmallIcon(R.drawable.ic_status_splash)
        .setContentTitle(resources.getString(R.string.app_name))
        .setContentIntent(pendingIntent)
        .setPriority(NotificationCompat.PRIORITY_LOW)

推荐阅读