如何在通知点击时进入特定活动?

3

有多个通知,点击通知后我想要进入特定的活动。比如奖励通知出现时,点击将进入RewardActivity;新朋友添加时,点击新朋友通知将进入friendlistActivity,无论应用程序是在前台还是后台。

但是在我的情况下,任何通知都会进入相同的活动,而不是不同的活动。

翻译:@机器人小助手

private void handleDataMessage(String noti_title,String noti_message,String noti_click_action) {

    try {

        Intent intent = new Intent(this, RewardActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("title", noti_title);
        ByteArrayOutputStream _bs = new ByteArrayOutputStream();
        //image.compress(Bitmap.CompressFormat.PNG, 50, _bs);
        //intent.putExtra("img", image);
        intent.putExtra("msg", noti_message);
        intent.putExtra("click_action", noti_click_action);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new
                NotificationCompat.Builder(this, "Default")
                //.setLargeIcon(R.mipmap.ic_launcher)/*Notification icon image*/
                .setSmallIcon(R.mipmap.ic_launcher)
                //.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(Notification.PRIORITY_HIGH)
                .setChannelId("Default")
                .setVibrate(new long[]{1000, 1000})
                .setContentIntent(pendingIntent);

        notificationBuilder.setContentTitle(noti_title);
        notificationBuilder.setContentText(noti_message);
        notificationBuilder.setAutoCancel(true);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());



    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

你有一个待处理的意图,你将其传递给通知,根据你的条件创建多个意图。 - undefined
你需要根据你的重定向需求修改以下代码:Intent intent = new Intent(this, RewardActivity.class); - undefined
@GaneshPokale:你认为他无法启动RewardActivity活动的问题是什么?你能简要解释一下吗? - undefined
你在哪个操作系统上运行这个程序? - undefined
在奖励通知中使用相同的意图,在新朋友通知中,意图将是Intent intent = new Intent(this,friendlistActivity.class); - undefined
2个回答

6

FCM会代表客户端应用程序自动向终端用户设备显示消息。当用户点击通知时,将创建两个条件:

  1. 当您的应用程序在后台时传递通知。在这种情况下,通知将传递到设备的系统托盘。用户点击通知默认打开应用程序启动器。

  2. 包含通知和数据有效负载的消息,后台和前台都有。在这种情况下,通知将传递到设备的系统托盘,并且数据有效负载将在您的启动器Activity的意图附加项中传递。

如果您想要在应用程序在后台时打开所需的Activity,并且通知仅包含通知而没有数据有效载荷,则不可能实现。

但是,如果您想要在应用程序在后台时打开所需的Activity,并且通知包含数据有效负载,则可以将用户导航到所需的Activity。

看下面的示例,了解如何在具有数据有效负载的消息(后台和前台)的情况下打开所需的Activity。

在我的AndroidManifest中,启动器Activity是SplashActivity。

<activity android:name=".activities.SplashActivity">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

您可以通过Google FCM Tester在pushtry.com上测试通知。以下是通过pushtry.com发送时的有效载荷数据格式。

{
  "to":"your_device_token",
  "data": {
      "title": "hello",
      "message": "test message",
  },
 "priority":"high"
}

MyFirebaseMessagingService类:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM Service";
    private static int count = 0;

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        KeyManager.setSharedPreferenceString(getApplicationContext(), "fcm_token", s);
        Log.e(TAG, "onNewToken: " + s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
//Here notification is recieved from server
        try {
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(getApplicationContext(), SplashActivity.class);  
//you can use your launcher Activity insted of SplashActivity, But if the Activity you used here is not launcher Activty than its not work when App is in background.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Add Any key-value to pass extras to intent
        intent.putExtra("pushnotification", "yes");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//For Android Version Orio and greater than orio.
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = new NotificationChannel("Sesame", "Sesame", importance);
            mChannel.setDescription(messageBody);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            mNotifyManager.createNotificationChannel(mChannel);
        }
//For Android Version lower than orio.
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "Seasame");
        mBuilder.setContentTitle(title)
                .setContentText(messageBody)
                .setSmallIcon(R.mipmap.ic_launcher_sesame)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_sesame))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setColor(Color.parseColor("#FFD600"))
                .setContentIntent(pendingIntent)
                .setChannelId("Sesame")
                .setPriority(NotificationCompat.PRIORITY_LOW);

        mNotifyManager.notify(count, mBuilder.build());
        count++;
    }

}

现在,当您在后台接收到推送通知并点击通知时,通知会传递到设备的系统托盘,Extras会传递给您的启动器Activity。检查启动器Activity是否带有额外信息或为空,然后将用户导航到所需的Activity。
如果您只想向已登录的用户显示活动,则SplashActivity如下所示:
public class SplashActivity extends AppCompatActivity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

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

        try {
            if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
                if (getIntent().hasExtra("pushnotification")) {
                    Intent intent = new Intent(this, YourDesiredActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    CheckLogin();
                }
            } else {
                Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }

        } catch (Exception e) {
            CheckLogin();
            e.printStackTrace();
        }
    }

    private void CheckLogin() {
        if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
            Intent i = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(i);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                }
            }, 2500);
        }
    }

}

在SplashActivity中的逻辑,根据条件引导用户进入不同的Activity。

当用户正常打开应用程序而没有点击推送通知时,getIntent().hasExtra("pushnotification")为null,因此命令进入catch块,并检查CheckLogin()方法是否已登录。 但是,如果用户通过点击推送通知进入,则getIntent().hasExtra("pushnotification")不为null,他将进入所需的Activity。


0

我曾经遇到同样的问题,在阅读了文档之后,这两个步骤对我有用。

  1. 定义您的应用程序的Activity层次结构
  2. 并使用TaskStackBuilder。这是我之前缺少的。
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
完整代码:
private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(
                "Foreground_Service_Channel_Id",
                "Foreground_Service_Channel_Name",
                NotificationManager.IMPORTANCE_DEFAULT
        );

        NotificationManager manager = getApplicationContext().getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}

private void showNotification()
{
    Intent notificationIntent = new Intent(context, YOUR_ACTIVITY.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(notificationIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel();
        Notification.Builder builder = new Notification.Builder(context, "Foreground_Service_Channel_Id")
                .setSmallIcon(R.drawable.ic_mode_night_24)
                .setContentTitle("SAMPLE_TEXT_TITLE")
                .setContentIntent(resultPendingIntent)
                .setStyle(new Notification.InboxStyle()
                        .setSummaryText("SAMPLE_TEXT"))
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setOngoing(true)
                .setAutoCancel(false);

        Notification notification = builder.build();
        startForeground(ID, notification);
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_mode_night_24)
                .setContentTitle("SAMPLE_TEXT_TITLE")
                .setContentIntent(resultPendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setOngoing(true)
                .setAutoCancel(false);
        builder.setContentIntent(resultPendingIntent);
        Notification notification = builder.build();
        startForeground(ID, notification);
    }

}

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