0
我的應用程序包含兩種方法,即一次性鬧鐘和每天重複鬧鐘,我需要根據我的要求設置鬧鐘。當我設置一次報警它工作正常,但是當我設置重複報警它不工作。我也一直在遵循以下方法,但它確實對我有用。如何在android中安排重複鬧鐘和一次鬧鐘
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour); // hour - user selected hour
calendar.set(Calendar.MINUTE, minute); // minute -user selected minute
// setRepeating() lets you specify a precise custom interval--in this case,
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
這裏是我的片段一次和重複報警的方法。
private SimpleDateFormat EEE_DD_MMM_YYYY_HH_MM_SS_A_Formatter = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss a"); //Tue, 07 Mar 2017 10:50:00 a.m.
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getBaseContext(), alarmId, intent, 0); // where alarmId is autoIncrement
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
try {
Date alarmDate = EEE_DD_MMM_YYYY_HH_MM_SS_A_Formatter.parse(getDateTime()); // where we get both time and date from both pickers respectively.
if (oneTimeAlarm) {
Logs.i(TAG,"one time alarm");
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDate.getTime(), pendingIntent);
Log.i(TAG,"one time alarm set!");
} else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmDate.getTime(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.i(TAG,"repeat alarm set!");
}
} catch (Exception e) {
e.printStackTrace();
}
這裏是我的報警接收器類文件
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Vibrator vib = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE); //for Vibration
vib.vibrate(2000);
showNotification(context);
}
private void showNotification(Context context) {
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,alarmId,intent, 0);
// NotificationCompat
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText("text");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());}}
上面的代碼火警12:30,那麼你可以你扔通知,每天上班後,使用相同的代碼在服務 –
我已經取代了代碼,報警有在當天開槍,但是當我改變日期(比如說,明天)警報沒有開火。 – Karthik
你有沒有把上面的代碼放在你的服務或者broadcat上? –