0

I have a dialog appearing on back press, but when it is show, I want the activity to be set on pause, there is animations playing, countdown timers working, etc.

Is there a simple way to put the whole activity on pause, without the need to pause each animation/timer, etc?

    @Override
public void onBackPressed() {

    AlertDialog.Builder builder = new AlertDialog.Builder(BreathActivity.this);
    ViewGroup viewGroup = findViewById(android.R.id.content);
    View dialogView = LayoutInflater.from(BreathActivity.this).inflate(R.layout.dialog_signin, viewGroup, false);
    builder.setView(dialogView);
    AlertDialog alertDialog = builder.create();
    alertDialog.show();

}

Thanks!

Roger Travis
  • 8,402
  • 18
  • 67
  • 94
  • 1
    Consider using an `Activity` with Dialog theme instead of an `AlertDialog`, this link provides some guidance https://stackoverflow.com/questions/1979369/android-activity-as-a-dialog. Starting an activity will pause the current activity – CSmith May 26 '21 at 18:11

2 Answers2

0

No, because there are a lot of threads (UI thread, your timer threads). So it is a very bad approach and maybe difficult to do.

What should you do?

Keep a reference of all timers, animations, and threads that are running by global variables. Create a method pauseAll() to pause all of them and another resumeAll() to resume all of them. When you show dialog call the pauseAll() method and when a user cancels the dialog you call resumeAll().

Vijay
  • 1,163
  • 8
  • 22
0

You could implement the ViewModel approach.

public class SharedTimerViewModel extends ViewModel{
    private TimerController timerController;
    public void setTimerController(TimeController timerController){
        this.timerController = timerController;
    }
    public TimerController getTimerController(){
        if(timerController != null){
            return timerController;
        }
        return new TimeController(){}
    }
}
public interface TimeController{
    default void control(Boolean on){}
}
public class MyActivty extends Activity implements TimerController {
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        SharedTimerViewModel model = new ViewModelProvider(this).get(SharedTimerViewModel.class);
        model.setTimerController(this);
        // do things
    }
    public void control(Boolean on){
        if(on){
            //start timers
        }else{
            //stop timers
        }
    }
}

Now inside any Android Lifecycle child object of the Activity ie Fragments and Dialogs you can call

SharedTimerViewModel model = new ViewModelProvider(this).get(SharedTimerViewModel.class);
model.getTimerController.control(false)//stopx timers
model.getTimerController.control(true)//start timers
avalerio
  • 2,072
  • 1
  • 12
  • 11