Basics of Android Activities - noojman/Test-Prep-Grading-App GitHub Wiki

This application primarily utilizes the built-in features in Android Activities.

An Android Activity is defined as "a single, focused thing that the user can do". An activity can be seen as the main process that runs when you're on a screen. It determines what you see on screen and the interactable elements as well.

Each activity has an onCreate() method in which the content view and anything else desired is initialized on the creation of this activity during the lifespan of the app.

To change from one activity to another, it is accomplished by the following code:

 Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
 startActivity(intent);

An important concept for activities in Android is the stack. When changing activities like above, the previous activity is saved (although the state is not necessarily saved - more on that later). The allows the user to go back to that activity if permissible, such as by pressing the default Android back button.

If desired, it is possible to clear the stack and disable going back from the current activity. For example, in this application, if the user begins an exam, they cannot simply go back to the selection screen. This block is accomplished using flags.

 Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(intent);

If you wish to clear the state of the previous activity, you can use the call finish(). This will end that calling activity. In our application, we use a combination of the flags and finish() for our user authentication. If the user is already signed in, then the application will skip the Login screen and make the MainActivity (home page) the bottom of the stack.

 // Check if user is signed in (non-null) and update UI accordingly.
 FirebaseUser currentUser = mAuth.getCurrentUser();

 if (currentUser != null)
 {
      Intent intent = new Intent(LoginActivity.this, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
      startActivity(intent);
      finish();
 }

These are the basics of how this application utilizes Android Activities in order to manage user workflow.