Я использую этот код, чтобы показать локальное уведомление, а когда появляется уведомление, при щелчке уведомления хотите запустить ListActivity, но на устройстве Google nexus ListActiviy
не запускается при нажатии на уведомление, а на другом устройстве этот код работает хорошо.
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.xy/.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.xy/.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)
Это сообщенная проблема для 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"
Эта проблема известна для Android Kitkat 4.4 и Lollipop. Пожалуйста, добавьте :
android:exported="true"
В андроиде манифест внутри тега активности, который должен быть открыт после нажатия уведомления из строки состояния
Вы также можете добавить PendingIntent.FLAG_ONE_SHOT
чтобы исправить это.
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Добавить android: exported = "true" в манифесте
<activity android:name=".ListActivity" android:label="ListActivity" android:exported="true"> </activity>
ListActivity – это активность, которая будет открыта при нажатии на уведомление.
Попробуйте заменить это
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 в Intent.
Мой выше код работает хорошо для всех версий ОС, кроме Kitkat 4.4 и 4.4 + Но у меня есть решение i, поместите ресивер в другой процесс, и он хорошо работает для всех версий ОС Android …
Вот так ..
Активность android: name = ". NotifyReciever" android: process = ": remote"
И мы можем узнать больше о процессах здесь ….
Должен ли я использовать android: process = ": remote" в моем приемнике?
Решение, предложенное mass
, сработало для меня, и это очень просто, не нужно менять код:
В AndroidManifest.xml добавьте следующий атрибут в свой <activity>
:
android:exported="true"
Он работал в Samsung Galaxy Young 2 с Android 4.4.2.
Если 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); }