Java timer running in Android

Source: Internet
Author: User
 

Objective: To use timer for timing, it is required to run in the service and record data every 10 minutes. However, after using timer, we found that the number of statistics did not reach the expected goal. Not even running. The following are the test cases:

1. Set the cycle time to 2 seconds to see the test results.

I plan to use the service for testing, but I will use the activity for testing for convenience.

Package COM. test. timertest;/*** test the timer */import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. textview; public class timeractivity extends activity {private textview txtcount; private int count; // processing interface private handler = new handler () {public void handlemessage (Android. OS. message MSG) {If (MSG. arg1 = 1) {txtcount. settext (string. valueof (count) ;}};@overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method limit count = (textview) findviewbyid (R. id. count); new timer (). schedule (counttask, 10,200 0); // The latency is 10 milliseconds and is executed every 2 seconds.} // The task timertask counttask = new timertask () {@ overridepublic void run () {// todo auto-generated method stubcount ++; message MSG = new message (); MSG. arg1 = 1; handler. sendmessage (MSG );}};}

Result:

1. Connect the mobile phone to the computer for testing, change the program to normal, and continue to run. In addition, press the power key to continue normal operation, and the number of statistics is also normal.

2. After the phone is disconnected from the computer, run the program again. The program can run normally. Then press the power key, and the phone is in the STANDBY state. After a period of time, I watched the number of times on the screen and found that the number of times was not moving. I don't know why ???

3. After the phone is disconnected from the computer, run the program and press the Home key. When the phone is not in the STANDBY state, the count of the statistics changes and the phone can run normally. However, if the mobile phone is in the standby status, the program is not running.

Problem: After the mobile phone is in standby mode, most programs will not run (except by phone or SMS ). Is this a system protection mechanism ???

2. Use thread sleep for processing;

Package COM. test. timertest;/*** test the timer */import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. textview; public class timeractivity extends activity {private textview txtcount; private int count; // processing interface private handler = new handler () {public void handlemessage (Android. OS. message MSG) {If (MSG. arg1 = 1) {txtcount. settext (string. valueof (count) ;}};@overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method limit count = (textview) findviewbyid (R. id. count); // new timer (). schedule (counttask, 10,200 0); // The latency is 10 milliseconds, and new countthread () is executed every 2 seconds (). start ();} class countthread extends thread {@ overridepublic void run () {While (true) {count ++; message MSG = new message (); MSG. arg1 = 1; handler. sendmessage (MSG); try {thread. sleep (2000);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}}/// task // timertask counttask = new timertask () {// @ override // public void run () {// todo auto-generated method stub // count ++; // message MSG = new message (); // MSG. arg1 = 1; // handler. sendmessage (MSG );//}//};}

The processing result using sleep is the same as that in the preceding 1. If the activity and thread are different, the thread is used for processing and the result is saved to XML.

The service is as follows:

Package COM. test. timertest; import Java. util. timer; import Java. util. timertask; import android. app. service; import android. content. context; import android. content. intent; import android. content. sharedpreferences; import android. content. sharedpreferences. editor; import android. OS. ibinder; public class countservice extends Service {@ overridepublic ibinder onbind (intent) {// todo auto-generated method stubreturn NULL;} @ overridepublic void oncreate () {// todo auto-generated method stubsuper. oncreate (); new timer (). schedule (counttask, 10,200 0); // 2 seconds} // task timertask counttask = new timertask () {@ overridepublic void run () {saveappcount ();}}; // Save the data private void saveappcount () {int COUNT = getappcount () + 1; sharedpreferences Sf = getsharedpreferences ("appcount", context. mode_private); Editor editor = SF. edit (); Editor. putint ("count", count); Editor. commit ();} // obtain the public int getappcount () {sharedpreferences SPF = getsharedpreferences ("appcount", context. mode_private); Return SPF. getint ("count", 0 );}}

Activity for displaying data

Package COM. test. timertest;/*** test the timer */import android. app. activity; import android. content. context; import android. content. intent; import android. content. sharedpreferences; import android. OS. bundle; import android. widget. textview; public class timeractivity extends activity {private textview txtcount; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method interval COUNT = (textview) findviewbyid (R. id. count); sharedpreferences SPF = getsharedpreferences ("appcount", context. mode_private); int COUNT = SPF. getint ("count", 0); txtcount. settext (string. valueof (count); intent = new intent (this, countservice. class); startservice (intent );}}

Test results ::

1. The mobile phone is connected to the computer, and the mobile phone is in debugging mode. Whether you press the power key to keep the mobile phone in standby status or press the Home key, the service can provide normal statistics.

2. The mobile phone is disconnected from the computer. no matter whether the mobile phone is automatically in the STANDBY state or actively press the power key to keep the mobile phone in the STANDBY state, the threads in the service do not properly record data. Solution ???

Combined with online data, alarmmanager is used to control timing operations. This ensures that the System Broadcasts data during sleep to achieve statistical purposes.

Package COM. test. timertest;/*** test the timer */import Java. util. timer; import android. app. activity; import android. app. alarmmanager; import android. app. pendingintent; import android. content. context; import android. content. intent; import android. content. sharedpreferences; import android. OS. bundle; import android. OS. systemclock; import android. widget. textview; public class timeractivity extends activity {private textview txtcount; public final string action = "com. test. timertest. alarmreciver "; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method limit count = (textview) findviewbyid (R. id. count); sharedpreferences SPF = getsharedpreferences ("appcount", context. mode_private); int COUNT = SPF. getint ("count", 0); txtcount. settext (string. valueof (count); // intent = new intent (this, countservice. class); // startservice (intent); // alarm global variable alarmmanager AM = (alarmmanager) getsystemservice (alarm_service); intent = new intent (action); pendingintent sender = pendingintent. getbroadcast (this, 0, intent, 0); long firsttime = systemclock. elapsedrealtime (); firsttime + = 2*1000; AM. setrepeating (alarmmanager. elapsed_realtime_wakeup, firsttime, 2*1000, Sender); // alarmmanager. elapsed_realtime_wakeup this type of tiype is used here to ensure that the system can broadcast during sleep. If you do not understand it, you can go to the introduction of the document }}

Broadcast receiving Class

Package COM. test. timertest; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android. content. sharedpreferences; import android. content. sharedpreferences. editor; public class alarmreciver extends broadcastreceiver {@ overridepublic void onreceive (context, intent) {// todo auto-generated method stubsaveappcount (context );} // Save the private void saveappcount (context) {int COUNT = getappcount (context) + 1; sharedpreferences Sf = context. getsharedpreferences ("appcount", context. mode_private); Editor editor = SF. edit (); Editor. putint ("count", count); Editor. commit () ;}// get the public int getappcount (context) {sharedpreferences SPF = context. getsharedpreferences ("appcount", context. mode_private); Return SPF. getint ("count", 0 );}}




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.