【问题标题】:Android Alarm firing instantly when I set alarm on earlier hour or after midnight [duplicate]当我在早些时候或午夜之后设置闹钟时,Android 闹钟会立即触发 [重复]
【发布时间】:2018-05-25 06:59:28
【问题描述】:

我正在 Android Studio 中创建我的第一个应用。我的闹钟几乎可以正常工作,但是当我将闹钟设置为比当前时间早一小时或午夜之后,我的闹钟会立即响起。例如,当前时间是 17:00,当我将闹钟设置为 17:05 时一切正常,但是当闹钟设置为 16:00 或 00:05 时,闹钟会立即响起。我将感谢您的所有建议。这是我的代码:

Alarm.java

public class Alarm extends AppCompatActivity {
private TimePicker timePicker;
private Button vibrationButton;
private Button soundButton;
private Button noteButton;
private Button saveButton;
private Button cancelButton;
private CheckBox wifiCheckBox;
private CheckBox soundCheckBox;
private CheckBox bluetoothCheckBox;
private TextView textView;
private BluetoothAdapter mBluetoothAdapter;
private WifiManager wiFi;
private AudioManager audioManager;
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private Intent intent;
private int hour;
private int minute;
private String minuteString;
private String hourString;
private void turnOnWifi() {
    if (wifiCheckBox.isChecked())
        wiFi.setWifiEnabled(true);
}

private void turnOnBluetooth() {
    if (bluetoothCheckBox.isChecked())
        mBluetoothAdapter.enable();
}

private void turnOnSound() {
    if (soundCheckBox.isChecked())
        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
private void notification() {
    Intent intentNotification = new Intent(this.getApplicationContext(),Alarm.class);
    PendingIntent pendingIntentNotification = PendingIntent.getActivity(this, 0, intentNotification, 0);
    Notification notification = new Notification.Builder(this)
            .setContentTitle("Alarm")
            .setContentText("Next alarm: " + hourString + ":" + minuteString)
            .setContentIntent(pendingIntentNotification)
            .setAutoCancel(false)
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();
    notificationManager.notify(0, notification);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm);
    timePicker = findViewById(R.id.timePicker);
    vibrationButton = findViewById(R.id.vibrationButton);
    soundButton = findViewById(R.id.soundButton);
    noteButton = findViewById(R.id.noteButton);
    saveButton = findViewById(R.id.saveButton);
    cancelButton = findViewById(R.id.cancelButton);
    wifiCheckBox = findViewById(R.id.wifiCheckBox);
    soundCheckBox = findViewById(R.id.soundCheckBox);
    bluetoothCheckBox = findViewById(R.id.bluetoothCheckBox);

    textView = findViewById(R.id.textView);
    wiFi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    intent = new Intent(this, AlarmReceiver.class);
    timePicker.setIs24HourView(true);
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar calendar = Calendar.getInstance();
            if (calendar.before(Calendar.getInstance()))
                calendar.add(Calendar.DATE, 1);
            if (Build.VERSION.SDK_INT >= 23) {
                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
                calendar.set(Calendar.MINUTE, timePicker.getMinute());
                calendar.set(Calendar.SECOND, 0);
                hour = timePicker.getHour();
                minute = timePicker.getMinute();
            } else {
                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
                calendar.set(Calendar.SECOND, 0);
                hour = timePicker.getCurrentHour();
                minute = timePicker.getCurrentMinute();
            }
            hourString = String.valueOf(hour);
            minuteString = String.valueOf(minute);
            if (hour == 0)
                hourString = "0" + hourString;
            if (minute < 10)
                minuteString = "0" + minuteString;
            textView.setText("Next alarm: " + hourString + ":" + minuteString);
            intent.putExtra("extra", "on");
            setAlarm(calendar.getTimeInMillis());
     //       notification();
        }
    });

cancelButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        textView.setText("Alarm off!");
        alarmManager.cancel(pendingIntent);
        intent.putExtra("extra", "off");
        sendBroadcast(intent);
     //   notificationManager.cancel(0);
    }
});
}

private void setAlarm(long timeInMillis) {
    pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
}

}

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Log.e("test","test123");
    String getState = intent.getExtras().getString("extra");
    Log.e("Key is: ", getState);
    Intent intentService = new Intent(context, RingtoneService.class);
    intentService.putExtra("extra", getState);
    context.startService(intentService);
}

}

RingtoneService.java

public class RingtoneService extends Service {
private MediaPlayer mediaPlayer;
boolean isRunning;
int startId;

@Override
public void onDestroy() {
    Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
    this.isRunning = false;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
    String state = intent.getExtras().getString("extra");
    assert state != null;
    switch (state) {
        case "on":
            startId = 1;
            break;
        case "off":
            startId = 0;
            break;
        default:
            startId = 0;
            break;
    }
    if (!this.isRunning && startId == 1){
        mediaPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
        mediaPlayer.start();
        this.isRunning = true;
        this.startId = 0;
    }
    else if (this.isRunning && startId == 0){
        mediaPlayer.stop();
        mediaPlayer.reset();
        this.isRunning = false;
        this.startId = 0;
    }
    else if (!this.isRunning && startId == 0){
        this.isRunning = false;
        this.startId = 0;
    }
    else if (this.isRunning && startId == 1){
        this.isRunning = true;
        this.startId = 1;
    }

    return START_NOT_STICKY;
}

}

【问题讨论】:

  • 设置calendar后,设置闹钟前,需要检查是否是过去,如果是则添加一天。链接副本的答案中有一个示例。
  • 感谢您的回答。是的,你是对的,我的主题是重复的,但只是因为我尝试了第一个主题的解决方案,但没有奏效。那是行不通的,因为我犯了错误并将此代码粘贴到错误的位置:) 谢谢:)

标签: java android alarmmanager


【解决方案1】:

当然可以……它本来就是这样工作的。 Android 会识别到时间已经过去,因此它会发出警报,即使已经很晚了。

您可以确保为闹钟设置的时间在当前时间之后。只需计算这个差异:

int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();

如果 diff 大于 0,则在日历中添加一天 (targetCal) 现在,您设备的时间将早于(而不是晚于)下一个预定的闹钟时间。


Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);

if(calendar.before(Calendar.getInstance())) {
    calendar.add(Calendar.DATE, 1);
}

alarmManager.set(AlarmManager.RTC_WAKEUP,
    calendar.getTimeInMillis(), pendingDinnerIntent);

【讨论】:

  • 感谢您的回答 :) 我做得很好,但我将代码粘贴到了错误的位置。谢谢你在我的代码中找到了这个 :) 效果很好 :)
猜你喜欢
  • 2012-07-08
  • 2016-07-31
相关资源
最近更新 更多