KIO
Kreative Ideen online
The State of an activity

The State of an activity

When Android creates and destroys an activity, the activity moves from being launched to running to being destroyed.

An activity is running whent it’s in the foreground of the screen.
onCreate() gets called when the activity is first created, and it’s where you do your normal activity setup.
onDestroy() gets called just before your activity gets destroyed.

The main state of an activity is when it’s running or active. An activity is running when it’s in the foreground of the screen, it has the focus, and the user can interact with it. The activity spends most of its life in this state. An activity starts running after it has been launched, and at the end of it’s life, the activity is destroyed.

  • Activity launched
    The activity object has been created but it’s not yet running
  • Activity running
    Your activity spends most of its life here
  • Activity destroyed
    At this point, your activity no longer exists.

When an activity moves from being launched to being destroyed, it triggers key activity lifecycle methods:
onCreate()
and
onDestroy()

These are lifecycle methods that your activity inherits, and which you can override in necessary.

The onCreate() method gets called immediatley after your activity is launched. This method is where you do all your normal activity setup such as calling setContentView(). You should always override this method. If you don’t override it, you won’t be able to tell Android what layout your activity should use.

The onDestroy() method is the final call you get before the acctivity is destroyed. There are a number of situations in which an activity can get desroyed – for example, if it’s been told to finish, if the activity is being recreated due to a change in device configuration, or if Android has decided to destroy the activity in order to save space.

The activity lifecycle: from reate to destroy

Here’s an oversimplified overview of the activity lifecycle from birth to death.

Activity lauched

onCreate()

Activity running

onDestroy()

Activity destroyed

  1. The activity gets launched.
    The activity object is created and it’s constructor is run.
  2. The onCreate() method runs immediatley after the activity is launched.
    The onCreate() method is where any initialization code should go, as this method always gets called after the activity has launched but before it starts running.
  3. An activity is running when it’s visible in the foreground and the user can interact with it.
    This is where an activity spends most of its life.
  4. The onDestroy() ethod runs immediately before athe activity is destroyed.
    The onDestroy() method enables you to perform any final cleanup such as freeing up resources.
  5. After the onDestroy() method has run, the activity is destroyed.
    The activity ceases to exist.
    Note: If your device is extremely low on memory, onDestroy() might not get called before the activity is destoyed

The onCreate() and onDestroy() methods are two of the activity lifecycle methods. So where do these methods come from?

Your activity inherits the lifecycle methods

Your activy extends the android.app.Activity class. This class is the one that gives your activity access to the Android lifecycle methods.Here’s a diagram showing the class hierachy:

  1. Context
    Context abstract class
    (android.content.Context)
    An interface to global information about the application enviroment.
    Allows access to application resources,classes, and operations.
  2. ContextWprapper class
    (android.content.ContextWrapper)
    A proxy implementation for the Context.
  3. ContextThemeWrapper class
    (android.view.ContextThemeWrapper)
    Allows you to modify the theme from what’s in the ContextWrapper.
  4. Activity class
    (android.app.Activity)
    The Actitvity class implements default versions of the lifecycle methods.It also defines methodds such as findViewById(Int) and setContentView(View).
  5. YourActivity class
    (com.mydomain.foo)
    Most of the behavior of your activity is handled by superclass methods your activity inherits.All you do is voerride the methods your need.

An example:

Save the current state….

When the screen switches from landscape to portrait, the activity gets destroyed and recreated, which means that local variable used by the activity are lost. So how dow we get around this?

The best way of dealing with configuration changes is to save the current state of the activity, and then reinstae it in the onCreate() method of the activity.

To save the activity’s state, you need to implement the onSaveInstanceState() method. This method gets called before the activity gets destroyed, which means you get an opportunity to save any values you want toretain before they get lost.

The onSaveInstanceState() method takes one parameter …

Bundel

A Bundle allows you to gather together different types of data into a single object:
public void onSaveInstanceState(Bundle savedInstanceState){}

The onCreate() method gets passed the Bundle as a parameter. This means that if you add the values of variables to the Bundle, the onCreate() method wil be able to pick them up when the activity get recreated. To do this, you use Bundle methods to add name/value pairs to the Bundle. these methods take the form:

bundle.put*(“name”,value)

where bundle is the name of the Bundle, * is the type of value you want to save, and name and value are the name and value of the data. As an example, to add the a value to the Bundle, your’ use:
bundle.putInt(“seconds”, secons);

