Подтвердить что ты не робот

Нажатие на Уведомление не запускает намеченную активность?

Я использую GCM в своем приложении, а также используя NotificationManager для создания уведомления, когда получено сообщение GCM. Теперь все работает отлично, и сообщение GCM отображается правильно в области уведомлений, но когда я нажимаю на уведомление, оно должно начинаться действие моего приложения, которое отображает детали сообщений, которые не происходят. Каждый раз я нажимаю на уведомление, что он не запускает никаких действий, и он остается как есть. Мой код для создания уведомления:

private void sendNotification(String msg) {
        SharedPreferences prefs = getSharedPreferences(
                DataAccessServer.PREFS_NAME, MODE_PRIVATE);
        mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, WarningDetails.class);
        Bundle bundle = new Bundle();
        bundle.putString("warning", msg);
        bundle.putInt("warningId", NOTIFICATION_ID);
        intent.putExtras(bundle);
        // The stack builder object will contain an artificial back stack for
        // the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(WarningDetails.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(intent);

        PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.weather_alert_notification)
                .setContentTitle("Weather Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);
        String selectedSound = prefs.getString("selectedSound", "");
        if (!selectedSound.equals("")) {
            Uri alarmSound = Uri.parse(selectedSound);
            mBuilder.setSound(alarmSound);

        } else {
            Uri alarmSound = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(alarmSound);
        }

        if (prefs.getBoolean("isVibrateOn", false)) {
            long[] pattern = { 500, 500, 500, 500, 500, 500, 500, 500, 500 };
            mBuilder.setVibrate(pattern);
        }

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

Я обновил свой код, чтобы поддерживать Preserving Navigation when Starting an Activity, как это происходит в приложении Gmail с веб-сайта разработчиков Android с тех пор, как он перестает работать. Некоторые из нас Пожалуйста, расскажите мне, что мне не хватает или что-то не так в этом коде.

4b9b3361

Ответ 1

Моя проблема решена. Мне просто нужно добавить флаг PendingIntent.FLAG_ONE_SHOT, поэтому я заменил:

PendingIntent contentIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

to

PendingIntent contentIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
                        | PendingIntent.FLAG_ONE_SHOT);

Ответ 2

Я столкнулся с той же проблемой и разрешил ее, добавив в объявление AndroidManifest.xml android: exported = "true" .

Ответ 3

Здесь вы только что передали свое намерение в ожидании ответа: см. ниже

Intent notificationIntent = new Intent(context, Login.class);

 PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
and set this contentintent into your Notification:

Notification noti = new NotificationCompat.Builder(context)
                    .setSmallIcon(icon_small)
                    .setTicker(message)
                    .setLargeIcon(largeIcon)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle(title)
                    .setContentText(message)
                    .setContentIntent(**contentIntent**)
                    .setAutoCancel(true).build();

Это может вам помочь.

Ответ 4

если вы запустили запланированное действие с помощью Строка Action, не забудьте добавить

<intent-filter>
       <action android:name="YOUR ACTION STRING"/>
       <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

внутри тега <activity></activity>

Ответ 5

Активность, которую вы хотите запустить, должна быть обозначена как активность LAUNCHER в вашем манифестах - иначе она не будет запускаться с помощью ожидающего намерения. Добавьте в приложение AndroidManifext.xml следующее:

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

В противном случае вам нужно будет использовать Activity, который уже обозначен как LAUNCHER (например, ваша MAIN-активность)

Ответ 6

Сделайте что-нибудь подобное в методе generateNotification().

Замените свою деятельность классом Splash.Java в нем.

/**
     * Issues a notification to inform the user that server has sent a message.
     */
    @SuppressWarnings("deprecation")
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        //message = "vivek";
       // Log.d("anjan", message.split("~")[0]);
        //Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);
        Log.d("anjan1", title);
        String text_message = context.getString(R.string.title_activity_main);
        Log.d("anjan1", text_message);

        Intent notificationIntent = new Intent(context, Splash.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);      

    }

Ответ 7

Попробуйте это вместо последней строки:

mNotificationManager.notify(0, mBuilder.getNotification());