android 如何通过点击通知栏打开应用程序?

mnemlml8  于 2022-12-09  发布在  Android
关注(0)|答案(2)|浏览(565)

我尝试通过点击应用程序的通知栏来打开我的应用程序。代码如下。我尝试添加pendingintent,但不确定它会使用哪种格式。

public static final String CHANNEL_ID = "channel1";
    
        public static final String ACTION_PREVIOUS = "actionprevious";
        public static final String ACTION_PLAY = "actionplay";
        public static final String ACTION_NEXT = "actionnext";
    
        public static Notification notification;
    
        public static void createNotification(Context context, TrackModel trackModel, 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(), R.drawable.img1);
    
    
    
                notification = new NotificationCompat.Builder(context,CHANNEL_ID)
    
                        .setSmallIcon(R.drawable.ic_music)
                        .setContentTitle(trackModel.getName())
                        .setLargeIcon(icon)
                        .setOnlyAlertOnce(true)
                        .setShowWhen(false)
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                        .setAutoCancel(true)
                        .build();
                notificationManagerCompat.notify(1, notification);
            }
        }
    }
oo7oh9g9

oo7oh9g91#

.setContentIntent(pendingIntent) 添加到您的通知生成器

val newIntent = Intent(context, MainActivity::class.java)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        PendingIntent.getActivity(context, 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
    } else {
        PendingIntent.getActivity(context, 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
    }
umuewwlo

umuewwlo2#

您可以为通知设置待定意向,以便在单击通知时打开应用:
Android Developers

相关问题