Is there anyway to kill thread/asynstask from closed android app
My app has to kill asynctask before run new asynctask
I tried Thread.getAllStackTraces() and check AsyncTask name when app open but I can not kill it.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
killThreadByName("AsyncTask");
LongOperation task = new LongOperation(this);
task.execute();
}
public void killThreadByName(String threadName) throws InterruptedException {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().contains(threadName)) {
t.interrupt();
}
}
}
private class LongOperation extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... params) {
while(true){
try {
Thread.sleep(1000);
publishProgress("This is number : " + i);
Log.i("TEST","NUMBER : " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(mContext, "Done!", Toast.LENGTH_SHORT).show();
}
}
}
This app is for counting 1 to 25 and when I close app, it still running.
But when I reopen the app, the old thread can not be killed.
I mean background service (Asynctask) still running forever even I close the app. The problem is if I open this app again I want the old asynctask be killed, and the new asynctask start from 1. now there are many asynctasks if I start this app more than 1 time.
Thank you