学习Android编程很困难,但我怀疑问题不一定是Android本身。我正在尝试制作一个(可切换的)自动消音器,让手机在学校开始时振动,一旦它结束就会进入常规模式。它也绝不能强迫这一点;即每次更改时它只会改变一次(例如,如果我将电话设置为在课余时间内振动,则不会在下一分钟将其更改回来)。这是我的代码:
public class TimeBroadcastReceiver extends BroadcastReceiver {
boolean previousState;
@Override
public void onReceive(Context context, Intent intent) {
Calendar now = GregorianCalendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
switch (day) {
case Calendar.MONDAY:
if (((hour == 7 && minute >= 40) || hour >= 7) && ((hour == 13 && minute <= 45) || hour <= 13)) {
if (!previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
previousState = true;
}
} else {
if (previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
previousState = false;
}
}
return;
case Calendar.TUESDAY:
case Calendar.WEDNESDAY:
case Calendar.THURSDAY:
case Calendar.FRIDAY:
if (((hour == 7 && minute >= 30) || hour >= 7) && ((hour == 14 && minute <= 40) || hour <= 14)) {
if (!previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
previousState = true;
}
} else {
if (previousState) {
manager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
previousState = false;
}
}
return;
}
}
}
反对所有逻辑,或者至少我希望对简单的布尔逻辑,振铃器在早上7点完全禁用自己(而不是星期一7:40和其他日子7:30),并重新启用自己准确地在星期一下午2点(而不是1:45)和下午3点准确地在其他日子(而不是2点40分)。我根本不知道它是如何产生这种结果的。想法?
此外,注册码以防万一:
TimeBroadcastReceiver receiver = new TimeBroadcastReceiver();
IntentFilter filter = new IntentFilter();
{
filter.addAction(Intent.ACTION_TIME_TICK);
}
public void setEnabled(boolean enabled) {
if (!this.enabled && enabled) {
registerReceiver(receiver, filter);
this.enabled = true;
} else if (this.enabled && !enabled) {
unregisterReceiver(receiver);
this.enabled = false;
}
}
这是从服务中调用的。