使用警报管理器启动服务
我有一些代码想在每天凌晨 3:00 执行。我已经阅读了服务类文档,看来我可以使用AlarmManager 触发一个意图(我认为是活动还是服务?),然后在该意图中创建消息并在 Android 通知区域中发布消息。
Calendar threeAM = Calendar.getInstance();
threeAM.set(Calendar.HOUR_OF_DAY,2);
threeAM.set(Calendar.MINUTE,0);
threeAM.set(Calendar.SECOND,0);
threeAM.set(Calendar.MILLISECOND,0);
AlarmManager alarmManager =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, myNotifier.class);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, threeAM.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, PendingIntent.getService(context, 1, i , 0));
Log.i("Service TEST", "Alarm set?" );
它运行代码没有任何问题,但没有迹象表明警报已设置,并且活动未启动。我正在使用一项我知道有效的活动。我尝试将其包装在 try/catch 中,但 logcat 中没有任何内容...
I have some code I want to execute at 3:00am every day. I've read the Service Class Documentation and it seems I can use AlarmManager to fire an intent(Activity or Service, I think?), and then, in that intent create and post a message in the Android Notification area.
Calendar threeAM = Calendar.getInstance();
threeAM.set(Calendar.HOUR_OF_DAY,2);
threeAM.set(Calendar.MINUTE,0);
threeAM.set(Calendar.SECOND,0);
threeAM.set(Calendar.MILLISECOND,0);
AlarmManager alarmManager =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, myNotifier.class);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, threeAM.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, PendingIntent.getService(context, 1, i , 0));
Log.i("Service TEST", "Alarm set?" );
It runs through the code with no problems, but there is no indication that the alarm is set, and the activity doesn't start. I'm using an activity that I know works. I tried wrapping it in a try/catch, nothing in logcat...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您应该注册您的活动以接收启动广播接收器,以便您的应用程序在操作系统启动完成时启动。这是链接 http://www.androidenea。 com/2009/09/starting-android-service-after-boot.html
它在通知方面没有帮助,但它会解决您的活动未启动的问题...
I think you should register your activity to receive boot broadcast receivers so that your application starts on the moment the OS boot up complete. here is the link http://www.androidenea.com/2009/09/starting-android-service-after-boot.html
It will not help in terms of notification but yes it will solve your problem of activity not starting...
仅当您在凌晨 3 点之前执行您的代码时,它才会起作用。否则,你就会设置过去的闹钟。
Your code will only work if you execute it before 3am. Otherwise, you will be setting an alarm in the past.