Andrzej Gis
Andrzej Gis

Reputation: 14306

Thread still running after application stopps

My main activity does some initial things and than starts InitDBActivity. This one is supposed to check i database is up to date and update it if necessary. The following is done in InitDBActivity's onCreate method.

Thread asyncDBCreation = new Thread(new Runnable() {
                public void run() {

                    SQLiteDatabase db = null;
                    try{
                        db = dbh.getWritableDatabase();
                    }catch(Exception ex){
                        return;
                    }

                    if(dbh.recreateDB(db)){
                        try{
                            dbh.insertQueries(dbh.getQueries(getAssets()),db);
                        }catch(Exception ex){
                            dbh.close();
                            finish();
                            return;
                        }
                        dbh.close();

                        prefEdit.putLong(dbVersion, dbFileVersion);
                        prefEdit.commit();

                        startActivity(intent);
                        finish();
                    }
                    else{
                    }
                }
            });
            asyncDBCreation.start();

The problem is that if the user clicks the 'back' button he exits the app, but this thread is still running in background. It wold be fine - the job gets gone anyway, but... it turns out that if he launches the application again before this thread finishes - everything messes up. Data in database is multiplied. How can I kill this thread?

Upvotes: 1

Views: 1635

Answers (2)

yorkw
yorkw

Reputation: 41126

Manage your thread creation within a threadpool in Activity.onCreate(), and use Future.cancel() to kill the running thread in Activity.onDestroy():

private Future longRunningTaskFuture;

public void onCreate(Bundle savedInstanceState) {
  ... ...
  ThreadPoolExecutor threadPoolExecutor = Executors.newSingleThreadExecutor();
  Runnable longRunningTask = new Runnable();
  // submit task to threadpool:
  Future longRunningTaskFuture = threadPoolExecutor.submit(longRunningTask);
}

... ...
public void onDestroy() {
  // if you want to kill the task:
  if (longRunningTaskFuture != null)
    longRunningTaskFuture.cancel(true);
  ... ...
}

Cancel method will behaviour differently based on your task running state, check out the API for more details.

Upvotes: 1

idiottiger
idiottiger

Reputation: 5177

in java, dont have method can kill thread, only interrupt the thread, you can use method:thread.interrupt() to interrupt thread, but the thread must in the state which can be interrupted, like: sleep, or wait.

so, here you can use db.close method to close database, the data query work will throw exception, you can catch the exception to finish the thread work.

Upvotes: 1

Related Questions