Я прочитал несколько вопросов и ответов по этой проблеме, однако я не могу заставить ни один из них работать на меня.

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

Это мой код уведомления

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("example")
            .setContentText("example");
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    // 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(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int mId = 0;
    // mId allows you to update the notification later on.
    mNotificationManager.notify(mId, mBuilder.build());

И в моем файле манифеста у меня есть

        android:launchMode="singleTop"

Кто-нибудь может увидеть, что происходит не так? Я не получаю ошибок, хотя уведомление не возобновляет работу приложения, а перезапускает его.

2
rossd 24 Фев 2014 в 22:04
 – 
weaknespase
24 Фев 2014 в 22:13
resultIntent.setFlags (Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); все еще вызывает перезапуск приложения.
 – 
rossd
24 Фев 2014 в 22:26
Может быть, деятельность, которую вы пытаетесь вывести на первый план, уже разрушена?
 – 
weaknespase
24 Фев 2014 в 22:32
Приложение воспроизводит звуки при нажатии кнопки. Тестируя эти методы, я проигрывал звук, свернул приложение, затем потянул вниз и выбрал уведомление. Когда уведомление выбрано, музыка останавливается, и приложение перезапускается.
 – 
rossd
24 Фев 2014 в 22:36
Попробуйте singleTask или singleInstance, может, это поможет. И я считаю, что тестирование со звуком могло быть некорректным. Когда я наблюдал за жизненным циклом активности, я использовал обратные вызовы журнала и жизненного цикла для печати сообщений.
 – 
weaknespase
24 Фев 2014 в 22:47

3 ответа

Лучший ответ

Исправлено с помощью этого:

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Sound Asleep")
            .setContentText("Click to play and stop sounds");
    // Creates an explicit intent for an Activity in your app
    final Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Intent.ACTION_MAIN);
    notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    // 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.

    // Adds the back stack for the Intent (but not the Intent itself)
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int mId = 0;
    // mId allows you to update the notification later on.
    mNotificationManager.notify(mId, mBuilder.build());
}

В манифесте

android:launchMode="singleTop"
5
rossd 24 Фев 2014 в 23:28
Это сработало для меня, но изменил mId = 1 и в манифесте android: launchMode = "singleInstance". Спасибо
 – 
Gonza Piotti
14 Окт 2015 в 06:11

У меня была аналогичная проблема, недавно изменив флаги намерений с помощью этих флагов:

resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

Изменить: и удалите этот режим запуска из своего манифеста.

Надеюсь, это поможет

1
murielK 24 Фев 2014 в 22:13
Пытался, и приложение все еще перезагружается, мне очень сложно понять, почему.
 – 
rossd
24 Фев 2014 в 22:25
Вместо использования конструктора стека просто создайте PendingIntent resultPendingIntent = PendingIntent.getActivities (context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT), поскольку вы устанавливаете флаги на свой resultIntent, я не думаю, что это действительно необходимо
 – 
murielK
24 Фев 2014 в 22:32
Удаление их и наличие - PendingIntent resultPendingIntent = PendingIntent.getActivity (this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); все еще перезапускает приложение. Кажется, мою проблему ничем не решит.
 – 
rossd
24 Фев 2014 в 23:19

Используйте приведенный ниже код, может он поможет

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Sound Asleep")
        .setContentText("Click to play and stop sounds");
// Creates an explicit intent for an Activity in your app
final Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// 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.

// Adds the back stack for the Intent (but not the Intent itself)
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_ACTIVITY_REORDER_TO_FRONT);

mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mId = 0;
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
0
Solution 25 Фев 2014 в 14:23