且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在点击推送通知时打开特定活动?

更新时间:2022-12-19 19:21:03

private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    long notificatioId = System.currentTimeMillis();

    Intent intent = new Intent(getApplicationContext(), TestActivity.class); // Here pass your activity where you want to redirect.

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, 0);

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
        currentapiVersion = R.mipmap.ic_notification_lolipop;
    } else{
        currentapiVersion = R.mipmap.ic_launcher;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(currentapiVersion)
            .setContentTitle(this.getResources().getString(R.string.app_name))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg)
            .setAutoCancel(true)
            .setPriority(Notification.PRIORITY_HIGH)
            .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
            .setContentIntent(contentIntent);
    mNotificationManager.notify((int) notificatioId, notificationBuilder.build());
}