Android timer and changing of its period
I'm developing an application that should execute some task periodically (10 seconds) in the background. For this I use Service and Timer. Actual jobs to be done in timer are:
1) collecting data from the phone (using ContentResolver) into the SQLite database, 2) sending this data to remote server synchronously using HttpPost method.The problem is next: after some iterations (ammount of these iterations changes every execution of the app) timer changes its period and start to perform all the tasks with 1-3 seconds (sometimes up to 9, but it always lower than 10 secs) delay, which is way too fast in my case and I can't find the reason. Has anyone faced similar behavior before?
I've tried to use different threads for uploading and collecting inside the timer task, but it didn't solve the problem.
Here's my code snippets:
public class DataForward extends Service{
private Context con = getBaseContext();
private Timer time开发者_如何学运维r = new Timer();
<...>
@Override
public void onStart(Intent intent, int startId) {
timer.schedule(new TimerTask(){
@Override
public void run() {
try {
updateData();
NetworkManager network = new NetworkManager(con);
if(network.isConnectedToTheInternet())
uploadData();
} catch (Exception e) {
e.printStackTrace();
}
}}, 0, 10000);
}
}
<...>
}
Or maybe there's another way to do this without actual Timer? Any Ideas?
The reason could be, since you told its running on a service, its so possible that your
backgroundTask(Service) may get killed when android OS finds its going low on RAM inorder to keep its
foreGround Applications running.. And again when it gets Free Ram it Restarts the Service Again, so
it may be restarting timer again and again.
for more Read THis ..SERVICE
First execution of your time is 0 millis and subsequent execution is after 10 millis.But android os may stop your service for internal task management.So,again when your service start s after some time then it reset timer again.So,it will execute your task immediately.thats the reason of your problem. So you can set a time minimum time for your first execution or can use repeating Alarm.
精彩评论