2015-04-24 3 views
1

Я прочитал (почти) все другие вопросы, связанные с той же проблемой здесь, в StackOverflow.Ещё одно Уведомление о недопустимости

Проблема обычная: когда я нажимаю на Notification, опубликованный моим приложением, связанный Activity не запускается. Это код:

NotificationManager notificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

... String json is prepared ... 
Intent intentForActivity = new Intent(this, MyActivity.class); 

Bundle extras = new Bundle(); 
extras.putString(Activity.KEY_JSON, json); 
intentForActivity.setFlags(
     Intent.FLAG_ACTIVITY_NEW_TASK | 
     Intent.FLAG_ACTIVITY_CLEAR_TOP | 
     Intent.FLAG_ACTIVITY_CLEAR_TASK); 
intentForActivity.putExtras(extras); 

PendingIntent pendingIntent = 
    PendingIntent.getActivity(this, 
           0, 
           intentForActivity, 
           PendingIntent.FLAG_UPDATE_CURRENT); 

NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 

... various builder methods for icon, title, message ... 

builder.setContentIntent(pendingIntent); 
notificationManager.notify(NOTIFICATION_ID++, builder.build()); 

Некоторые примечания:

  • Я пробовал различные флаги и перестановки, ничего не изменилось;
  • Мне пришлось поставить PendingIntent.FLAG_UPDATE_CURRENT за то, что String json в extras обновлен, в противном случае Android сохранился с использованием первого.
+1

новый Intent (это, Activity.class); // Вы помещаете здесь «Активность» или свое собственное название деятельности, которое вы хотите запустить? – Sharj

+0

Извините. Я только что отредактировал этот вопрос. Спасибо. –

ответ

0

Это то, что я использовал, и это сработало для меня. Код является самоочевидным.

private void showNotification(final String title, String text, int ID, boolean showTimeStamp) { 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) //Use a builder 
      .setContentTitle(title) // Title 
      .setContentText(text) // Message to display 
      .setTicker(text).setSmallIcon(R.drawable.ic_notif_small) // This one is also displayed in ticker message 
      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bulb)); // In notification bar 

    Intent resultIntent = new Intent(this, MainActivity.class); 
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
    stackBuilder.addParentStack(MainActivity.class); 
    stackBuilder.addNextIntent(resultIntent); 
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 
    mBuilder.setContentIntent(resultPendingIntent); 

    //mBuilder.addAction(R.drawable.bulb_small, "OK", resultPendingIntent); 

    Notification notification = mBuilder.build(); 
    notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS | Notification.DEFAULT_SOUND; 
    notification.defaults |= Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE; 

    long time = 0; 
    if (showTimeStamp) 
     Calendar.getInstance().getTimeInMillis(); 
    else 
     time = android.os.Build.VERSION.SDK_INT >= 9 ? -Long.MAX_VALUE : Long.MAX_VALUE; 

    notification.when = time; 

    mNotificationManager.cancel(ID); 
    mNotificationManager.notify(ID, notification); 
} 

А также добавить этот android:launchMode="singleTask" к вашему манифесту, где у вас есть ваша основная деятельность

Пример:

<activity 
    android:name=".MainActivity" 
    android:label="@string/app_name" 
    android:launchMode="singleTask" > 
    <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 

     <category android:name="android.intent.category.LAUNCHER" /> 
    </intent-filter> 
</activity> 
+0

Благодарим вас за ответ, но я предпочел бы сохранить код как можно более простым: согласно учебникам Google, это не должно быть так сложно. –

+0

Удалите время, связанное со звуком, и светодиод мигает, если вам это не нужно, но appart from is is does not get any sinpler –

Смежные вопросы