我正在尝试让用户选择闹钟时间,但即使我选择其他偏好,闹钟也会每隔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();
}
});
我正在创建pend和Alarm在onCreate方法中,第二次按下“btn”,因为我正在创建另一个按钮来取消它,我试着“长时间”检查PendingIntent是否“挂起” “和AlarmManager”am“已经存在或者没有然后取决于结果取消它但我失败了所以我认为这种方法可能有效
现在,每当用户想要取消闹钟并打开应用程序时,它将创建新的待定意图和警报管理器,因此如果用户按下取消按钮而不先按“btn”应用程序不会崩溃并且已经发出警报工作被取消..我怀疑这是我现在有问题的一部分
我知道这很多东西,但我尝试尽可能简单地解释..感谢花时间阅读所有这些!
答案 0 :(得分:0)
我的应用没有回复我的更改,因为我在点击" btn"之前检索了共享偏好设置。将共享首选项部分移动到onClick方法后,它得到修复。