Android:如何修复通知的递增setNumber()?

时间:2018-05-14 06:31:31

标签: android android-notifications notificationmanager jobintentservice

我使用从JobIntentService启动的BroadcastReceiver向用户发送截止日期的通知。当另一个到期日的通知接近时,我只想更新现有的通知并将setNumber()指标递增+1。第一个通知会增加" totalMesssages"通过+1正确变量,setNumber()显示" 1"在“通知”下拉对话框中。下一个Notification正确触发,但setNumber()不会增加+1到" 2"。它停留在" 1"。

我在这里缺少什么?

public class AlarmService extends JobIntentService {

    static final int JOB_ID = 9999;
    private int totalMessages = 0;

    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, AlarmService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {

    sendNotification();
    }

    private void sendNotification() {

        int notifyID = 1;

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

        if (notificationManager != null) {
         notificationManager.createNotificationChannel(notificationChannel);
        }
    }

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setDefaults(Notification.DEFAULT_ALL)
        .setSmallIcon(R.drawable.ic_announcement_white_24dp)
        .setContentText("")
        .setNumber(++totalMessages);

    Intent intent = new Intent(this, MainActivity.class);        
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(contentIntent);
    mBuilder.setAutoCancel(true);;

    if (notificationManager != null) {
        notificationManager.notify(notifyID, mBuilder.build());
    }
  }
}   

1 个答案:

答案 0 :(得分:1)

public static String convertTimeintoHrs(String hr, String mn){

        return hr + Integer.parseInt(mn)/60;
}

每次从private int totalMessages = 0; 启动JobIntentService时,都会初始化为0.

其中一个解决方案是将totalMessage存储在SharedPreferences中,并在AlarmService中使用它。

BroadcastReceiver

您可以在代码中的通知构建器之前插入它。