我有一个Android应用程序。我希望在特定时间发出警报让我们说10:30 AM&晚上7点30分,我每天都重复搜索,但没有任何工作> \ n 我试过这段代码:
//var
public int AM_IS_ON = 1288, PM_IS_ON = 98760, am_hr, pm_hr;
private String am;
private AlarmManager alarmManager;
private SharedPreferences sharedPrefs;
private PendingIntent pendingIntent;
//////after OnCreate() Method//////
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
am_hr = Integer.parseInt((sharedPrefs.getString("am_hr", "7")));
pm_hr = Integer.parseInt((sharedPrefs.getString("pm_hr", "5")));
boolean AM = sharedPrefs.getBoolean("isAM", true);
boolean PM = sharedPrefs.getBoolean("isPM", true);
boolean on_or_off = sharedPrefs.getBoolean("alarm_on_or_off", false);
if (on_or_off) {
if (AM) {
SetAlarm(am_hr, AM_IS_ON, PM_IS_ON);
} else {
Toast.makeText(MainActivity.this, R.string.alarm_is_off, Toast.LENGTH_SHORT).show();
}
public void SetAlarm(int hr, int am_uid, int pm_uid) {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
am = "AM";
Log.e("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hr);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
if (am.equals("AM")) {
am = "PM";
Log.e("MyActivity", "AM On");
calendar.set(Calendar.AM_PM, Calendar.AM);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, am_uid, myIntent, Intent.FILL_IN_ACTION);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
if (am.equals("PM")) {
Log.e("MyActivity", "PM On");
calendar.set(Calendar.AM_PM, Calendar.PM);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, pm_uid, myIntent, Intent.FILL_IN_ACTION);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
&安培;这是我的回忆者:
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
MainActivity inst = MainActivity.instance();
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
问题是当我打开MainActivity时SetAlarm()方法>>这是为了PM&上午 我想要的是在指定的时间内安排闹钟我该如何做到这一点?