我正在尝试在用户指定的时间触发警报。因此,我有timepickerdialog
,用户可以从中选择时间。它向我显示了在指定的时间已设置警报的祝酒词,但它没有起作用。下面是代码。
这是我的MainActivity。
Calendar currentTime = Calendar.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
int minute = currentTime.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hours = hourOfDay;
minutes = minute;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(getApplicationContext(), "Alarm has been set for "+hours+":"+minutes,Toast.LENGTH_LONG).show();
}
}, hour, minute, false);
timePickerDialog.setTitle("Select time");
timePickerDialog.show();
这是我的AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Uri alarmRingtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(alarmRingtone == null){
alarmRingtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context,alarmRingtone);
ringtone.play();
}
这是我的AndroidManifest文件
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver
android:name=".AlarmReceiver"
android:exported="true"
android:enabled="true"/>
答案 0 :(得分:1)
请尝试以下代码,它将对您有用
/**
* Method for start Alarm on Every minute
*
* @param minutes Minute when you want to start after current time
* @param context
*/
public static void startAlarm(Context context, int minutes) {
Logger.print("AlarmReceiver startAlarm called");
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
alarmIntent.setAction("testAPP");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 123451, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
long alarmPeriodicTime = System.currentTimeMillis() + (minutes*60*1000);
if (Build.VERSION.SDK_INT >= 23) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmPeriodicTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
manager.setExact(AlarmManager.RTC_WAKEUP, alarmPeriodicTime, pendingIntent);
} else {
manager.set(AlarmManager.RTC_WAKEUP, alarmPeriodicTime, pendingIntent);
}
}
在“我的接收器”中,我再次打来电话
startAlarm(context, Prefs.getLocationUpdateInterval(context));