我在一个线程上运行繁重的操作,该操作在按钮单击时被调用。为了防止用户再次单击该按钮,我只是检查 if thread.isAlive()
,只要我处于当前活动中,它就可以正常运行。当我按下 backpress 并再次进入此活动时,thread.isAlive()
返回 false 并再次开始执行该密集功能,因为我正在 onCreate 中创建新线程。我该如何解决这个问题?我的代码如下
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();
}
}
});}
备份线程类
class BackupThread extends Thread {
BackupRestore.Backup backup;
BackupThread(BackupRestore.Backup obj)
{
this.backup=obj;
}
@Override
public void run() {
backup.overallbackup();
backup.dbbackup();
backup.deletetempfolder();
}