【发布时间】:2016-11-09 21:40:46
【问题描述】:
我试图让用户选择闹钟时间,但即使我选择其他偏好,闹钟也会每 15 分钟触发一次“这是默认设置”
这是与我的 MainActivity 中的问题相关的代码
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private static String reminder;
private static AlarmManager am;
private ImageButton btn;
private ImageButton cancel;
private EditText et;
private Intent intent;
private PendingIntent pend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize variables
btn = (ImageButton) findViewById(R.id.imageButton2);
cancel = (ImageButton) findViewById(R.id.imageButton);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
// create intents
intent = new Intent(getApplicationContext(), Notifications.class);
pend = getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
// get the user preference
String sel = sp.getString("repeatPref", "1");
final String repeat[] = getResources().getStringArray(R.array.settings_repeat_by_labels);
final int ss = Integer.parseInt(sel);
// action when user presses the "Tweak" button
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pend.cancel();
am.cancel(pend);
// initialize pend and AlarmManager
pend = getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
// if the user didn't type anything
Calendar calendar = Calendar.getInstance();
// notify at different times
if (repeat[ss - 1].equals("15 MINUTES")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 60*1000 ,60*1000, pend);
}
} else if (repeat[ss - 1].equals("1 HOUR")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 120 * 1000, 120 * 1000, pend);
}
} else if (repeat[ss - 1].equals("2 HOURS")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + AlarmManager.INTERVAL_HOUR * 2, AlarmManager.INTERVAL_HOUR * 2, pend);
}
});
另一个取消闹钟的按钮
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
am.cancel(pend);
pend.cancel();
Toast.makeText(MainActivity.this,"All cleared", Toast.LENGTH_LONG).show();
}
});
我在 onCreate 方法和第二次按下“btn”时创建挂起和警报,因为我正在创建另一个按钮来取消它,我尝试“长时间”检查 PendingIntent 是否“挂起” " 和 AlarmManager "am" 已经存在或不存在,然后根据结果取消它,但我失败了,所以我认为这种方法可能有效
现在,每次用户想要取消警报并打开应用程序时,它都会创建新的挂起意图和警报管理器,因此如果用户在没有先按“btn”的情况下按下取消按钮,应用程序不会崩溃并且警报已经工作被取消..我怀疑这是我现在遇到的问题的一部分
我知道内容很多,但我尝试尽可能简单地解释......感谢您花时间阅读所有内容!
【问题讨论】:
标签: android sharedpreferences alarmmanager android-pendingintent