Android alert clock final version [Android source code alert clock parsing]

Source: Internet
Author: User

I used to write a demo of a complex alarm. For more information, seeAndroid alarm clock [complex version] [Daming evolution 15th ].But there are some bugs in it, so many people leave a message, so I will look at the source code and find the reason? By the way, we sorted out the source code and made it into a complete running APK. This morning we sorted it out, and we found that the source code processing logic is more, with many considerations, for example, after the instance is started, it receives a broadcast, compares the time in the database with the current time, and sets an alarm. When the time zone changes, it also sends a broadcast to set the alarm.

Reprinted please indicate the source: http://blog.csdn.net/wdaming1986/article/details/7461043

Someone asked me, "When an alarm is set, and then the system time exceeds the set alarm time, then the alarm is triggered ??"

Through the source code, I found this situation is normal. Not a bug. Understandable.

The following are some of the important points I have found in the alarm:

(1) There is an audiomanager management mechanism in the alarm, which can apply for and release the onaudiofocuschangelistener listener.

There is also an mtelephonymanager object that handles switching of incoming call ringtones when an alarm is triggered.

(2) broadcast receiving alarm, enable the alarmklaxon service through broadcast, and implicitly start the service:

Public static final string alarm_intent_extra = "intent. Extra. Alarm ";

// Play the alarm alert and vibrate the device.        Intent playAlarm = new Intent(Alarms.ALARM_ALERT_ACTION);        playAlarm.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm);        context.startService(playAlarm);

In mainfest, The alarmklaxon service is defined as follows:

<service android:name="AlarmKlaxon"                android:description="@string/alarm_klaxon_service_desc"                >            <intent-filter>                <action android:name="com.cn.daming.deskclock.ALARM_ALERT" />            </intent-filter>        </service>

This service allows other activities to interrupt the ringing of the bell and play other ringtones. For example, when the alarm is triggered, a call is sent.

