0

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();

}
MMG
  • 3,226
  • 5
  • 16
  • 43
ZigZag
  • 53
  • 6
  • 1
    Even if it does not answer your question, have you considered using WorkManager? It greatly simplifies your work and ensures your work is done. From the `run` function of your thread, I see you try to do a backup, which is why `WorkManager` exists (and not only!) https://developer.android.com/topic/libraries/architecture/workmanager – SnuKies Mar 30 '20 at 09:39
  • 1
    This code isn't going to work, as the Activity may not be the same and thus the Thread variable won't be initialized. The correct answer here is to either have the Thread owned by a Service, or to use something like WorkManager. If neither of these work you can hack something like keeping it in a global variable somewhere, but really one of the previous two is your best bet. – Gabe Sechan Mar 30 '20 at 09:41
  • Also, your code is wrong. If BackupThread extends Thread, there is no need to do new Thread(new BackupThread()). Its just thread = new BackupThread(). The other might work because Thread implements Runnable, but its not how it should be used. – Gabe Sechan Mar 30 '20 at 09:42
  • I have changed the code as your recommended. For my original problem, i am going to look into workmanager. Thanks – ZigZag Mar 30 '20 at 09:49

1 Answers1

0

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.

Ravi
  • 2,277
  • 3
  • 22
  • 37