How to check if thread is alive after restarting an Activity?

1k Views Asked by At

I am running a heavy operation on a thread, which is invoked on button click. To prevent user from clicking that button again, I am simply checking if thread.isAlive(), which runs fine as long as I am in the current activity. When I press backpress and come again to this activity, thread.isAlive() returns false and start executing that intensive function again because I am creating new thread in onCreate. How can I solve this? My code as under

 Thread thread;
     @Override
           protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_backup_restore);
           Backup backupobj= new Backup();
            thread= new Thread (new BackupThread(backupobj));

                  button.setOnClickListener(v -> { 
                  if(posts.size()>0) {

                 if (!thread.isAlive()) {
                   thread.start();

                 }
                 else {
                     Toast toast = Toast.makeText(getApplicationContext(), "Backup in Progress" , 
                     Toast.LENGTH_LONG);
                     toast.show();

                 }

         }
     });}

BackupThread class

class BackupThread extends Thread {
BackupRestore.Backup backup;

BackupThread(BackupRestore.Backup obj)
{
    this.backup=obj;
}


@Override
public void run() {

    backup.overallbackup();
    backup.dbbackup();
    backup.deletetempfolder();

}
1

There are 1 best solutions below

1
Ravi On

To be precise,

Thread.isAlive() returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

Thread.getState() returns the exact state of the thread.