Android background timer implementation, android background Timer

Source: Internet
Author: User

Android background timer implementation, android background Timer

The Android background runs the timer to facilitate the execution of positioning and tracking tasks. The following briefly describes the key points for implementing the Android background timer. The project code can be downloaded at the end of the article and can be compiled and executed directly.


The AndroidManifest. xml file contains the following content:


<?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: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="14"        android:targetSdkVersion="16" />    <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 grant the project RECEIVE_BOOT_COMPLETED permission:

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

The content of the Video. java file is 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) getSystem Service (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); // Save the data to 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. getInt ("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) fi NdViewById (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) f IndViewById (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 (); // get the Context object of SharedPreferences Ctx = Video. this; SharedPreferences sp = ctx. getSharedPreferences ("VIDEO", MODE_PRIVATE); // Save the data 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 present. 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 of this file is the following four 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);   am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 10*1000, sender); 
Intent. setAction ("VIDEO_TIMER") sets the type of message the system sends to the application as VIDEO_TIMER.

Am. setRepeating (AlarmManager. ELAPSED_REALTIME_WAKEUP, SystemClock. elapsedRealtime (), 10*1000, sender); this line of code allows the system to send a message for how long. Here I set a 10-second VIDEO_TIMER message.

The sent message is received and processed in the class AutoReceiver extends BroadcastReceiver class.




The following is the TimerService. java file:

Package com. routing. videocamera; public class TimerService extends Service {public void onCreate () {super. onCreate (); 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); // number of deposits According to String serverAddr = sp. getString ("ServerAddr", ""); String cameraName = sp. getString ("CameraName", ""); int cameraID = sp. getInt ("CameraID", 0); int cameraPort = sp. getInt ("CameraPort", 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 HTTP parameters (this part is not required) httpParams = new BasicHttpParams (); // set connection timeout and Socket timeout, and Socket cache size HttpConnectionParams. setConnectionTimeout (httpParams, 20*1000); HttpConnectionParams. setSo Timeout (httpParams, 20*1000); HttpConnectionParams. setSocketBufferSize (httpParams, 8192); // sets the redirection. The default value is true HttpClientParams. setRedirecting (httpParams, true); // set 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 an HttpClient instance // note HttpClient httpClient = new Htt PClient (); is the usage in Commons HttpClient //. In Android 1.5, we need to use the default Apache implementation DefaultHttpClient HttpClient httpClient = new DefaultHttpClient (httpParams); // String s = this. getName (); HttpGet httpRequest = new HttpGet (mUrl); String strResult = "doGetError"; try {HttpResponse httpResponse = httpClient.exe cute (httpRequest); if (httpResponse. getStatusLine (). getStatusCode () = 200) {strResult = EntityUt Ils. toString (httpResponse. getEntity ();} else {strResult = "Error Response:" + httpResponse. getStatusLine (). 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) {/* Create an HTTPPost object */HttpPost httpRequest = new HttpPost (url ); string strResult = "doPostError"; try {/* add request parameters to the request object */httpRequest. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8);/* send the request and wait for the response */HttpParams httpParams; // create HttpParams to set HTTP parameters (this part is not required) httpParams = new BasicHttp Params (); // sets the connection timeout and Socket timeout, And the Socket cache size HttpConnectionParams. setConnectionTimeout (httpParams, 20*1000); HttpConnectionParams. setSoTimeout (httpParams, 20*1000); HttpConnectionParams. setSocketBufferSize (httpParams, 8192); // sets the redirection. The default value is true HttpClientParams. setRedirecting (httpParams, true); // set 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 callback (httpParams); HttpResponse httpResponse = httpClient.exe cute (httpRequest);/* if the status code is 200 OK */if (httpResponse. getStatusLine (). getStatusCode () = 200) {/* read returned data */strResult = EntityUtils. toString (httpResponse. getEntity ();} else {strResult = "Error Response:" + httpRespon Se. getStatusLine (). 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); return strResult;} public void onDestroy () {super. onDestroy (); L Og. 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 executed by the timer, nothing special.


The AutoReceiver. java file is as follows:

Package com. routing. videocamera; public class AutoReceiver extends BroadcastReceiver {/* intent source to be received * // static final String ACTION = "android. intent. action. BOOT_COMPLETED "; private 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); // The Ctivity Intentservice. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); context. startService (Intentservice) ;}} public static String inStream2String (InputStream inputStream) {InputStreamReader inputStreamReader = null; try {inputStreamReader = new InputStreamReader (inputStream, "utf8 ");} catch (UnsupportedEncodingException e1) {e1.printStackTrace ();} BufferedReader reader = new BufferedReader (inputSt ReamReader); 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 DefaultHttpClient (); httpGet = new HttpGet ("http://www.baidu.com"); HttpResponse response; try {response = client.exe cute (get); if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {InputStream is = response. getEntity (). 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. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} // super. run ();}}. start ();}}

The key function of this file is the onReceive function. Here we receive the VIDEO_TIMER message sent by the system, and then we start a new task to execute the TimerService code:

Public void onReceive (Context context, Intent intent) {if (intent. getAction (). equals ("VIDEO_TIMER") {Intent Intentservice = new Intent (context, TimerService. class); // The Intentservice of the Activity to be started. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); context. startService (Intentservice );}}


Complete source code: http://download.csdn.net/download/langeldep/7845831




How to Implement android Timer

It can be implemented using Service + Broadcast + Handler.
Handler in Service
The main logic in the Service is: Use Handler to send a broadcast every minute
Broadcast in Activity, internal class form
Broadcast receives the Broadcast and calls the XX method.

Core: The Activity enables the service to send a broadcast notification every minute to call the method.

This is the code in the Activity.
Public class MainActivity extends Activity {public Intent startService; // Action public static final String BROADCAST_ACTION = "broadcast. action ";/** Called when the activity is first created. * // @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // register the broadcast IntentFilter filter = new IntentFilter (); filter. addAction (ConstantTool. BROADCAST_ACTION); registerReceiver (myResver, filter); // you can specify startService as a new Intent (MusicService. SERVICE_ACTION); startService. setClass (this, MusicService. class);} // assume that this is the method you call every minute. private void initViews () {}// this click event controls when to enable the Service private OnClickListener clickListener = new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubstartService (startService );}}; /*** broadcast ** @ author Administrator **/class MyResver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// first determine whether your actions are consistent if (BROADCAST_ACTION.equals (intent. getAction () {// if they are consistent, call the initVies () ;}}@ Overrideprotected void onDestroy () {& #4 ...... remaining full text>

What can I do if I want to learn how to set an alarm clock for android to run in the background and try to bring up images in time?

It can be used as a timer. The alarm is actually a timer. After you set the time, it will calculate how long it will last and then run the timer. When the time is reached, the code block will be implemented.
 

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.