2015-11-26 95 views
0

BootCompletedReceiver在啓動時運行後臺服務,因此生命週期的通知在運行時在通知欄中顯示。當我從通知欄中刪除通知時,我希望在15分鐘後看到它,但我不知道,它隨機出現。每15分鐘啓動一次通知的報警管理器

我的代碼有什麼問題?

public class BootCompletedReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
    Intent serviceIntent = new Intent(context, BirthdayNotifyService.class); 
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); 
    context.startService(serviceIntent); 
    setAlarm(context, pendingIntent); 
} 

private void setAlarm(Context context, PendingIntent pendingIntent) { 
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), 1000 * 60 * 2, pendingIntent); 
} 


public class BirthdayNotifyService extends Service { 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    createNotifications(); 
    return super.onStartCommand(intent, flags, startId); 
} 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

private void createNotifications() { 
    // Fetching contacts from the Contacts application 
    ArrayList<MyContact> contactsList = BirthdayDataFactory.getContacts(this); 
    // Going trough the contacts list and creating notifications for each contact that has birthday 
    for (int i = 0; i<contactsList.size(); i++) { 
     if(contactsList.get(i).hasBirthday()) { 
      Intent intent = new Intent(this, MainActivity.class); 
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); 
      // Creating a notification builder 
      NotificationCompat.Builder builder = 
        (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
          .setSmallIcon(R.drawable.ic_notification) 
          .setContentTitle("Birthday Notifier") 
          .setContentText(contactsList.get(i).getName() + " has a Birthday today!") 
          .setContentIntent(pendingIntent); 
      // Creating a notification manager 
      NotificationManagerCompat manager = NotificationManagerCompat.from(this); 
      manager.notify(i, builder.build()); 
     } 
    } 
} 

}

回答

0

「當我從通知欄中刪除通知,我希望看到 它15分鐘後說:」

如果這是你要發生什麼,您不需要服務或重複警報。

你應該做的是在你的NotificationBuilder上使用.setDeleteIntent(Intent intent),傳入一個意圖,在15分鐘內再次運行通知代碼,看起來像這樣,而不是你目前在setAlarm():

alarmManager.set(AlarmManager.ELAPSED_REALTIME, 1000*60*15, pendingIntent); 

你正在做在你的代碼是什麼如下:

context.startService(serviceIntent);
啓動服務立即用於顯示通知

setAlarm(context, pendingIntent);

設置其顯示的通知後,立即觸發報警,並每2分鐘後


我建議更多的究竟讀了你正在使用的每個方法/類都是。

0

您可以用alarmManager.INTERVAL_FIFTEEN_MINUTES代替1000 * 60 * 2