我已经设置了一个首选项屏幕,其中我有一个列表首选项,允许用户选择时间间隔来通知他们。
他们可以选择是否每隔2,4,8,10或12小时通知他们。
以下是我的列表首选项:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<ListPreference
android:title="Notification Timer"
android:summary="Select when to Notify"
android:dialogTitle="Show Notification after every:"
android:positiveButtonText="OK"
android:negativeButtonText="Cancel"
android:entries="@array/entries"
android:entryValues="@array/entries"
android:key="listPrefs" />
</PreferenceScreen>
这是我的Settings.class文件:
public class Settings extends PreferenceActivity implements OnPreferenceChangeListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
ListPreference listPreference = (ListPreference) findPreference("listPrefs");
listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return false;
}
});
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
return false;
}
}
我希望每当用户更改通知他/她的时间间隔时更新或重置警报。例如 - 如果用户选择4小时而不是他/她必须在4小时后得到通知,或者如果用户选择10小时,则他/她必须在10小时后得到通知!
答案 0 :(得分:4)
请按照以下步骤操作:
将以下方法复制到 Setting.java 文件中:
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();
}
}
从onPreferenceChange()
方法调用它们。像这样:
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;
}
});
答案 1 :(得分:1)
FLAG_CANCEL_CURRENT与上述答案具有相同的效果
PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);