Using Alarm Manager to Start a Service
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 Notifica开发者_运维知识库tion 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...
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...
Your code will only work if you execute it before 3am. Otherwise, you will be setting an alarm in the past.
精彩评论