PendingIntent не отправляет дополнения Intent
Моя MainActicity
запускает RefreshService
с Intent
который имеет boolean
isNextWeek
.
Мой RefreshService
создает Notification
которое запускает мою MainActivity
когда пользователь нажимает на нее.
это выглядит так:
Log.d("Refresh", "RefreshService got: isNextWeek: " + String.valueOf(isNextWeek));
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra(MainActivity.IS_NEXT_WEEK, isNextWeek);
Log.d("Refresh", "RefreshService put in Intent: isNextWeek: " + String.valueOf(notificationIntent.getBooleanExtra(MainActivity.IS_NEXT_WEEK,false)));
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder = new NotificationCompat.Builder(this).setContentTitle("Title").setContentText("ContentText").setSmallIcon(R.drawable.ic_notification).setContentIntent(pendingIntent);
notification = builder.build();
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_REFRESH, notification);
Как вы можете видеть notificationIntent
должны иметь boolean
дополнительное IS_NEXT_WEEK
со значением isNextWeek
, который ставится в PendingIntent
.
Когда я isNextWeek
сейчас это Notification
я всегда получаю false
как значение isNextWeek
Вот как я получаю значение в MainActivity
:
isNextWeek = getIntent().getBooleanExtra(IS_NEXT_WEEK, false);
Журнал:
08-04 00:19:32.500 13367-13367/de.MayerhoferSimon.Vertretungsplan D/Refresh: MainActivity sent: isNextWeek: true
08-04 00:19:32.510 13367-13573/de.MayerhoferSimon.Vertretungsplan D/Refresh: RefreshService got: isNextWeek: true
08-04 00:19:32.510 13367-13573/de.MayerhoferSimon.Vertretungsplan D/Refresh: RefreshService put in Intent: isNextWeek: true
08-04 00:19:41.990 13367-13367/de.MayerhoferSimon.Vertretungsplan D/Refresh: MainActivity.onCreate got: isNextWeek: false
Когда я непосредственно запускаю MainActivity
с Intent
с "sNextValue", как это:
Intent i = new Intent(this, MainActivity.class);
i.putExtra(IS_NEXT_WEEK, isNextWeek);
finish();
startActivity(i);
все работает отлично, и я получаю true
когда isNextWeek
это true
.
Что я делаю не так, что всегда есть false
значение?
ОБНОВИТЬ
это решает проблему: qaru.site/info/63532/...
Цитата:
Я подозреваю, что, поскольку в Intent изменяются только дополнительные PendingIntent.getActivity(...)
фабричный метод PendingIntent.getActivity(...)
просто повторно использует старое намерение в качестве оптимизации.
В RefreshService попробуйте:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Увидеть:
http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT
ОБНОВЛЕНИЕ 2
Смотрите ответ ниже, почему лучше использовать PendingIntent.FLAG_UPDATE_CURRENT
.
Ответы
Ответ 1
Использование PendingIntent.FLAG_CANCEL_CURRENT не является хорошим решением из-за неэффективного использования памяти. Вместо этого используйте PendingIntent.FLAG_UPDATE_CURRENT.
Используйте также Intent.FLAG_ACTIVITY_SINGLE_TOP (действие не будет запущено, если оно уже запущено в верхней части стек истории).
Intent resultIntent = new Intent(this, FragmentPagerSupportActivity.class).
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
resultIntent.putExtra(FragmentPagerSupportActivity.PAGE_NUMBER_KEY, pageNumber);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
Тогда:
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
int startPageNumber;
if ( savedInstanceState != null)
{
startPageNumber = savedInstanceState.getInt(PAGE_NUMBER_KEY);
//so on
Теперь он должен работать.
Если вы все еще не ожидали поведения, попробуйте реализовать обработчик событий void onNewIntent(Intent intent)
, таким образом вы сможете получить доступ к новому намерению, которое было вызвано для активности (что не то же самое, что просто вызвать getIntent(), это всегда будет верните первое намерение, которое запустило вашу деятельность.
@Override
protected void onNewIntent(Intent intent) {
int startPageNumber;
if (intent != null) {
startPageNumber = intent.getExtras().getInt(PAGE_NUMBER_KEY);
} else {
startPageNumber = 0;
}
}
Ответ 2
Я думаю, вам нужно обновить Intent
, когда вы получите новый, переопределив onNewIntent(Intent)
в своей деятельности. Добавьте в свою деятельность следующее:
@Override
public void onNewIntent(Intent newIntent) {
this.setIntent(newIntent);
// Now getIntent() returns the updated Intent
isNextWeek = getIntent().getBooleanExtra(IS_NEXT_WEEK, false);
}
Edit:
Это необходимо, только если ваша активность уже запущена при получении намерения. Если ваша деятельность запущена (и не только возобновлена) по намерению, тогда проблема находится в другом месте, и мое предложение не может ее исправить.
Ответ 3
Следующий код должен работать: -
int icon = R.drawable.icon;
String message = "hello";
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("isNexWeek", true);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, pIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
В MainActivity onCreate:
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("isNextWeek")) {
boolean isNextWeek = getIntent().getExtras().getBoolean("isNextWeek");
}