(3) The listview contains the checkbox. during the processing of the alarm, the activity implements an onitemclicklistener listener and clicks the listener for each item. Then, the checkbox will take it out and write a class separately, inherit linearlayout, and rewrite the setpressed () method to implement "do not trigger the parent click event when you click checkbox ". The key code is as follows:

 @Override    public void setPressed(boolean pressed) {        // If the parent is pressed, do not set to pressed.        if (pressed && ((View) getParent()).isPressed()) {            return;        }        super.setPressed(pressed);    }

 

Let's take a look at my program:

The red circle icon is my alarm. Click "Ling alarm" on the page

Click "create alarm" and set the time to display the toast.

Below I will post the code of my main entry class:

Deskclockmainactivity. Java

Package com.cn. daming. export clock; import Java. util. calendar; import android. app. activity; import android. app. alertdialog; import android. content. context; import android. content. dialoginterface; import android. content. intent; import android. content. sharedpreferences; import android. database. cursor; import android. graphics. typeface; import android. OS. bundle; import android. view. layoutinflater; import android. view. Menu; import android. view. menuitem; import android. view. view; import android. view. contextmenu; import android. view. contextmenu. contextmenuinfo; import android. view. view. onclicklistener; import android. view. viewgroup; import android. widget. adapterview; import android. widget. adapterview. adaptercontextmenuinfo; import android. widget. adapterview. onitemclicklistener; import android. widget. checkbox; import androi D. widget. cursoradapter; import android. widget. imagebutton; import android. widget. imageview; import android. widget. listview; import android. widget. textview; public class extends clockmainactivity extends activity implements onitemclicklistener {static final string preferences = "alarmclock";/*** this must be false for production. if true, turns on logging, test code, etc. */static final Boolean DEBUG = Fal Se; private sharedpreferences mprefs; private layoutinflater mfactory; private listview malarmslist; private cursor mcursor; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // It is taken from layoutinflater mfactory = layoutinflater. from (this); // obtain the value of key = "alarmclock" in getsharedpreferences mprefs = getsharedpreferences (preferences, 0); // obtain the cursor mcursor = Al of the alarm. Arms. getalarmscursor (getcontentresolver (); // update the layout interface updatelayout ();} // load the update interface layout private void updatelayout () {setcontentview (R. layout. alarm_clock); malarmslist = (listview) findviewbyid (R. id. alarms_list); alarmtimeadapter adapter = new alarmtimeadapter (this, mcursor); malarmslist. setadapter (adapter); malarmslist. setverticalscrollbarenabled (true); malarmslist. setonitemclicklistener (this); malarms List. setoncreatecontextmenulistener (this); view addalarm = findviewbyid (R. id. add_alarm); addalarm. setonclicklistener (new view. onclicklistener () {public void onclick (view v) {addnewalarm () ;}}); // make the entire View selected when focused. addalarm. setonfocuschangelistener (new view. onfocuschangelistener () {public void onfocuschange (view V, Boolean hasfocus) {v. setselected (hasfocus) ;}}); Im Agebutton export clock = (imagebutton) findviewbyid (R. id. __clock_button); Clock. setonclicklistener (new view. onclicklistener () {public void onclick (view v) {}});} private void addnewalarm () {startactivity (new intent (this, setalarm. class);}/*** the listview adapter inherits cursoradapter * @ author wangxianming * or you can use baseadapter */private class alarmtimeadapter extends cursoradapter {public alarmtime Adapter (context, cursor) {super (context, cursor);} public view newview (context, cursor, viewgroup parent) {view ret = mfactory. inflate (R. layout. alarm_time, parent, false); digitalclock = (digitalclock) ret. findviewbyid (R. id. digitalclock); digitalclock. setlive (false); return ret;} // bind the view to each public void BindView (view, context, cur) of the cursor Sor cursor) {final alarm = new alarm (cursor); view Indicator = view. findviewbyid (R. id. indicator); // set the initial resource for the bar image. final imageview baronoff = (imageview) indicator. findviewbyid (R. id. bar_onoff); baronoff. setimageresource (alarm. enabled? R. drawable. ic_indicator_on: R. drawable. ic_indicator_off); // set the initial state of the clock "checkbox" final checkbox clockonoff = (checkbox) indicator. findviewbyid (R. id. clock_onoff); clockonoff. setchecked (alarm. enabled); // clicking outside the "checkbox" shocould also change the state. // configure a listener for the checkbox so that the indicator is consistent inside and outside. setonclicklistener (New onclicklistener () {public void onclick (view v) {clo Ckonoff. toggle (); updateindicatorandalarm (clockonoff. ischecked (), baronoff, alarm) ;}}); digitalclock = (digitalclock) view. findviewbyid (R. id. digitalclock); // set the alarm text final calendar c = calendar. getinstance (); C. set (calendar. hour_of_day, alarm. hour); C. set (calendar. minute, alarm. minutes); digitalclock. updatetime (c); digitalclock. settypeface (typeface. default); // set the r Epeat text or leave it blank if it does not repeat. textview daysofweekview = (textview) digitalclock. findviewbyid (R. id. daysofweek); final string daysofweekstr = alarm. daysofweek. tostring (export clockmainactivity. this, false); If (daysofweekstr! = NULL & daysofweekstr. Length ()! = 0) {daysofweekview. settext (daysofweekstr); daysofweekview. setvisibility (view. visible);} else {daysofweekview. setvisibility (view. gone);} // display the label textview labelview = (textview) view. findviewbyid (R. id. label); If (alarm. label! = NULL & alarm. Label. Length ()! = 0) {labelview. settext (alarm. label); labelview. setvisibility (view. visible);} else {labelview. setvisibility (view. gone) ;}}; // update checkbox private void updateindicatorandalarm (Boolean enabled, imageview bar, alarm) {bar. setimageresource (Enabled? R. drawable. ic_indicator_on: R. drawable. ic_indicator_off); alarms. enablealarm (this, alarm. ID, enabled); If (Enabled) {setalarm. popalarmsettoast (this, alarm. hour, alarm. minutes, alarm. daysofweek) ;}}/** (non-javadoc) * @ see android. app. activity # oncontextitemselected (Android. view. menuitem) * Create context menu */@ override public Boolean oncontextitemselected (final menuitem item) {final adaptercontextmenu Info info = (adaptercontextmenuinfo) item. getmenuinfo (); Final int id = (INT) info. ID; // error check just in case. if (ID =-1) {return Super. oncontextitemselected (item);} switch (item. getitemid () {case R. id. delete_alarm: // confirm that the alarm will be deleted. new alertdialog. builder (this ). settitle (getstring (R. string. delete_alarm )). setmessage (getstring (R. string. delete_alarm_confirm )). Setpositivebutton (Android. r. string. OK, new dialoginterface. onclicklistener () {public void onclick (dialoginterface D, int W) {alarms. deletealarm (export clockmainactivity. this, ID );}}). setnegativebutton (Android. r. string. cancel, null ). show (); Return true; case R. id. enable_alarm: Final cursor c = (cursor) malarmslist. getadapter (). getitem (info. position); final alarm = new alarm (c); alarms. ena Blealarm (this, alarm. ID ,! Alarm. enabled); If (! Alarm. enabled) {setalarm. popalarmsettoast (this, alarm. hour, alarm. minutes, alarm. daysofweek);} return true; case R. id. edit_alarm: intent = new intent (this, setalarm. class); intent. putextra (alarms. alarm_id, ID); startactivity (intent); Return true; default: break;} return Super. oncontextitemselected (item);}/** (non-javadoc) * @ see android. app. activity # oncreatecontextmenu (Android. view. con Textmenu, android. view. view, android. view. contextmenu. contextmenuinfo) * Create menu */@ override public void oncreatecontextmenu (contextmenu menu, view, contextmenuinfo menuinfo) {// inflate the menu from XML. getmenuinflater (). inflate (R. menu. context_menu, menu); // use the current item to create a custom view for the header. final adaptercontextmenuinfo info = (adaptercontextmenuinfo) menuinfo; f Inal cursor c = (cursor) malarmslist. getadapter (). getitem (INT) info. position); final alarm = new alarm (c); // construct the calendar to compute the time. final calendar Cal = calendar. getinstance (); Cal. set (calendar. hour_of_day, alarm. hour); Cal. set (calendar. minute, alarm. minutes); final string time = alarms. formattime (this, Cal); // inflate the custom view and set each textview's text. fin Al view v = mfactory. inflate (R. layout. context_menu_header, null); textview = (textview) v. findviewbyid (R. id. header_time); textview. settext (time); textview = (textview) v. findviewbyid (R. id. header_label); textview. settext (alarm. label); // set the custom view on the menu. menu. setheaderview (V); // change the text based on the state of the alarm. if (alarm. enabled) {menu. finditem (R. id. enable _ Alarm ). settitle (R. string. disable_alarm) ;}}/ ** (non-javadoc) * @ see android. app. activity # onoptionsitemselected (Android. view. menuitem) * set the processing of click events in the menu */@ override public Boolean onoptionsitemselected (menuitem item) {Switch (item. getitemid () {case R. id. menu_item_settings: startactivity (new intent (this, settingsactivity. class); Return true; case R. id. menu_item_desk_clock: // modify by wangxian Ming in 2012-4-14 // startactivity (new intent (this, Clock. class); Return true; case R. id. menu_item_add_alarm: addnewalarm (); Return true; default: break;} return Super. onoptionsitemselected (item);}/** (non-javadoc) * @ see android. app. activity # oncreateoptionsmenu (Android. view. menu) * Create menu */@ override public Boolean oncreateoptionsmenu (menu) {getmenuinflater (). inflate (R. menu. alarm_lis T_menu, menu); return Super. oncreateoptionsmenu (menu);}/** (non-javadoc) * @ see android. widget. adapterview. onitemclicklistener # onitemclick (Android. widget. adapterview, android. view. view, Int, long) * Create a menu Click Event Response */Public void onitemclick (adapterview <?> Adapterview, view V, int POs, long ID) {intent = new intent (this, setalarm. class); intent. putextra (alarms. alarm_id, (INT) ID); startactivity (intent) ;}@ override protected void ondestroy () {super. ondestroy (); toastmaster. canceltoast (); mcursor. close ();}}

 

[Note] If you want the source code, you can leave a mailbox. I will send it to you after seeing it!

You can also go to my csdn resources to download: http://download.csdn.net/detail/wdaming1986/4226174

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.