Timer implementation in Android background

Source: Internet
Author: User
Tags getmessage

Android Background running timer, convenient for us to run location tracking and other task requirements. The following is a brief description of the essentials of implementing the Android background timer, which can be downloaded to project code at the end of the article and run directly.


Androidmanifest.xml file contents such as the following:


<?

XML version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.routing.videocamera" android:versioncode= "1" android:versionname= "1.0" > <uses-permission Android Oid:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/> <uses-permission android:name= " Android.permission.INTERNET "/> <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/ > <uses-sdk android:minsdkversion= "android:targetsdkversion="/> <application Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style/apptheme" > <activity android:name= "Com.routing.videocamera.Video" Android:label= "@string/app_name" > <intent-filter> <action android:name= "Android . Intent.action.MAIN "/> <category android:nAme= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service Android:enabled= "true" android:name= ". Timerservice "/> <receiver android:name=". Autoreceiver "android:label=" @string/app_name "> <intent-filter> <action android:name=" Android.intent.action.BOOT_COMPLETED "/> <category android:name=" Android.intent.category.LAUNCHER "/>< /intent-filter></receiver> </application> </manifest>


The key code is to give the project receive_boot_completed permissions:

<uses-permission android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/>

The contents of the Video.java file are as follows:

Package Com.routing.videocamera;public class Video extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_video); Intent intent=  New Intent (This,autoreceiver.class); Intent.setaction ("Video_timer");  Pendingintent sender = Pendingintent.getbroadcast (this, 0, intent, 0);   Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service); Am.setrepeating (Alarmmanager.elapsed_realtime_wakeup, Systemclock.elapsedrealtime (), 10*1000, sender); Button btnstart = (button) Findviewbyid (R.id.buttonsave); Btnstart.setonclicklistener (Clicklistener);       Context CTX = video.this; Sharedpreferences sp = ctx.getsharedpreferences ("VIDEO", mode_private);//Deposit Data Editor editor = Sp.edit (); String serveraddr = sp.getstring ("Serveraddr", "NULL"); String cameraname = sp.getstring ("Cameraname", "NULL"), int cameraid = Sp.getint ("Cameraid", 0); int cameraport = Sp.getin        T ("Cameraport", 0); EditText editserveraddr = (EdiTtext) Findviewbyid (R.ID.EDITSERVERADDR);        Editserveraddr.settext (SERVERADDR);          EditText editcameraname = (EditText) Findviewbyid (r.id.editcameraname);                Editcameraname.settext (Cameraname);          EditText Editcameraid = (EditText) Findviewbyid (R.id.editcameraid);                        Editcameraid.settext (integer.tostring (Cameraid));          EditText Editcameraport = (EditText) Findviewbyid (R.id.editcameraport); Editcameraport.settext (integer.tostring (Cameraport));}          private void SaveSetting () {EditText editserveraddr = (EditText) Findviewbyid (R.ID.EDITSERVERADDR);        String serveraddr = Editserveraddr.gettext (). toString ();          EditText editcameraname = (EditText) Findviewbyid (r.id.editcameraname);                String cameraname = Editcameraname.gettext (). toString ();          EditText Editcameraid = (EditText) Findviewbyid (R.id.editcameraid);                  int cameraid = Integer.parseint (Editcameraid.gettext (). toString ());      EditText Editcameraport = (EditText) Findviewbyid (R.id.editcameraport);        int cameraport = Integer.parseint (Editcameraport.gettext (). toString ());       Gets the Sharedpreferences object context ctx = Video.this; Sharedpreferences sp = ctx.getsharedpreferences ("VIDEO", mode_private);//Deposit Data Editor editor = Sp.edit (); if (serveraddr!) = "") editor.putstring ("Serveraddr", serveraddr), if (cameraname! = "") editor.putstring ("Cameraname", cameraname);        Editor.putint ("Cameraid", Cameraid); Editor.putint ("Cameraport", Cameraport); Editor.commit (); } @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action Bar if it is P Resent.getmenuinflater (). Inflate (R.menu.activity_video, menu); return true;} Private Onclicklistener Clicklistener = new Onclicklistener () {@Overridepublic void OnClick (View v) {int ret = 0;switch (v. GetId ()) {case r.id.buttonsave:savesetting (); break;}}};}

