gpt4 book ai didi

android - 使用 Alarmmanager 在特定时间启动服务

转载 作者:IT老高 更新时间:2023-10-28 22:05:55 24 4
gpt4 key购买 nike

我已经搜索了很多地方,但找不到关于如何在每天的特定时间使用 AlarmManager 启动服务(或者如果那不可能,那么是 Activity )的清晰顺序解释??

我想注册几个这样的警报并触发它们应该会导致服务启动。我将在服务中有一小段代码,然后可以执行,我可以永久完成服务....

Calendar cal = Calendar.getInstance();
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Date date = new Date(cur_cal.get(Calendar.YEAR), cur_cal.get(Calendar.MONTH), cur_cal.get(Calendar.DATE), 16, 45);
cal.setTime(date);
Intent intent = new Intent(ProfileList.this, ActivateOnTime.class);
intent.putExtra("profile_id", 2);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
System.out.println("The alarm set!!");

我尝试使用此代码在 4.45 激活警报...但它没有触发服务...我必须保持进程运行吗?我做错什么了吗???

还有一件事,如果我使用以下代码,我的服务将得到完美执行:

long firstTime = SystemClock.elapsedRealtime();
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000,pintent);

最佳答案

各位 friend ,经过大量研究并引用“Pentium10”关于同一主题的问题后,我设法让它工作。虽然我仍然无法理解为什么我在问题中提到的“日期”概念和 Calendar(non GregorianCalendar) 对象无法正常工作。

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this, IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);

关于android - 使用 Alarmmanager 在特定时间启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3052149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com