2014-01-21 6 views
21

. Я использую этот код для отображения локального уведомления. Когда появляется уведомление, при щелчке уведомления нужно запустить ListActivity, но в устройстве Google nexus ListActiviy не запускается при нажатии на уведомление , но на другом устройстве этот код работает хорошо.Уведомление Нажмите, чтобы не запускать данное действие на телефонах Nexus.

Intent notificationIntent = new Intent(context, 
      ListActivity.class); 
    notificationIntent.putExtra("clicked", "Notification Clicked"); 
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // To open only one activity on launch. 
    PendingIntent pIntent = PendingIntent.getActivity(context, reqCode, 
      notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    NotificationManager nM = (NotificationManager) context 
      .getSystemService(Context.NOTIFICATION_SERVICE); 
    NotificationCompat.Builder notify = new NotificationCompat.Builder(
      context); 

    notify.setContentIntent(pIntent); 
    notify.setSmallIcon(R.drawable.app_icon); 
    notify.setContentTitle("Hello World"); 
    notify.setContentText(""); 
    notify.setAutoCancel(true); 
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    notify.setSound(alarmSound); 
    notify.setLights(Color.BLUE, 500, 1000); 
    nM.notify(reqCode, notify.build()); 

Добавление LogCat когда активность не запускается:

03-26 14:22:35.893: W/ActivityManager(515): Permission Denial: starting Intent { cmp=com.x.y/.music.ui.PlaybackActivity bnds=[42,101][636,186] (has extras) } from null (pid=-1, uid=10121) not exported from uid 10126 
03-26 14:22:35.893: W/ActivityManager(515): Unable to send startActivity intent 
03-26 14:22:35.893: W/ActivityManager(515): java.lang.SecurityException: Permission Denial: starting Intent { cmp=com.x.y/.music.ui.PlaybackActivity bnds=[42,101][636,186] (has extras) } from null (pid=-1, uid=10121) not exported from uid 10126 
03-26 14:22:35.893: W/ActivityManager(515):  at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:1186) 
03-26 14:22:35.893: W/ActivityManager(515):  at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:741) 
03-26 14:22:35.893: W/ActivityManager(515):  at com.android.server.am.ActivityManagerService.startActivityInPackage(ActivityManagerService.java:3300) 
03-26 14:22:35.893: W/ActivityManager(515):  at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:252) 
03-26 14:22:35.893: W/ActivityManager(515):  at com.android.server.am.PendingIntentRecord.send(PendingIntentRecord.java:192) 
03-26 14:22:35.893: W/ActivityManager(515):  at android.content.IIntentSender$Stub.onTransact(IIntentSender.java:64) 
03-26 14:22:35.893: W/ActivityManager(515):  at android.os.Binder.execTransact(Binder.java:404) 
03-26 14:22:35.893: W/ActivityManager(515):  at dalvik.system.NativeStart.run(Native Method) 
+0

В какой версии есть нексуса? kitkat (4.4)? – Hardik

+0

Да, KitKat 4.4 – Amrit

+0

ОК, это проблема !!! см. мой ответ – Hardik

ответ

0

Мой выше код работает хорошо для всех ОС версия, кроме Kitkat 4.4 и 4.4 + Но у меня есть решение i, поставьте ресивер в другой процесс, и он хорошо работает для всех ОС Android. сий ...

Как этот способ ..

деятельность андроид: имя = андроида "NotifyReciever.": процесс = ": удаленный"

и мы можем больше узнать о процессах здесь ....

Should I use android: process =":remote" in my receiver?

65

Об этом сообщается вопрос для KitKat 4.4 не открытия активности при нажмите на уведомление здесь вопрос URL

http://code.google.com/p/android/issues/detail?id=63236

http://code.google.com/p/android/issues/detail?id=61850

предложил временное решение отменить существующие PendingIntent или использовать PendingIntent.FLAG_CANCEL_CURRENT

ИЛИ

