Я прочитал несколько вопросов и ответов по этой проблеме, однако я не могу заставить ни один из них работать на меня.
У меня есть уведомление о том, что при нажатии я хотел бы вывести приложение на передний план и возобновить его, а не закрыть и перезапустить.
Это мой код уведомления
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"
Кто-нибудь может увидеть, что происходит не так? Я не получаю ошибок, хотя уведомление не возобновляет работу приложения, а перезапускает его.
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"
У меня была аналогичная проблема, недавно изменив флаги намерений с помощью этих флагов:
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Изменить: и удалите этот режим запуска из своего манифеста.
Надеюсь, это поможет
Используйте приведенный ниже код, может он поможет
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());
Похожие вопросы
Связанные вопросы
Новые вопросы
java
Java — это высокоуровневый объектно-ориентированный язык программирования. Используйте этот тег, если у вас возникли проблемы с использованием или пониманием самого языка. Этот тег часто используется вместе с другими тегами для библиотек и/или фреймворков, используемых разработчиками Java.
singleTask
илиsingleInstance
, может, это поможет. И я считаю, что тестирование со звуком могло быть некорректным. Когда я наблюдал за жизненным циклом активности, я использовал обратные вызовы журнала и жизненного цикла для печати сообщений.