安卓如何在用户点击通知时启动活动?

4

当用户点击通知时,我想要打开一个活动。我知道这个问题已经有人问过了,但是我找不到解决方案,以下是我所做的:

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");

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

// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
);

mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = 
    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());

这里是我所遵循的文档。有没有人知道为什么ResultActivity无法打开?

5个回答

5

1
setLatestEventInfo 方法已经过时,针对第二个链接 https://dev59.com/m2Yr5IYBdhLWcg3wYpQg - nAkhmedov
感谢您提供的第三个链接。 - nAkhmedov

3
这是我的最终解决方案:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(YourService.this)
            .setContentTitle(getResources().getText(R.string.app_name))
            .setContentText(getServiceStateDescription(HomeBridgeService.this))
            .setSmallIcon(iconId)
            .setWhen(System.currentTimeMillis());

    Intent nIntent = getPreviousIntent();
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack
    stackBuilder.addParentStack(MainActivity_.class);
    stackBuilder.addNextIntent(nIntent);
    PendingIntent pendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    notificationBuilder.setContentIntent(pendingIntent);

    startForeground(ContextConstants.LAUNCHER_SERVICE_NOTE_ID, notificationBuilder.build());


private Intent getPreviousIntent() {
    Intent newIntent = null;
    final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final List<ActivityManager.AppTask> recentTaskInfos = activityManager.getAppTasks();
        if (!recentTaskInfos.isEmpty()) {
            for (ActivityManager.AppTask appTaskTaskInfo: recentTaskInfos) {
                if (appTaskTaskInfo.getTaskInfo().baseIntent.getComponent().getPackageName().equals(ContextConstants.PACKAGE_NAME)) {
                    newIntent = appTaskTaskInfo.getTaskInfo().baseIntent;
                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
            }
        }
    } else {
        final List<ActivityManager.RecentTaskInfo> recentTaskInfos = activityManager.getRecentTasks(1024, 0);
        if (!recentTaskInfos.isEmpty()) {
            for (ActivityManager.RecentTaskInfo recentTaskInfo: recentTaskInfos) {
                if (recentTaskInfo.baseIntent.getComponent().getPackageName().equals(ContextConstants.PACKAGE_NAME)) {
                    newIntent = recentTaskInfo.baseIntent;
                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
            }
        }
    }
    if (newIntent == null) newIntent = new Intent();
    return newIntent;
}

some explanation please - Shadab K
@ShadabK 当用户点击通知时,我将从TaskBuilder中显示上一个意图。请尝试了解一下相关信息。 - nAkhmedov

2

这是我的代码...它可以运行。这会带你到另一个活动note.class。

package com.x.notifix;

import android.app.TaskStackBuilder;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;



public class MainActivity extends AppCompatActivity {

    NotificationCompat.Builder notifix;
    private static final int xid = 12345;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        notifix = new  NotificationCompat.Builder(this);
        notifix.setAutoCancel(true);

    }



    public void click (View view){
        notifix.setSmallIcon(R.drawable.x);
        notifix.setTicker(" hollup!! ");
        notifix.setWhen(System.currentTimeMillis());
        notifix.setContentTitle(" X-Noted !!");
        notifix.setContentText( " this is where you got Xed ..");

        Intent i = new Intent(this, note.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this , 1 , i , PendingIntent.FLAG_UPDATE_CURRENT);
        notifix.setContentIntent(pendingIntent);

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(xid, notifix.build());

    }

}

1
在你的代码中,
Intent resultIntent = new Intent(this, ResultActivity.class);//Here mention the class which you want to open.

并在待定意图中添加FLAG_ACTIVITY_NEW_TASK

PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    Intent.FLAG_ACTIVITY_NEW_TASK
);

谢谢您的回应,但是它并没有帮助我。我认为 Intent.FLAG_ACTIVITY_NEW_TASK 还需要其他标志。 - nAkhmedov
请查看此链接:http://developer.android.com/reference/android/content/Intent.html 它可能会对有关活动标志方面有所帮助。 - Kishore Kumar

0

使用 Kotlin,

val channelId = "My_Channel_id"
val channelName = "My Channel"

val resultIntent = Intent(this, MainActivity::class.java)
val pendingIntent = TaskStackBuilder.create(this).run {
    addNextIntentWithParentStack(resultIntent)
    getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
}

var notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Much longer text that cannot fit one line...")
    .setStyle(NotificationCompat.BigTextStyle()
    .bigText("Much longer text that cannot fit one line..."))
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setContentIntent(pendingIntent)

with(NotificationManagerCompat.from(this)){
    notify(1,  notificationBuilder.build())
}

这将创建一个通知,点击后打开MainActivity


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