Попробуйте ниже

Добавление флага в Activity в AndroidManifiest.xml

android:exported="true" 
+7

Одно из предложений в этих ссылках , добавив * android: exported = "true" * в тегах "activity" для целевой активности. Исправлена ​​проблема с KitKat. Спасибо вам за ссылки. – mass

+2

PendingIntent.FLAG_CANCEL_CURRENT Исправлена ​​ошибка –

+1

Это решило мою проблему на kitkat, однако я могу только открыть активность ПОСЛЕ перезагрузки устройства, кто-то еще столкнулся с этим? т.е. перед перезапуском устройства я нажимаю уведомление и ничего не происходит, но после перезагрузки, если я нажимаю кнопку, он открывает активность –

3

Вы также можете добавить PendingIntent.FLAG_ONE_SHOT, чтобы исправить это.

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

Решение, предложенное mass работал для меня, и это не очень просто, нет необходимости менять код:

В вашем AndroidManifest.xml добавить следующий атрибут к вашему <activity> тегу:

android:exported="true" 

Он работал в Samsung Galaxy Young 2 с Android 4.4.2.

10

Эта проблема известна под Android Kitkat 4.4 и Lollipop. Пожалуйста, добавьте:

android:exported="true" 

в андроиде манифеста внутри тега действия, которые, как предполагается, будет открыты после нажатия уведомления от строки состояния

1

Добавить андроид: экспортироваться = «истина» в проявленном

<activity 
      android:name=".ListActivity" 
      android:label="ListActivity" 
      android:exported="true"> 
</activity> 

ListActivity - это активность, которая будет открыта при нажатии на уведомление.

0

Попробуйте заменить этот

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // To open only one activity on launch. 
PendingIntent pIntent = PendingIntent.getActivity(context, reqCode, 
     notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

в

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // To open only one activity on launch. 
PendingIntent pIntent = PendingIntent.getActivity(context, reqCode, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); 

он будет работать на всех версиях даже с KitKat также.

Примечание: Действие будет запущено вне контекста существующего действия, поэтому вы должны использовать флаг запуска Intent.FLAG_ACTIVITY_NEW_TASK в намерении.

0

Если android:exported="true" не подходит для вас, просто переназначите намерение своей деятельности LAUNCHER.

В вашей LAUNCHER проверки активности для входящих уведомлений следующим образом:

if(getIntent().hasExtra("type") && getIntent().getStringExtra("type").compareTo("notification")==0){ 
     Intent redirect = new Intent(getIntent()); 
     redirect.setClass(this,YourNotificationActivity.class); 
     startActivity(redirect); 
} 

Если вам нужно фильтровать намерение затем использовать:

Intent incoming = getIntent(); 
if(intent.hasExtra("type") && intent.getStringExtra("type").compareTo("notification")==0){ 
    Intent outgoing = new Intent(this, YourNotificationActivity.class); 
    outgoing.putExtra("title", incoming.getStringExtra("title"); 
    outgoing.putExtra("content", incoming.getStringExtra("content"); 
    startActivity(outgoing); 
} 
0

Я надеюсь, что это поможет и.

long uniqueId = System.currentTimeMillis();

/** This is the part to let your application recognise difference notification when the user click on the notification. 
    * You could use any unique string to represent your notification. But be sure each notification have difference action name. 
    **/ 
    taskDetailIntent.setAction("notifi" + uniqueId); 


    PendingIntent contentIntent = PendingIntent. 
      getActivity(this, 0, taskDetailIntent, PendingIntent.FLAG_ONE_SHOT); 

    builder.setContentIntent(contentIntent); 

    /** Set the unique id to let Notification Manager knows this is a another notification instead of same notification. 
    * If you use the same uniqueId for each notification, the Notification Manager will assume that is same notification 
    * and would replace the previous notification. **/ 
    notificationManager.notify((int) uniqueId, builder.build()); 
Смежные вопросы