How to edit/reset Alarm Manager?

前端 未结 2 1055
执念已碎
执念已碎 2021-01-05 11:28

I\'ve set up a Preference Screen in which i have a list preference which allows user to select time interval to notify them.

They can choose whether to

相关标签:
2条回答
  • 2021-01-05 11:35

    Follow these steps:

    1. Copy the following methods to your Setting.java file:

      private final int NOTIFICATION_TIMER = 11;
      
      public void setAlarm(Context mContext,int requestCode,long time) {
      
          Intent myIntent = new Intent(mContext, AlarmReceiver.class);
          PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, requestCode, myIntent,0);
      
          cancelAlarmIfExists(mContext,requestCode,myIntent);
      
          AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(ALARM_SERVICE);
          alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()+time), time, pendingIntent);
      }
      
      public void cancelAlarmIfExists(Context mContext,int requestCode,Intent intent){
          try {
              PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, requestCode, intent,0);
              AlarmManager am=(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
              am.cancel(pendingIntent);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      
    2. Call them from the onPreferenceChange() method. Like so:

      listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
      
              long time = 34352355253; // calculate millisecons from change value by user.
              setAlarm(Settings.this,NOTIFICATION_TIMER,time);
              return false;
          }
      });
      
    0 讨论(0)
  • 2021-01-05 11:58

    FLAG_CANCEL_CURRENT has the same effect as above answer

    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    
    0 讨论(0)
提交回复
热议问题