Reputation: 8362
Most of the times we as programmers experience this problem, when we are in between of certain Asynctask doinBackground() Method - performing an operation which requires Network (Internet Connection), and if in between the network is lost then our Application results in Force Close or Crash, or FreeZed. To stop this we use try/catch operations to be used with the code.
I just want to know is there any perfect means to do the same, Scenario written below,
Here in my case:
I require Internet Connection after every 20secs to parse an API in the Asyntask, and based upon the result of the API, I have to update the UI on the screen.
Here is my Timer Method
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
if(DCCStaticMethod.checkInternet(DriverMainMenuActivity.this)){
try {
if(mLocalAreaDriverPass.getStatus() == AsyncTask.Status.FINISHED){
mLocalAreaDriverPass = new LocalAreaDriverPass(DriverMainMenuActivity.this,true);
mLocalAreaDriverPass.execute();
Log.d("RefreshLocalAreaTimerDriver", "running");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
timer.scheduleAtFixedRate(task, 20000, 20000);
Suppose at any instant of time, the internet connectivity is lost or goes down, how to cancel and restart the timer again to achieve my requirement.
I HAVE SO MANY TRICKS AND CRANKS TO PERFORM THE SAME, BUT I AM IN SEARCH OF GOOD MEANS TO PERFORM THESE TYPES OF TASKS IN FUTURE, AS THESE TYPES OF TASKS OCCUR IN ALMOST ALL THE APPS
Upvotes: 0
Views: 364
Reputation: 3721
There is a custom class CountdownTimerwithPause.By using this you can pause and cancel the timer in middle of Asyn Task
Refer the below link
How to extend CountDown Timer With Pause?
Upvotes: 1
Reputation: 12733
Make broadcast receiver for checking internet connection. and get status of that. if connection is lost then set value to variable of any application class or simple class and then use that variable in activity for stop timer.
Upvotes: 1