I am start working on the Asynctask Demo. What I want is , "When I press the back button in the android device I want to stop the task which is running in the app "
I set up this thing on the onBackPressed() method but after this in the Logcat Task doesn't stop .
Where am I make the mistake , help me out of this ?
public class Activity1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CountDownTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
new CountDownTask().cancel(true);
}
private class CountDownTask extends AsyncTask<Void, Integer, Void>{
@Override
protected void onPreExecute() {
TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
tvCounter.setText("START");
}
@Override
protected Void doInBackground(Void... params) {
for(int i=15;i>=0;i--){
try {
Thread.sleep(1000);
publishProgress(i);
Log.e("Aka", String.valueOf(i));
if(isCancelled()){
break;
}
} catch (InterruptedException e) {
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
tvCounter.setText( Integer.toString(values[0].intValue()));
}
@Override
protected void onPostExecute(Void result) {
TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
tvCounter.setText("DONE");
}
}
}