我已经在启动完成时在 android 中启动了上午 9:00 的警报。但在完成启动后每分钟触发一次警报。
我的要求是它应该在启动后设置警报,但只在上午 9:00 触发警报。
这是我的代码: 公共(public)类 AlarmUtil { private PendingIntent alarmIntent;
public static void setAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
calendar.set(Calendar.AM_PM, Calendar.AM);
//calendar.setTimeInMillis(calendar.getTimeInMillis());
calendar.add(Calendar.SECOND, 1);
Intent intent = new Intent(context, Services.class);
PendingIntent pintent = PendingIntent.getService(context, 123456789,
intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, pintent);
}
}
public class AlarmBroadcastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Toast.makeText(context, "Booted!", Toast.LENGTH_SHORT).show();
AlarmUtil.setAlarm(context);
}
}
}
服务(我的服务类)
public class Services extends IntentService {
public Services(String name) {
super("services");
// TODO Auto-generated constructor stub
}
public Services() {
super("services");
// TODO Auto-generated constructor stub
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MyApp.counter += 1;
Toast.makeText(getApplicationContext(),
"Service started: " + MyApp.counter, Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "handling intent",
Toast.LENGTH_LONG).show();
}
我欠缺的地方。请帮我。提前致谢。
最佳答案
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, pintent);
通过调用 setRepeating()
,您可以指示它每分钟触发一次 intent。您可能打算使用 set()
或 setExact()
代替。
此外,您将闹钟设置为 当前日期 9:00。我不确定您的目标是什么,但如果您想要“下一个 9:00”的闹钟(即作为闹钟),如果当前时间大于 9:00,您可能应该添加一天。来自文档:
If the stated trigger time is in the past, the alarm will be triggered immediately.
编辑:如果您需要每天 9:00 触发此警报,则 setRepeating()
是正确的,但是以毫秒为单位的时间应该是 AlarmManager.INTERVAL_DAY
。不过,请注意有关过去警报的注释。如果您在上午 10:00 启动您的手机,并使用您当前的代码,除了 future 的警报之外,您将立即收到警报。
而且,正如@DerGolem 指出的那样,如果您的目标是 API 级别 19,那么这些警报将不准确(并且没有 setRepeatingExact()
)。如果您需要精确 警报,则必须使用 setExact()
安排一个,然后在下一个触发时安排下一个,依此类推。
关于android - 在每天的特定时间设置开机时间警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24300686/