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上? –