点击通知后打开应用程序

137

我的应用程序中有一个包含以下代码的通知:

//Notification Start

   notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

   int icon = R.drawable.n1; 
   CharSequence tickerText = "Call Blocker";
   long when = System.currentTimeMillis(); //now
   Notification notification = new Notification(icon, tickerText, when);
   Intent notificationIntent = new Intent(context, Main.class);
   PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

   Context context = getApplicationContext();
   CharSequence title = "Call Blocker";
   text = "Calls will be blocked while driving";

   notification.setLatestEventInfo(context, title, text, contentIntent);

   notification.flags |= Notification.FLAG_ONGOING_EVENT;
   notification.flags |= Notification.FLAG_SHOW_LIGHTS;
   notificationManager.notify(1, notification);

}

我的通知可以正常触发,但问题在于,当我在通知中心点击通知时,它没有启动我的应用程序。

基本上,在点击我的通知后什么也没发生! 我应该怎么做,才能让点击通知后启动我的主活动。 谢谢。


2
尝试使用此链接:http://stackoverflow.com/a/4849754/1265724 - Ram kiran Pachigolla
2
Context context = getApplicationContext(); 移动到 Notification notification = new Notification(icon, tickerText, when); 之前,也许您没有传递正确的上下文来启动 Activity。 - ρяσѕρєя K
@HamedGh 差不多五年前啦!:))) - Reza_Rg
1
@Reza_Rg是7年前的事了。我有同样的问题! - fuliozor
可能是如何在点击通知时打开应用程序?的重复问题。 - chans
显示剩余2条评论
12个回答

184

看下面的代码,我正在使用它并且它打开了我的 HomeActivity。

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    Intent notificationIntent = new Intent(context, HomeActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

1
我漏掉了FLAG_AUTO_CANCEL标志。谢谢! - JonasVautherin
10
自此帖发布以来,Notiification(int, java.lang.CharSequence, long)已被弃用,请使用NotificationCompat.Builder。 - Bourne
13
无法解决方法“notification.setLatestEventInfo”。 - Ravi Vaniya

70

这里是使用NotificationCompact.Builder类的示例,它是构建通知的最新版本。

private void startNotification() {
    Log.i("NextActivity", "startNotification");

 // Sets an ID for the notification
      int mNotificationId = 001;

    // Build Notification , setOngoing keeps the notification always in status bar
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ldb)
                    .setContentTitle("Stop LDB")
                    .setContentText("Click to stop LDB")
                    .setOngoing(true);

    // Create pending intent, mention the Activity which needs to be 
    //triggered when user clicks on notification(StopScript.class in this case)

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);


    mBuilder.setContentIntent(contentIntent);


    // Gets an instance of the NotificationManager service
   NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotificationManager.notify(mNotificationId, mBuilder.build());


}

3
我到底做错了什么?我完全按照这个代码,但当我点击通知时它却不起作用。 - TheRealChx101

17

看起来你错过了这一部分,

notification.contentIntent = pendingIntent;

尝试添加这个,它应该能够工作。


14
请使用以下代码作为简单通知的完整示例,在该代码中,您可以在单击通知后打开应用程序,它将解决您的问题。
public class AndroidNotifications extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button notificationButton = (Button) findViewById(R.id.notificationButton);

        notificationButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        // Notification Title and Message
                        Notification("Dipak Keshariya (Android Developer)",
                                "This is Message from Dipak Keshariya (Android Developer)");
                    }
                }, 0);
            }
        });
    }

    // Notification Function
    private void Notification(String notificationTitle,
            String notificationMessage) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        android.app.Notification notification = new android.app.Notification(
                R.drawable.ic_launcher, "Message from Dipak Keshariya! (Android Developer)",
                System.currentTimeMillis());

        Intent notificationIntent = new Intent(this, AndroidNotifications.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        notification.setLatestEventInfo(AndroidNotifications.this,
                notificationTitle, notificationMessage, pendingIntent);
        notificationManager.notify(10001, notification);
    }
}

更多信息请参见下面的链接。

简单通知示例


6

请使用以下方法:

    Notification mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_music)
                    .setContentTitle(songName).build();


    mBuilder.contentIntent=  PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

contentIntent 将在用户点击通知时打开相应的活动。


6

