Как открыть конкретный экран после нажатия на уведомление?

1

В настоящее время, когда пользователь получает уведомление, когда приложение флаттера свернуто, и нажимает на уведомление, оно каждый раз перенаправляет пользователя к screen A Но я хочу, чтобы пользователь приземлился, скажем, на screen C через Deeplink, который создается вручную. Кроме того, если пользователь сворачивает приложение с любого экрана, нажатие на уведомление приводит пользователя к этому экрану. Но независимо от того, откуда пользователь сворачивает приложение или когда оно находится в фоновом режиме, нажатие на уведомление должно всегда перенаправлять пользователя на screen C Я не реализовывал уведомления раньше, так что я впервые имею дело с этой проблемой, поэтому ищу помощь в этом отношении. Код класса уведомления ниже:

companion object {

    const val CHAT_REQUEST_NOTIFICATION_ID = 1775
    const val CHAT_CHANNEL_ID = "com.example.com.CHAT_CHANNEL_ID"
    const val CHAT_CHANNEL_NAME = "Demo Notifications"

    fun showChatNotification(context: Context, userName: String?, body: String?) {

        createChatNotificationChannel(context);

        val chatIntent = Intent();
        val deeplink = generateDeepLink(userName);
        chatIntent.setAction(Intent.ACTION_VIEW);
        chatIntent.setData(Uri.parse(deeplink));
        val chatPendingIntent = PendingIntent.getActivity(context, 100, chatIntent, PendingIntent.FLAG_ONE_SHOT)

        val notification: Notification

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            notification = Notification.Builder(context, CHAT_CHANNEL_ID)
                .setContentIntent(chatPendingIntent)
                .setSmallIcon(R.drawable.notification_icon)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.ic_app_icon))
                .setAutoCancel(true)
                .setContentTitle("Message")
                .setContentText(body)
                .setOngoing(false)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .build()
        } else {
            notification = Notification.Builder(context)
                .setContentIntent(chatPendingIntent)
                .setSmallIcon(android.R.drawable.btn_star)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.app_icon))
                .setAutoCancel(true)
                .setVibrate(chatVibrationPattern)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setContentTitle("Message")
                .setOngoing(false)
                .setContentText(body)
                .build()
        }
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(CHAT_REQUEST_NOTIFICATION_ID, notification)
    }

    fun generateDeepLink(userId: String?): String {
        return "https://demo.page.link/?link=https://demo.com/chat?user=$userId&apn=com.example.com&efr=1";
    }

    private fun createChatNotificationChannel(context: Context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            notificationManager.deleteNotificationChannel(CHAT_CHANNEL_ID)

            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel = NotificationChannel(CHAT_CHANNEL_ID, CHAT_CHANNEL_NAME, importance)
            notificationChannel.description = "Message"
            notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }
}

Я использую эмуляторы Android (6.0).

Теги:
kotlin
flutter
android-notifications

3 ответа

0

Попробуй это:

     /**Creates an explicit intent for an Activity in your app**/
    Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(resultPendingIntent);

    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
    {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}
0

Я не обнаружил, что вы упомянули деятельность, которую хотите открыть.

val resultIntent = Intent (это, ResultActivity :: class.java)

Следуйте этому шагу, и вы получите ответ.

или вы можете попробовать это

0

@Dk15 Вы правильно делаете, что нужно сделать для определенного перенаправления: отправьте событие в ваших данных с сервера, например, при создании уведомления отправьте событие, подобное JOB_ACCEPTED, так что вы можете проверить его при создании.
if (getIntent().getExtras() != null)
затем перенаправить на оператор switch и проверить, какое событие вы получили, а затем перенаправить пользователя туда, куда вы хотите
switch (getIntent().getStringExtra("EVENT_TYPE")){ Match your case here and redirect user in your case to SCREEN C case "JOB_ACCEPTED": OPEN SCREEN C; break; }

Ещё вопросы

Сообщество Overcoder
Наверх
Меню