The key code for the file is the following 4 lines of code in the OnCreate function:

Intent.setaction ("Video_timer"); Pendingintent sender = Pendingintent.getbroadcast (this, 0, intent, 0);  Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);   
Intent.setaction ("Video_timer") sets the type of message that the system sends to the application as Video_timer.

Am.setrepeating (Alarmmanager.elapsed_realtime_wakeup, Systemclock.elapsedrealtime (), 10*1000, sender); This line of code gives the system how often to send a message, which I set here is 10 seconds to send a video_timer message.

Messages sent out will be received and processed in class Autoreceiver extends Broadcastreceiver classes.




The following is the Timerservice.java file:

Package Com.routing.videocamera;public class Timerservice extends service{public void OnCreate () {SUPER.ONCR          Eate ();    LOG.V ("Timerservice", "OnCreate");    } private static String Murl;                           public void OnStart (Intent Intent, int startid) {log.v ("Timerservice", "OnStart");  Context CTX = timerservice.this;       Context CTX = context; Sharedpreferences sp = ctx.getsharedpreferences ("VIDEO", mode_private);//Deposit Data String serveraddr = Sp.getstring (" Serveraddr "," "); String cameraname = sp.getstring ("Cameraname", "" "), int cameraid = Sp.getint (" Cameraid ", 0); int cameraport = Sp.getint (" C        Ameraport ", 0); if (serveraddr = = "" | | Cameraname = = "" | | Cameraid = = 0 | | Cameraport = = 0 | | Serveraddr = = "NULL" | |        Cameraname = = "NULL") return; String URL = serveraddr + "/cameramgr.php?"

"+" cameraname= "+ cameraname +" &cameraid= "+ Cameraid +" &cameraport= "+ cameraport; LOG.V ("FFMPEG url=", URL); Murl = URL; New Thread () {@Override public void run () {Httpparams httpparams; Create Httpparams to set the HTTP parameters (this part is not necessary) Httpparams = new Basichttpparams (); Set connection timeout and socket timeout, and socket cache size Httpconnectionparams.setconnectiontimeout (httpparams, 20 * 100 0); Httpconnectionparams.setsotimeout (Httpparams, 20 * 1000); Httpconnectionparams.setsocketbuffersize (Httpparams, 8192); Sets the redirect, which defaults to True Httpclientparams.setredirecting (Httpparams, true); Set the user agent String useragent = "mozilla/5.0 (Windows; U Windows NT 5.1; ZH-CN; rv:1.9.2) gecko/20100115 firefox/3.6 "; Httpprotocolparams.Setuseragent (Httpparams, useragent); Create a HttpClient instance//Note HttpClient HttpClient = new HttpClient (); is Commons HttpClient//In the use of, in Android 1.5 we need to use the Apache default implementation defaulthttpclient HTTPC Lient httpClient = new Defaulthttpclient (httpparams); String s = this.getname (); HttpGet HttpRequest = new HttpGet (Murl); String strresult = "Dogeterror"; try {HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = 200) { strresult = entityutils.tostring (Httpresponse.getentity ()); } else {strresult = "Error Response:" + httpresponse.g Etstatusline (). ToString (); }} catch (Clientprotocolexception e) {strresult = E.getmessage (). toString (); E.printstacktrace (); } catch (IOException e) {strresult = E.getmessage (). toString (); E.printstacktrace (); } catch (Exception e) {strresult = E.getmessage (). toString (); E.printstacktrace (); } log.v ("Strresult", strresult); }}.start (); public string doPost (string url, list<namevaluepair> params) {/* Build HttpPost Object */ HttpPost HttpRequest = new HttpPost (URL); String strresult = "Doposterror"; try {/* joins the request to the Request object */httprequest.setentity (New Urlencodedformentity (params, HTTP. Utf_8)); /* Send request and wait for response */Httpparams httpparams; Create Httpparams to set the HTTP parameters (this part is not necessary) Httpparams = new Basichttpparams (); Set the connection timeout and the Socket timeout. And the Socket cache size Httpconnectionparams.setconnectiontimeout (httpparams, 20 * 1000); Httpconnectionparams.setsotimeout (Httpparams, 20 * 1000); Httpconnectionparams.setsocketbuffersize (Httpparams, 8192); Sets the redirect, which defaults to True Httpclientparams.setredirecting (Httpparams, true); Set the user agent String useragent = "mozilla/5.0 (Windows; U Windows NT 5.1; ZH-CN; rv:1.9.2) gecko/20100115 firefox/3.6 "; Httpprotocolparams.setuseragent (Httpparams, useragent); HttpClient HttpClient = new Defaulthttpclient (httpparams); HttpResponse HttpResponse = Httpclient.execute (HttpRequest); /* If the status code is */if (Httpresponse.getstatusline ()). Getstatuscode () = = 200) {/* Read return data */strresult = entityutils.tostring (Httpresponse.getentity ()); } else {strresult = "Error Response:" + httpresponse.getstatusline (). ToS Tring (); }} catch (Clientprotocolexception e) {strresult = E.getmessage (). toString (); E.printstacktrace (); } catch (IOException e) {strresult = E.getmessage (). toString (); E.printstacktrace (); } catch (Exception e) {strresult = E.getmessage (). toString (); E.printstacktrace (); } log.v ("Strresult", strresult); return strresult; } public void OnDestroy () {Super.ondestroy (); LOG.V ("Timerservice", "OnDestroy"); } public IBinder Onbind (Intent Intent) {return null; } public static String InstreAm2string (InputStream inputstream) {InputStreamReader inputstreamreader = null; try {inputstreamreader = new InputStreamReader (InputStream, "UTF8"); } catch (Unsupportedencodingexception E1) {e1.printstacktrace (); } BufferedReader reader = new BufferedReader (InputStreamReader); StringBuffer sb = new StringBuffer (""); String Line; try {while (line = Reader.readline ())! = null) {sb.append (line); Sb.append ("\ n"); }} catch (IOException e) {e.printstacktrace (); } return sb.tostring (); } }


This file is the code of the timer run, nothing special.


The following is the Autoreceiver.java file:

Package Com.routing.videocamera; public class Autoreceiver extends broadcastreceiver{/* The intent Source to receive *///static final String ACTION = "android.intent. Action.    boot_completed ";p rivate static final int mode_private = 0; @Override public void OnReceive (context context, Intent Intent) {if (Intent.getaction (). Equals ("Video_timer  ") {Intent intentservice = new Intent (context, timerservice.class);        ACTIVITY intentservice.addflags to start (Intent.flag_activity_new_task);                Context.startservice (Intentservice); }} public static String instream2string (InputStream inputstream) {InputStreamReader Inputstreamre          Ader = null;          try {inputstreamreader = new InputStreamReader (InputStream, "UTF8");          } catch (Unsupportedencodingexception E1) {e1.printstacktrace ();          } BufferedReader reader = new BufferedReader (InputStreamReader);StringBuffer sb = new StringBuffer ("");          String Line;                  try {while (line = Reader.readline ())! = null) {sb.append (line);              Sb.append ("\ n");          }} catch (IOException e) {e.printstacktrace ();      } return sb.tostring (); } public void KeepAlive () {new Thread () {public void run () {HttpClient client = new Defaulthttpclie          NT ();          HttpGet get = new HttpGet ("http://www.baidu.com");        HttpResponse response;        try {response = Client.execute (get); if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {InputStream is = Response.getenti              Ty (). getcontent ();              String result = Instream2string (IS);              Assert.assertequals (Result, "get_success");            Toast.maketext (Video.this, "Http Get Success:", Toast.length_long). Show (); LOG.V ("FFMPEG-----=", result);                } else {//toast.maketext (video.this, "Http Get Fail", Toast.length_long). Show (); }} catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstack        Trace ();        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();        }//super.run ();}    }.start (); }          }

The key function of the file is the OnReceive function, where you receive the Video_timer message sent by the system, and then we start a new task to run the Timerservice code:

    public void OnReceive (context context, Intent Intent)     {        if (intent.getaction (). Equals ("Video_timer"))         {        Intent intentservice = new Intent (context, timerservice.class);  ACTIVITY intentservice.addflags to start        (intent.flag_activity_new_task);        Context.startservice (Intentservice);                }    }


Full Source: http://download.csdn.net/download/langeldep/7845831



Timer implementation in Android background

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.