You can save multiple name/value pairs of data to the Bundle.

//Save the values of the seconds and running variables to the Bundle.
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
         savedInstanceState.putInt("seconds", seconds);
         sevedInstanceState.putBoolean("running", running);
}

Once you’ve saved variable values to the Bundle, you can use them in your onCreate() method.

.. then restore the state in onCreate()

As we seid earlier, the onCreate() method takes one parameter, a Bundle. If the activity’s being created from scratch, this parameter will be null. If, however, the activity’s being recreated and there’s been a prior call to onSaveInstanceState(), the Bundle object used by onSaveInstanceState() will get passed to the activity:

protected void onCreate(Bundle savedInstanceState){}

You can get values from Bundle by using methods of the form:

//Instead of *, use Int,String, and so on, to specify the type of data you want to get.
bundle.get*("name");

where bundle is the name of the Bundle, * is the type of value your want to get, and name is the name of the name/value pair you specified. As an example, to the the seconds value from the Bundle, you’d use:

int seconds = bundle.getInt(“seconds”);

Putting all of this together, here’s what a onCreate() method would look like.

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);
    if(savedInstanceState != null){
       seconds = savedInstancesState.getInt("seconds");
       running = savedInstanceState.getBoolean("running");
    }
    runTimer();
}  

Advanced….

There’s more to an activity’s life than create and destroy

So far we’ve looked at the create and destroy parts of the activity lifecycle(and a little bit in between), and you’ve seen how to deal with configuration changes such as screen orientation. But there are other events in an activity’s life that you might want to deal with to get the app to behave in the way your want.

As an eample, suppos the a stopwatch is running and you get a phone call. Even though the stopwatch isn’t visible, it will continure running. But what if you want the stopwatch to stop while it’s hidden, and resume once the app is vidble again?

Start, stop, and restart

Foortunatley, it’s easy tho handle actions that relate to an avtivity’s visibility if you use the right lifecycle methods. In addition to the onCreate() and onDestroy() methods, which deal with the overall lifecycle of the activity, thera re aother lifecycle methods that deal with an activity’s visibility.

An activity has a state of topped if itÄs completely hidden by another activity and isnt’t visible to the user.The activity still exists in the background and maintains all state information.

Specifically, there are three key lifecycle methods that deal with when an activity becomes visible or invisible to the user:

  • onStart()
  • onStop()
  • onRestart()

Just as with onCreate() and onDestroy(), your activity inherits them from the Android Avtivity class.

onStart() gets called when your activity becomes visible to the user.

onStop() gets called when your activity has stopped being visible to the user.This might be because it’s comöetely hidden by another activity that’s appeared on top of it, or because the activity is going to be destroyed. If onStop() is called because the activity’s going to be destroyed,
onSaveInstancesState() gets called before onStop().
onRestart() gets called after your activity has beeb made invisble, before it gets made visible again.

  1. The activity gets launched, and the onCreate() method runs.
    Any avtivity initialzation code in the onCreate() method runs. At this point, the activity isn’t yet visible, as no call to onStart() has been made.
  2. The onStart() method runs.It gets called when the activity is about to become visible.
    After the onStart() method has run, the user can see the ac tivity on the screen.
  3. The onStop() method runs when the activity stops being visible to the user.
    After the onStop() method has run, the activity is no longer visible.
  4. If the activity becomes visible to the user again, the onRestart() method gets called followed by onStart().
    The activity may go through this cycle many times if the activity repeatedly becomes incisible and then visible again.
  5. Finally, the activity is destroyed.
    The onStop() method will get called befor onDestroy().
public class SomeActivity extends Activity{
      private boolean local_running;
      private boolean local_wasrunning;

      @Override
      protected void onCreate(Bundle savedInstanceState){
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activty_something);
             if(savedInstanceState != null){
             running = savedInstanceState.getBoolean("running");   
             wasrunning = savedInstanceState.getBoolean("wasrunning");
             }
      } 

      @Override
      public void onSaveInstanceState(Bundle savedInstanceState){
           savedInstanceState.putBoolean("running", local_running);
           savedInstanceState.putBoolean("wasrunning", local_wasrunning);
      }

      @Override
      public void onStop(){
          super.onStop();
          local_wasrunning = local_running;
          local_running = false;
      }

      @Override
      protected void onStart(){
         super.onStart();
         if(local_wasrunning){
             local_running = true;
         } 
     }
}

Leave a Reply

Your email address will not be published. Required fields are marked *