开发者

Starting alarm service in android

In my applica开发者_Go百科tion i want to use alarm service for specific period of time.I'm taking start time and end time values from user and saving it in database,Now i want to start a alarm service at start time and alarm should go off at end time specified by user.I'm new to this topic and not able to understand how to implement this...Any help will be appreciated.Thank u..


This is how you implement an alarm manager. But you will need to read about Calendar object in android also.

 String alarm = Context.ALARM_SERVICE;
 Calendar calendar = Calendar.getInstance();

 calendar.set(Calendar.HOUR_OF_DAY, 8);//Just an example setting the alarm for the 8th hour of a day.
  calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);



AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
//This is the intent that is launched when the alarm goes off.
                    Intent intent = new Intent("WAKE_UP");

PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);



//If the user wants the alarm to repeat then use AlarmManager.setRepeating if they just want it one time use AlarmManager.set().

    am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);




                    }

Also you will need to register a BroadCast Receiver to except the intent when the alarm sets it off. You create the BroadCast reciever and register it in your manifest to receive the intent from the alarm. http://www.vogella.de/articles/AndroidServices/article.html

Here is a great tutorial to help you understand better


The key is to use the AlarmManager with a pending intent.

mAlarmSender = PendingIntent.getService(AlarmService.this, 
0, new Intent(AlarmService.this, AlarmService_Service.class), 0);

Then you create the AlarmManager from the current context:

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

And schedule the previously created pending intent.

am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        firstTime, 30*1000, mAlarmSender);

On schedule the AlarmService_Service service will be called, or you can put another intent like open a specific activity.

Here is the complete example of how you can schedule an alarm: AlarmService.java

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