我爲android創建一個鬧鐘應用程序,出於某種原因,總有一些東西在我的報警中延遲20-60秒。我不知道爲什麼它使用setExact()方法的API發生作爲即時通訊19+報警應用程序不準確
我的代碼:
private void setAlarm() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mHour = mTimePicker.getHour();
mMinutes = mTimePicker.getMinute();
} else {
mHour = mTimePicker.getCurrentHour();
mMinutes = mTimePicker.getCurrentMinute();
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, mHour);
calendar.set(Calendar.MINUTE, mMinutes);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(EditAlarm.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(EditAlarm.this, 0, alarmIntent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
報警接收機
public class AlarmReceiver extends WakefulBroadcastReceiver {
public AlarmReceiver() {
}
@Override
public void onReceive(final Context context, Intent intent) {
Toast.makeText(context, "Alarm works", Toast.LENGTH_LONG).show();
Intent alarmIntent = new Intent(context, AlarmActivity.class);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarmIntent);
}
報警活動
public class AlarmActivity extends AppCompatActivity {
private Vibrator mVibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
// The ringing effects
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = { 0, 300, 200, 300, 100, 100 };
mVibrator.vibrate(pattern, 0);
// UI
Button stopButton = (Button) findViewById(R.id.finishButton);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mVibrator.cancel();
finish();
}
});
}
我在做什麼錯?提前致謝;)
首先,請注意你的'Calendar'代碼有缺陷,因爲你不處理其中'mHour'是之前,現在的情況下(例如,它剛剛在我所在的地方變成了中午,因此,從0到11的'mHour'是過去的)。除此之外,您正在測試的確切硬件是什麼,以及如何測試它?請記住,許多設備(包括所有運行的Android 6.0+)都具有可以忽略或延遲某些AlarmManager定時事件以節省電池的功能。 – CommonsWare