使用以下代码创建打开活动的通知。它对我有用。 完整代码

 Intent myIntent = new Intent(context, DoSomething.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(
        context, 
        0, 
        myIntent, 
        Intent.FLAG_ACTIVITY_NEW_TASK);

 myNotification = new NotificationCompat.Builder(context)
   .setContentTitle("Exercise of Notification!")
   .setContentText("Do Something...")
   .setTicker("Notification!")
   .setWhen(System.currentTimeMillis())
   .setContentIntent(pendingIntent)
   .setDefaults(Notification.DEFAULT_SOUND)
   .setAutoCancel(true)
   .setSmallIcon(R.drawable.ic_launcher)
   .build();

 notificationManager = 
   (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
 notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

setAutoCancel(true) 就是我要找的。 - Wojtek

6
public void addNotification()
{
    NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this);
    mBuilder.setSmallIcon(R.drawable.email);
    mBuilder.setContentTitle("Notification Alert, Click Me!");
    mBuilder.setContentText("Hi,This notification for you let me check");
    Intent notificationIntent = new Intent(this,MainActivity.class);
    PendingIntent conPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(conPendingIntent);

    NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0,mBuilder.build());
    Toast.makeText(MainActivity.this, "Notification", Toast.LENGTH_SHORT).show();

}

3
虽然这段代码片段可能解决问题,但包括解释会真正有助于提高您帖子的质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您提出代码建议的原因。 - Alessio

5

Android 12及以上版本的通知代码:

如果你的应用程序的目标是Android 12,你必须指定每个 PendingIntent 对象的可变性。这个额外的要求可以提高你的应用程序的安全性。

在 Android 12 之前:

PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

对于 Android 12:

PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

首先创建频道:

 @RequiresApi(api = Build.VERSION_CODES.O)
private synchronized String createChannel() {
    NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    String name = "dummy text for channel";
    int importance = NotificationManager.IMPORTANCE_LOW;

    NotificationChannel mChannel = new NotificationChannel("channel name, name, importance);
    mChannel.setShowBadge(false);
    mChannel.enableLights(true);
    mChannel.setLightColor(Color.BLUE);
    if (mNotificationManager != null) {
        mNotificationManager.createNotificationChannel(mChannel);
    } else {
        stopSelf();
    }
    return "Channel";
}

通知示例:
String channel="";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            channel = createChannel();
        else {
            channel = "";
        }

    RemoteViews mContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.general_notification_layout_new);

    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel);
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

    builder.setSmallIcon(R.drawable.notification_small_icon_one)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setSound(notificationSound)
            .setColor(ContextCompat.getColor(this, R.color.colorPrimary))
            .setCustomContentView(mContentView)
            .setCustomBigContentView(mContentView)
            .setContentIntent(contentIntent);


    builder.setAutoCancel(true);

    Notification notification = builder.build();
    mNotificationManager.notify(notificationId, notification);

Android 12 notifications


3

感谢以上帖子,以下是从较长的代码答案中提炼出来的主要行 - 必要的连接通知与点击侦听器设置打开某个应用程序活动的行。

private Notification getNotification(String messageText) {

    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentText(messageText);
    // ...

    Intent appActivityIntent = new Intent(this, SomeAppActivity.class);

    PendingIntent contentAppActivityIntent =
            PendingIntent.getActivity(
                            this,  // calling from Activity
                            0,
                            appActivityIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(contentAppActivityIntent);

    return builder.build();
}

3

这是我处理的方式。

public class AppFCMService extends FirebaseMessagingService {

    private final static String TAG = "FCM Message";
    String notify, requstId, Notification;
    PendingIntent pendingIntent;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        //split string and getting order id from notification
        String Str = remoteMessage.getNotification().getBody();
        String[] tmp;
        tmp = Str.split(" ");
        String temp1 = tmp[0];
        String temp2 = tmp[1];
        String id = tmp[2];
        notify = temp1 + " " + temp2;
        requstId = id;
        showNotification(remoteMessage.getNotification().getBody());
    }

    private void showNotification(String messageBody) {
        // check whether session has been initiated or not
        if (new SessionHelper(getApplicationContext()).isLoggedIn()) {

            if (notify.equalsIgnoreCase("Travel request")) {

                Intent intent = new Intent(this, ViewTravelDetailsActivity.class);
                intent.putExtra("TravelRequestID", requstId);
                intent.putExtra("BackPress", "Notify");
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);

            } else if (notify.equalsIgnoreCase("Timesheet replied")) {

                Intent intent = new Intent(this, ViewReplyActivity.class);
                intent.putExtra("timesheetActivityID", requstId);
                intent.putExtra("BackPress", "Notify");
                intent.putExtra("RealmData", "DeleteRealm");
                intent.putExtra("isToday", "true");
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
            } else {

                Intent intent = new Intent(this, Dashboard.class);
                intent.putExtra("timesheetActivityID", requstId);
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
            }
        } else {

            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("timesheetActivityID", requstId);
            pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        Bitmap notifyImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(notifyImage)
                .setColor(Color.parseColor("#FFE74C3C"))
                .setContentTitle("TEST")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接