0

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

Thanawat.h
  • 11
  • 4
  • it your application gets killed then their no reference of asyntask or thread available. It will be garbage collected so you don't have to closed or remove it again. – Jitesh Mohite Mar 14 '17 at 07:56
  • Use AlarmManager instead, don't use AsyncTask – HendraWD Mar 14 '17 at 08:04
  • add some flag to your thread, which will be checked to decide if it should continue running, and set it to true when the app is closed. – Vladyslav Matviienko Mar 14 '17 at 08:14
  • `new LongOperation(this)` is `this` is `Activity`? Why do you need to passing `Activity` to `AsyncTask` when you don't have that constructor on `LongOperation`? – HendraWD Mar 14 '17 at 10:34

2 Answers2

1

It is a bad choice if you want to count on the background using AsyncTask inside an Activity, because it will lead to Activity leak. I enforce you to use AlarmManager or Service instead. Just for knowledge i will show you how to kill your AsyncTask inside an Activity when the Activity stopped or on the background. Firstly, you must make a member variable of your AsyncTask

private LongOperation task;

Then you start your AsyncTask like this

task = new LongOperation();
task.execute();

Lastly, you stop your AsyncTask from Activity's onStop

@Override
protected void onStop() {
    super.onStop();
    task.cancel(true);
}
HendraWD
  • 2,984
  • 2
  • 31
  • 45
  • 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. – Thanawat.h Mar 14 '17 at 10:19
  • @Thanawat.h No. When you close the App, the `AsyncTask` is closed. – JonZarate Mar 14 '17 at 10:27
  • Yes, `AsyncTask` will be terminated if the application closed, but not if the application run on the background. `Service` is not an `AsyncTask`, you can see it here https://developer.android.com/guide/components/services.html – HendraWD Mar 14 '17 at 10:30
-1

I think you assumed the old Thread is alive because the code is not running.

However, I think you are wrong. The problem is that you miss the execute() call.

Try the following code:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LongOperation task = new LongOperation(this);
        task.execute(); // <-- New added code
    }

    private class LongOperation extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < 25; i++) {
                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();
        }
    }
}
JonZarate
  • 841
  • 6
  • 28