I use timer to schedule some thing to do after time. And when I close my apps, timer alives until work comple. (It is what I want, and I did ). But when I open it again, 2 timer is run (old and new). How to remove old timer when reopen apps. I know my question is difficult to understand. But I hope some one can help me. Thanks
Asked
Active
Viewed 170 times
2 Answers
0
You should stop your timer when your activity call onStop.
Checkout the life cycle of an Activity http://developer.android.com/reference/android/app/Activity.html
If your timer is a global variable
@override
public void onStop(){
super.onStop();
mTimer.cancel();
}
Well, if you want to save your data after user is closing your form, it is a good idea to use a service. In your Activity onStop() You could save all the form data in a parcelable / serializable model, put that model into the intent service, and then call service with startService(Intent)
@Override
public void onStop(){
FormData formData = recoverAllMyFormData();
Intent myServiceIntent = new Intent(this, MyService.class);
myServiceIntent.putParcelable("INTENT_EXTRA_FORM_DATA", formData);
startService(myServiceIntent);
super.onStop();
}
Then, in your Service onStartCommand will be called. I like to use ThreadPoolExecutor to control one thread at a time
//Global variable
private ThreadPoolExecutor storerExecutor = new ThreadPoolExecutor(1, 18, 50, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final FormData formData = intent.getParcelable("INTENT_EXTRA_FORM_DATA");
if(formData != null){
storerExecutor.execute(new Runnable(){
public void run(){
//Use your sqlite code to store the form
}
});
}
return Service.START_NOT_STICKY;
}
Note: FormData should implement Parcelable
Thats what i can suggest without see your code ;)

jDur
- 1,481
- 9
- 10
-
I kown that. But I have to do complete to do some thing. So I have to wait to cancel it. And by the time it's not canceled, user can reopen it. And 2 timer is run. Some complits can be occur when 2 timer do same thing. – user3709485 Jul 03 '14 at 10:47
-
Maybe you could use a Service and sync the process you want to do. It is a bad practise to use Timer and TimerTask in android. There is other pretty nice ways to schedule a Task. Have an eye in handlers, Services and TimerTasks. – jDur Jul 03 '14 at 11:01
-
Thanks. I used Service whith Timmer do do.After 5s I want to excute an Asysntask to update data from sqlite to spreadsheet. By the time updating in asysntask, user can add data to sqlite. When closing app all data form sqlite need to be update. So I wait util updating complete , I cancel timer. Can you give me suggestions. – user3709485 Jul 03 '14 at 11:13