Nativescript - Как вывести приложение на передний план при нажатии уведомления - PullRequest
0 голосов
/ 31 мая 2019

Я пишу собственный код Android, чтобы открывать мое приложение при нажатии на уведомление. Если приложение уже открыто (работает ли оно на переднем плане или в фоновом режиме), я хочу щелкнуть уведомление, чтобы вывести приложение на передний план, не перезапуская его, чтобы сохранить его состояние.

Я попробовал следующий код (показывает только соответствующий код):



        ///////// Create an activity on tap (intent)
        const Intent = android.content.Intent;
        const PendingIntent = android.app.PendingIntent;
        // Create an explicit intent for an Activity in your app
        const intent = new Intent(context, com.tns.NativeScriptActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);


        const pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        ///////// Creating a notification 
        var NotificationCompat = android.support.v4.app.NotificationCompat;
        const builder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.btn_star_big_on)
            .setContentTitle(title)
            .setContentText(message)
            .setStyle(
                new NotificationCompat.BigTextStyle()
                .bigText("By default, the notification's text content is truncated to fit one line.")
                )
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

        ///////// Show the notification
        notificationManager.notify(NOTIFICATION_ID, builder.build());

Но это открыло приложение без сохранения его состояния.

Следуя рекомендациям здесь , я также попытался эмулировать нажатие на значок приложения на панели запуска, чтобы приложение просто выводилось на передний план, а действие Nativescript не создавалось заново.

        const packageName = context.getPackageName();
        console.log('Package name: ',packageName);

        const emulateLaunchByAppIconIntent = context.getPackageManager()
            .getLaunchIntentForPackage(packageName)
            .setPackage(null)
            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        const pendingIntent_emulated = PendingIntent.getActivity(context, 0, emulateLaunchByAppIconIntent, 0);


        ///////// Creating a notification 
        var NotificationCompat = android.support.v4.app.NotificationCompat;
        const builder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.btn_star_big_on)
            .setContentTitle(title)
            .setContentText(message)
            .setStyle(
                new NotificationCompat.BigTextStyle()
                .bigText("By default, the notification's text content is truncated to fit one line.")
                )
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent_emulated)
            .setAutoCancel(true);

        ///////// Show the notification
        notificationManager.notify(NOTIFICATION_ID, builder.build());

Это действительно заставило приложение выйти на первый план, но не сохранило его состояние (даже если приложение уже было на переднем плане - оно перезагрузило приложение).

Затем я попытался нажать значок приложения Nativescript (вручную), когда приложение только что было отправлено в фоновый режим, и обнаружил, что оно перезапустит приложение, а не просто выведет его на передний план.

Мой вопрос - почему приложение Nativescript ведет себя так? Как сделать так, чтобы Android просто выводил приложение на передний план, а не перестраивал новую активность nativescript?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...