如何在点击通知时打开活动

时间:2017-02-03 14:24:26

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

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

我的代码:

 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());
}    

这是可能的,

感谢。

2 个答案:

答案 0 :(得分:4)

嘿@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());
} 

你完成了:)

答案 1 :(得分:3)

是的,这是可能的。

改变你的方法,就像那样;

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);

此代码有效。