The previous article on the recent small alarm clock did a functional elaboration, and now to summarize the whole development process used in some of the knowledge points:
1.TimePicker of monitoring
The Timepicker control is the core of the entire application, and all other operations are based on the correct manipulation of the control. The key to the control's operation is to set the listener for it, and to get the user set time in the Listener event.
PrivateCalendar calendar=calendar.getinstance ();//Create a Calendar objectPrivate classOntimechangedlistenerimplImplementsOntimechangedlistener {@Override Public voidOntimechanged (Timepicker view,intHour_of_day,intminutes) { //TODO auto-generated Method StubCalendar.settimeinmillis (System.currenttimemillis ());//converts the current time of Timepciker to a calender objectCalendar.set (Calendar.hour_of_day,hour_of_day);//Set HoursCalendar.set (calendar.minute,minutes);//Set minutesCalendar.set (calendar.second,0);//Set secondsCalendar.set (calendar.millisecond,0);//set millisecondsHour=hour_of_day;//Save settings for hoursMinute=minutes;//minutes to save settings } }
The Calendar class is used in the design to represent a specific time (that is, the user-set alarm time). The Calendar class is an abstract class whose constructor permission is protected, so the object cannot be created by constructing the method, so it can only be created by calling getinstance (). The conversion between the date and calendar classes is implemented through the settime () and GetTime () two methods.
Use of 2.PendingIntent
In this design, the Pendingintent realizes the alarm function by timing sending the broadcast:
Intent intent=New Intent (mainactivity. this, myalarmreceiver. class); // Specify the Inetent of the jump Intent.setaction ("Com.example.action.setalarm"); // Specify action for intent Pendingintent sender=pendingintent.getbroadcast (mainactivity. this, 0,intent,pendingintent.flag_update_current); // Specifies pendingintentalarm.set (alarmmanager.rtc_wakeup,mainactivity. this. Calendar.gettimeinmillis (), sender); // Set Alarm
pendingintent literal meaning: undecided, pending intent. This is the first contact to Pendingintent, also saw a lot of information on the Internet, but all feel confused, and later saw a definition of the official website, it dawned on: an Intent is something that was used right now; Pendingintent is something a Intent in the future. You'll use a pendingintent with notifications, Alarmmanager, etc. The key is the in the future, combined with this example, that is, when the alarm clock time, Pendingintent carry broadcast will be broadcast out.
3. Querying the list of audio files using the cursor database
The user can select an audio file on the device's SD card as the ringtone for the alarm, which is achieved through the cursor in this design:
//get audio files on an SD card Public voidScannermusic () {//querying the Media databaseCursor cursor=mainactivity. This. Getcontentresolver (). Query (MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,NULL,NULL,NULL, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); //traversing the database if(Cursor.movetofirst ()) { while(!Cursor.isafterlast ()) { intId=cursor.getint (Cursor.getcolumnindexorthrow (mediastore.audio.media._id));//Get Song number intTrackid=cursor.getint (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.ALBUM_ID));//Get song IDString album=cursor.getstring (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.ALBUM));//get song album nameString artist=cursor.getstring (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.ARTIST));//get the song singer nameString url=cursor.getstring (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.DATA));//Get Song PathString duration=cursor.getstring (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.DURATION));//get the song playback duration intSize=cursor.getint (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.SIZE));//Get song sizeString disname=cursor.getstring (Cursor.getcolumnindexorthrow (MediaStore.Audio.Media.DISPLAY_NAME));//get the song file display nameItems.Add (disname); Urls.add (URL);//Save Song PathCursor.movetonext (); } cursor.close (); } fileList=NewArrayadapter<string> ( This, R.layout.list_item,items); }
The Android device automatically classifies the files when the SD card is loaded, where the audio files are stored in the Mediastore database, which can be called by Contentresolver to invoke the encapsulated interfaces, and then call Qurey () method to obtain a list of audio files and related information, the query () method prototype is:
Query (_uri, Prjs, selections, Selectargs, order);
The first parameter of the method is: the name of the database to be queried plus the name of the table. The second parameter is the column selected from the table. The third parameter is a query condition. The fifth parameter is a sort condition.
After getting all the audio files, save the name of the audio file and the corresponding path to the dynamic array, which facilitates late invocation.
4.SharePreference Complete Data storage
When the user selects an audio file in this design, it needs to be played in another activity, so sharepreference is used to store the path of the user's chosen audio.
Sharedpreferences sp=getsharedpreferences ("Mrsoft", mode_private); // get a private type of sharedpreferences Editor Editor=sp.edit (); // //Editor objects are stored in key-value form
Editor.putstring ("Musicurl", Urls.get (item)); // Add music address editor.commit (); // Confirm Submission
Sharepreferences is a lightweight storage solution within the application and is most often used to store configuration parameters for the application. The use of sharepreference to save data, is essentially the use of XML files for storage, the path of storage is:/data/data/<package name>/shared_prefs. Sharepreference is handy: using Getsharepreferences () to get the Sharepreferences object, the object obtained by the method can be accessed by other components under the application. The method has two parameters, the first parameter sets the name of the shared file, and the second parameter sets the type of the shared file. Then the editor object is obtained through the edit () method, and the Putstring () method of the Editor object is used to increase the value to be saved, and finally the commit () method is called. Accordingly, you can call the GetString () method when you need to read the saved data.
5.Adapter, Alertdialog, ListView combined use
Adapter is actually the bridge between the data and the view, and the data is sent to the view after the adapter is processed accordingly. This design uses a string-type array adapter:
Arrayadapter<string> fileList
filelist=New arrayadapter<string> (this, r.layout.list_item,items);
Arrayadapter<string> There are three parameters, the first parameter is the context, that is, the current activtiy, the second parameter is a custom layout, white is a textview, each piece of data is presented in the form of this layout file , the third parameter is the data to be displayed. This design will read the list of audio files displayed on a alertdialog, so you also need to set the connection between adapter and Alertdialog:
Builder.setadapter (fileList, new Dialoginterface.onclicklistener () { @Override Public void int Item) { } });
FileList is the data adapter, the second parameter is the Click event Listener for the ListView list, and when the user clicks on the contents of the ListView list, the appropriate action is taken.
6.Recording for recording
Users can record their favorite audio as an alarm ringtone through this app. The recording operation is similar to the audio file playback and is relatively simple to implement:
Private voidstartrecording () {//Get Mediarecorder ObjectMrecorder=NewMediarecorder (); //set the audio source to MicphoneMrecorder.setaudiosource (MediaRecorder.AudioSource.MIC); //set the encapsulation formatMrecorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP); //set audio file output pathMrecorder.setoutputfile (mfilename); //set the encoding formatMrecorder.setaudioencoder (MediaRecorder.AudioEncoder.AMR_NB); Try{mrecorder.prepare (); Mrecorder.start (); } Catch(IOException e) {e.printstacktrace (); } } Private voidstoprecording () { Try{mrecorder.stop (); } Catch(IllegalStateException e) {e.printstacktrace (); } mrecorder.release ();//Freeing ResourcesMrecorder=NULL;//empty The Mediarecorder object, this step can not be less }
The recording process is similar to using MediaPlayer to play the audio process, it is worth noting that the recording must call Mrecorder.release () to release the resources, and empty the Mrecorder object, otherwise the user will be recording again when the hardware resource conflict exception , causing the application to shut down gracefully.
7.BroadcastReceiver
This design uses Broadcastreceiver to start the "Alarm Time to" interface:
Public classMyalarmreceiverextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {//TODO auto-generated Method Stub if(Intent.getaction (). Equals ("Com.example.action.setalarm") {Intent it=NewIntent (context,alarmmessage.class);//customizing the activity to jumpIt.addflags (Intent.flag_activity_new_task);//Pass a new task tokenContext.startactivity (IT);//Start Intent } }}
Broadcast receivers (BROADCASTRECEIVER) are used to receive broadcast intent, usually a broadcast intent can be received by multiple Broadcastreceiver subscribed to the broadcast. Broadcast is a mechanism for message transmission between applications, and Broadcastreceiver is a type of component that filters and responds to transmitted broadcasts, and Broadcastreceiver does not implement a graphical interface itself. Each time the broadcast arrives, it re-creates the Broadcastreceiver object and calls its OnReceive method, where it is not possible to do some relatively time-consuming operations, because the Broadcastreceiver life cycle is only about 10 seconds. There is a lot more to be learned about broadcasting, which is not covered here.
7.Vibrator
In this design, when the alarm clock sounded, the user equipment is accompanied by a vibration phenomenon. In Android, vibration is achieved by invoking the vibrator class.
Vibrator= (Vibrator) Getsystemservice (Context.vibrator_service); // Get vibration Service long pattern[]={100,400,100,400}; // Stop turn on // control the number of milliseconds the phone vibrates, where the second parameter specifies the index of the first array parameter, 1 means only one shake, Non-1 means repeating vibration vibrator.vibrate (pattern,2) starting from the specified subscript (second parameter) ;
First get the vibration service of the device, then define an array to hold the vibration time, in the vibrator, the vibration time is calculated in milliseconds (1/1000 seconds), so it can control the starting and stopping of the vibration by the size of the value. Finally, the vibrate method is called to implement the vibration function, the second parameter is 1, which means that the vibration is repeated only once, and non-1 is a repeat vibration.
8.ExitApplication
This design involves two activity, so when the user wants to close the application, it is necessary to close all activity at once, and if the finish () method is called at the current interface, only the activity of the active period can be exited. Therefore, the following methods are used to accomplish this function:
Public classExitapplicationextendsapplication{PrivateList<activity> activitylist=NewLinkedlist<activity>(); Private StaticExitapplication instance; Privateexitapplication () {}//in singleton mode, get a unique exitapplication instance Public Staticexitapplication getinstance () {if(NULL==instance) {Instance=Newexitapplication (); } returninstance; } //add activity to container Public voidaddactivity (activity activity) {Activitylist.add (activity); } //traverse all activity and finish Public voidexit () { for(Activity activity:activitylist) {activity.finish (); } system.exit (0); }}
The Exitapplication.getinstance (). Addactivity (This) method is then called in each of the OnCreate () methods in the activity. This allows you to invoke the Exitapplication.getinstance (). Exit () method when any activity exits, completely exiting the application.