【问题标题】:How can i open Activity when notification click单击通知时如何打开活动
【发布时间】:2017-02-03 14:24:26
【问题描述】:

我需要使用带有点击事件的通知,我有通知方法,但此方法不会打开我的活动。

我的代码:

 private void sendNotification(String msg) {

        NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
        .setContentTitle("EXX")
        .setSmallIcon(R.drawable.ic_launcher)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg)          
        .setOngoing(true);          
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}    

这可能吗,

谢谢。

【问题讨论】:

标签: java android android-notifications android-notification-bar


【解决方案1】:

是的,有可能。

改变你的方法,像那样;

private void sendNotification(String msg) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("yourpackage.notifyId", NOTIFICATION_ID);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
            .setContentTitle("EXX")
            .setSmallIcon(R.drawable.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle()
            .bigText(msg))
            .addAction(getNotificationIcon(), "Action Button", pIntent)
            .setContentIntent(pIntent)
            .setContentText(msg)
            .setOngoing(true);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

并添加您的主要活动

    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

此代码有效。

【讨论】:

  • 哦,谢谢!这段代码对我有用!我爱你兄弟
  • 请注意 addAction(getNotificationIcon(), "Action Button", pIntent) 已弃用
【解决方案2】:

嘿@John,这很简单

你只需要这样做

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

... // 因为点击通知会打开一个新的(“特殊”)活动,所以有 // 无需创建人工回栈。

PendingIntent pendingIntent = TaskStackBuilder.create(getApp())
            .addNextIntent(intent)
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

并在 mBuilder 中设置待处理的 Intent

private void sendNotification(String msg) {
        NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
        .setContentTitle("EXX")
        .setSmallIcon(R.drawable.ic_launcher)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg)          
        .setOngoing(true);    
        .setContentIntent(pendingIntent)
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
} 

你完成了:)

【讨论】:

  • 可以使用MainActivity.class 或具体的活动名称来代替getApp() 来指定您的活动名称。
猜你喜欢
  • 1970-01-01
  • 2017-05-05
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多