Android Learning note Alarmmanager for timer and alarm clock implementation

Source: Internet
Author: User

Graduation design has a function module called a doctor to remind, probably the function is the user to set a future time alarm clock, and set the alarm clock label, the label says to where to seek medical information, the main design reference Meizu system comes with alarm function. I read a lot of blogs on the internet, but also on GitHub downloaded a lot of source code, found that there is no particularly good, there is always this or that kind of problem, such as the alarm clock is not written in the background service mode, the app is closed after the alarm clock will not be alerted, or the phone after the shutdown alarm clock information is lost, So I'm going to write myself a more complete function.

So the function of the alarm clock needs to use the Android database SQLite, Service, broadcastreceiver three more important modules, before looking at the "first line of code", because of the more hurried to see, so the part of the book Behind the Knowledge Point learning is not solid, The code in the book did not personally knock in the IDE, so I took a good look at the first line of code for the database SQLite, Service, and Broadcastreceiver sections on the 51 holiday three days.

SQLite is a lightweight Android built-in database that typically accounts for only hundreds of KB of memory, so it's also very useful on mobile devices. The table for creating the database is as follows, and a helper class is written to encapsulate the database operations, simplifying the operation of the underlying operational data.

1  Public classAlarmdbhelperextendssqliteopenhelper{2      Public Static FinalString database_name = "Userinfo.db";3      Public Static Final intDatabase_version = 2;4      Public Static FinalString TABLE = "Alarm";5 6 7     Private Static FinalString create_alarm_table = "CREATE table" + Table + "("8+ alarmcolumn._id + "Integer primary key AutoIncrement,"9+ alarmcolumn.alarm_id + "text UNIQUE on CONFLICT REPLACE,"Ten+ Alarmcolumn.alarm_calendar + "text," One+ alarmcolumn.alarm_cancelable + "text," A+ Alarmcolumn.alarm_tag + "text," -+ alarmcolumn.alarm_available + "text," -+ Alarmcolumn.alarm_ringtone + "text"); the  -      PublicAlarmdbhelper (Context context) { -         Super(Context, database_name,NULL, database_version); -     } +  - @Override +      Public voidonCreate (Sqlitedatabase db) { A Db.execsql (create_alarm_table); at     } -  - @Override -      Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { -String sql= "DROP TABLE IF EXISTS" +TABLE; - db.execsql (SQL); in onCreate (db); -     } to}

To modify the original database, just take the dbhelper = new Alarmdbhelper (This, "userinfo.db", NULL, 3); You can add version numbers to the The operation of the database is nothing more than the Crud,c representative add (Create), R for the query (Retrieve), U for Update (updated), and D for delete. The operation is essentially the same as SQL, while the official support for using SQL statements to build databases and crud. Which queries the database design to a new data type--cursor, intended to be the cursor, can be understood as the contents of each row in the database. Cursor.movetofirst () moves to the first row in the table, and Cursor.movetonext () moves to the next line. The code above creates an alarm table and saves some of the information needed to create the alarm in the database.

1  Public classBootreceiverextendsbroadcastreceiver{2 @Override3      Public voidOnReceive (Context context, Intent Intent) {4arraylist<alarm> alarms =getallalarms (context);5          for(Alarm alarm:alarms) {6             //Test7             //when restarted, all should be restored, and if this is a timed task, then just restore the monthly and yearly.8             //If the alarm clock is rebuilt 00:00 every day, will the alarm clock ring at 00:00?9             //so finally stagger a bit, because the alarm clock does not have the number of seconds, so set to 00:00:30 seconds. Ten             //no matter what the alarm clock, will be guaranteed if the next day alarm clock will be set up, so do not worry about the 00:00 alarm clock will not be set on One alarm.activate (); A         } -     } -  the     /** - * Recover all alarms from the local database -      * -      * @return +      */ -     PrivateArraylist<alarm>getallalarms (Context context) { +Alarmhelper helper =NewAlarmhelper (context); A         returnhelper.getalarms (); at     } -}

and register a broadcast monitoring boot action, each time the power-on will all alarm from the database, and activate all the alarm clock, that is, alarmreceive monitor all alarms.

1  Private voidSetonetimealarm () {2         if(Audreycalendar.gettimeinmillis ()-System.currenttimemillis () > 0) {3             //The last parameter must be pendingintent.flag_update_current, otherwise broadcastreceiver will not receive the parameter. 4Pendingintent pendingintent =pendingintent.getbroadcast (Mcontext,50, intent, pendingintent.flag_update_current);6Alarmmanager Manager =(Alarmmanager) Mcontext7 . Getsystemservice (context.alarm_service);8 Manager.set (Alarmmanager.rtc_wakeup,9 Audreycalendar.gettimeinmillis (), pendingintent);Ten}Else { OneToast.maketext (Mcontext, "lad, set too early for the alarm is not going to execute the drip! ", A toast.length_short). Show (); -         } -}

By doing so, the alarm in the database sets the time of the ring in Setonetimealarm (). The code in Alarmreceive is as follows,

1  Public classAlarmreceiverextendsbroadcastreceiver{2 3 @Override4      Public voidOnReceive (Context context, Intent Intent) {5 6Alarm alarm=NewAlarm (context, Intent.getextras ());7Intent intent2=NewIntent ();8 intent2.addflags (intent.flag_activity_new_task);9Intent2.setclass (context, ringactivity.class);Ten Intent2.putextras (Alarm.alarm2bundle (Alarm)); One context.startactivity (intent2); A  -  -  the     } -}

The logic of the entire alarm is completed by starting the Ringactivity with the method in receive and triggering the ringing action.

Supposedly, the implementation of the alarm clock should be implemented through the service, so that even when the app is turned off, the alarm in the background is running, but how to start an alarm in the service I don't know how to do it. The whole logic should be when you set the alarm's properties, click Add Alarm, Alarm information is saved in the database, while triggering a service launch, in the service services to accept the information in alarm, set the latter

Pendingintent pendingintent = pendingintent.getbroadcast (mcontext, 5                     0, Intent, Pendingintent.flag_ Update_current); 6             Alarmmanager manager =                                  audreycalendar.gettimeinmillis (), pendingintent); Change the getbroadcast to Getactivity and jump to ringactivity to achieve the entire logic.


Because my code borrowed from someone else's code, causing me to fall into a lot of confusion in the code reading, while the whole logic is very unclear, causing the code to work very slowly the fact that I have to read the code of others on the basis of understanding the entire logic implementation, clear the idea, to complete their own design.

Android Learning note Alarmmanager for timer and alarm clock implementation

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.