2013-05-31 1 views
6

Я хочу, чтобы мой Android пребывания уведомления, даже если пользователь нажимает кнопку или щелкает ясно все ...Как сделать уведомление несократимы/неустранимые

Сейчас он остается иногда, и получает удалены иногда, и я не уверенный, что вызывает это.

Вот мой код для уведомления:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
public static void createNotification() 
{ 
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); 

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context) 
          .setContentTitle("Wolftech Field Agent") 
          .setContentText("Getting Status") 
          .setSmallIcon(R.drawable.ic_launcher) 
          .setOngoing(true) 
          .setAutoCancel(false); 

    Intent intent = new Intent(context, FieldAgent.class); 
    intent.setAction(Intent.ACTION_MAIN); 
    intent.addCategory(Intent.CATEGORY_LAUNCHER); 

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 
    stackBuilder.addParentStack(FieldAgent.class); 
    stackBuilder.addNextIntent(intent); 

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

    builder.setContentIntent(pendingIntent); 

    notificationManager.notify(NOTIFICATION_ID, builder.build()); 
} 

public static void updateNotificationText(String inString) 
{ 
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context) 
              .setContentText(inString) 
              .setContentTitle("Wolftech Field Agent") 
              .setSmallIcon(R.drawable.ic_launcher) 
              .setOngoing(true) 
              .setAutoCancel(false); 

    Intent intent = new Intent(context, FieldAgent.class); 
    intent.setAction(Intent.ACTION_MAIN); 
    intent.addCategory(Intent.CATEGORY_LAUNCHER); 

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 
    stackBuilder.addParentStack(FieldAgent.class); 
    stackBuilder.addNextIntent(intent); 

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

    builder.setContentIntent(pendingIntent); 

    notificationManager.notify(NOTIFICATION_ID, builder.build()); 
} 

public static void cancelNotification() 
{ 
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationManager.cancel(NOTIFICATION_ID); 
} 

ответ

1

Okey, я понял, что код, который я опубликовал, на самом деле хорош.

Что происходит, когда я нажимаю уведомление, он снова вызывает onCreate(), а затем после случайного интервала он вызывает onDestroy().

В onDestroy() У меня был метод cancelNotification(), поэтому, если onDestroy() получил вызов после onCreate(), он удалил мое уведомление.

Это подводит меня к новому вопросу: почему это разрушает и воссоздает мою деятельность после того, как я следил за каждым ответом, который я мог найти здесь, как остановить это?

Вы можете найти этот вопрос здесь How to make notification resume and not recreate activity? если вы хотите, чтобы помочь мне решить эту проблему ...

1

вы пытаетесь

PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 
notificationManager.cancel(pendingIntent); 
+0

Я думаю, что вы неправильно поняли вопрос (или я не понимаю ваш ответ ...) Я не хочу отменять уведомление (ну, когда я это решаю), я хочу, чтобы уведомление оставалось на каждый таймер пользователь нажимает на нее или нажимает «очистить все». – CeeRo

4

Я считаю, что вы ищете этот флаг:

Notification.FLAG_NO_CLEAR 

Добавить этот флаг в уведомлении ,

+0

Кажется, что он остается, когда я нажимаю кнопку «Очистить все», но иногда он исчезает, когда я нажимаю на него. Weird – CeeRo

+0

Прямо сейчас я склоняюсь к воссозданию/обновлению уведомления onResume(), поэтому он получает переделку после каждого щелчка, похоже, не существует способа убедиться, что он действительно остается в ином случае ... – CeeRo

+0

Я понял что вызывает его, проверьте мой ответ – CeeRo

8

Я думаю, что вы ищете текущие уведомления, в том случае, если вы используете NotificationCompat.Builder, вы можете использовать:

NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this); 
mNotifyBuilder.setOngoing(true); 
+0

Должно ли это быть передним планом? –

-1

У меня была эта проблема тоже. Мое решение является добавление дополнительных на функцию, которая создает пристальный

 private void addNotification(String headLine, String info, Context context) { 
     mBuilder = 
       new NotificationCompat.Builder(context) 
         .setSmallIcon(R.drawable.icon) //R.drawable.icon 
         .setContentTitle(headLine) 
         .setContentText(info) 
         .setOngoing(true) 
         .setAutoCancel(false); 
// Creates an explicit intent for an Activity in your app 
     Intent resultIntent = new Intent(context, MainActivity.class); 
     resultIntent.putExtra("FROM_NOTIF", true); 
// 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(context); 
// 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); 

     mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
// mId allows you to update the notification later on. 
     //  mBuilder.setf |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; 
     mNotificationManager.notify(mNotification_id, mBuilder.build()); 
    } 

и В MainActivity:

@Override 
protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); 
    if (intent.getBooleanExtra("FROM_NOTIF", false)) { 
     addNotification(...) 
      ... call the function that adds the notification again ..} 

Так дело в том, что уведомление выключается после того, как пользователь нажмет на нее, но чем вы можете уведомлять о деятельности, которая начала использовать onNewIntent(), проверить намерение там, и если вы узнаете, что это произошло из уведомления, установите его снова.

+0

Хотя этот код может ответить на вопрос, предоставление дополнительного контекста относительно того, как и/или почему оно решает проблему, улучшит долгосрочную ценность ответа. Пожалуйста, прочтите это [как ответить] (http: // stackoverflow.com/help/how-to-answer) для обеспечения качественного ответа. – thewaywewere

+0

Отредактировал мой ответ –

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