Android:Activity

From Juneday education
Jump to: navigation, search

Android Activity

An Activity is a fundamental building block of an Android app. It is the starting point for your app, so your app needs at least one. It is important to know how an application may get paused due to a phone call and how to handle that. If you're using more than one Activity you need to know how you switch between Activities. This chapter introcudes these concepts to you.

Videos

All videos in this chapter: Android:Activity

See below for individual links to the videos.

Activity Lifecycle

Android provides means to let you, as a programmer, decide how an Activity should behave when for example a user clicks the Back button or if you get a phone call while using an app. We will use a practical approach to give you an idea of how you can control your Activity.

A simplified illustration of the activity lifecycle. The picture is originally from Activity Lifecycle and is Licensed under Apache 2.0.

Let's see what is written on the page Activity Lifecycle at developer.android.com:

For example, good implementation of the lifecycle callbacks can help ensure that your app avoids:

  • Crashing if the user receives a phone call or switches to another app while using your app.
  • Consuming valuable system resources when the user is not actively using it.
  • Losing the user's progress if they leave your app and return to it at a later time.
  • Crashing or losing the user's progress when the screen rotates between landscape and portrait orientation.}}

When an activity switches between the stages in its lifecycle, six methods get called (if you have declared them):

Videos

External video:

Switching between Activities

An app can have one or many activities, and it's quite likely that you need to switch between activities - why would you have more than one Activity otherwise. It's easy to switch from one Activity to another. In short you: call the method startActivity() or startActivityForResult and passing an Intent. The intent lets you specify what Activity you want to switch to.

Let's say you want to start an Activity called UserActivity.

The corresponding code will switch to that activity:

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

Videos

Passing data to the Activity to start

If you want to start an activity and pass information to that Activity you simply use the methods putExtra() and getExtras(). The methods getExtras and putExtra let you store store objects together with a key. As an example you can pass a User object in the bundle together with the key "user" and in the Activity you start get that User object using the same key. Typically you don't hard code strings but rather use constant String (static final String).

Here's an example of how to pass a User object to an Activity:

  public void startBlaBla(View v) {
    Log.d(LOG_TAG, "Starting Bla Bla");
    Intent intent = new Intent(this, BlaBlaActivity.class);
    intent.putExtra(USER_TAG, user);

    intent.putExtra(TEMP_TAG, 21);
    startActivity(intent);
  }

The code above assumes:

  • you have a class Constants with a String USER_TAG
  • you have a class Constants with a String TEMP_TAG
  • you have a User class that implements Parcelable
  • user is a User instance (object)

Videos

Implementing Parcelable

In order to pass data other than String, int etc you need to have that class implement Parcelable. In short, Parcelable is an interface for classes the can be written and retrieved from a Parcel. A Parcel is a container for a message you can send, typically when switching between activities.

We will not spend to much time on this here. Instead we will refer to the live video and the code below for the User class:

package se.juneday.throwaway.activityswitcher;

import android.os.Parcel;
import android.os.Parcelable;

public class User implements Parcelable {

  private String name;

  public User(String name) {
    this.name = name;
  }

  public String name() {
    return name;
  }

  public String toString() {
    return name;
  }

  public static final Parcelable.Creator<User> CREATOR
      = new Parcelable.Creator<User>() {
    public User createFromParcel(Parcel in) {
      return new User(in);
    }

    public User[] newArray(int size) {
      return new User[size];
    }
  };


  private User(Parcel in) {
    name = in.readString();
  }
  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(name);
  }
}

Note: Parcel is not a serialization mechanism. Don't use Parcel for permanent storage

Retreieving data passed to an Activity

Here's an example of how to retrieve the User instance passed to the Activity in the previous section:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bla_bla);

    Bundle extras = getIntent().getExtras();
    if (extras == null) {
      return;
    }

    int temp = extras.getInt(MainActivity.TEMP_TAG);
    Log.d(LOG_TAG, "You passed temp: " + temp);

    User user = getIntent().getParcelableExtra(MainActivity.USER_TAG);
    if (user != null) {
      Log.d(LOG_TAG, "You passed user: " + user);
    }
  }
}

Videos

Getting something back from an Actvity

Let's say you want to take a photo. You can do this in different ways, but in this chapter we'll be focusing on starting the Photo app an getting the photo back. Starting the photo app is pretty straight forward. You create and intent and then start the activity (not in your app). But his time we'll be using the method startActivityForResult since we want something back (the picture).

So let's look at some example code:

 public void startCamera(View v) {
    // The code below is taken from https://developer.android.com/training/camera/photobasics.html
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
      startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
  }

The code above launches the camera app. After having taken a photo and ok it (or cancel) Android gives back the control to your Activity (from which you started the camera app). If we read the specs for the camera app we'll find that the photo can be retrieved from a bundle using the String "data".

So let's look at a code example:

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // The code below is heavily based on https://developer.android.com/training/camera/photobasics.html
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
      Bundle extras = data.getExtras();
      Bitmap imageBitmap = (Bitmap) extras.get("data");
      ImageView imageView = (ImageView) findViewById(R.id.imageView);
      imageView.setImageBitmap(imageBitmap);
    }
  }

Videos

Sharing data between Activities

If you would like to share a bit more complex classes and don't feel an urge to implement Parcelable you can create a Singleton class and use that

package se.juneday.throwaway.activityswitcher;

public class Session {

  private static Session session; 

  public User currentUser; 

  // private constructor to prevent other from creating Session objects
  private Session() {};

  static {
    session = new Session();
  }

  public static Session getInstance() {
    return session;
  }

}

Note: we make the currentUser reference public since we want this reference to be updated. Having a private reference variable and public getters and setters will not give us any extra ...well, possibly some extra lines which might be good if you get "paid by the lines". Also, check out our page about Getters and setters

We can use this class in our MainActivity to keep track a the current User.

    Session.getInstance().currentUser = new User("This is me!");

and then use that in another activity.

    Log.d(LOG_TAG, "current user: " +     Session.getInstance().currentUser);

Videos

Going back

When a user clicks the back button, which app or Activity does Android switch to? We will not go into this in this chapter, but would like to give you a link in case you woyld like to read more. Check out: Tasks and Back Stack.

Links

Exercises for this chapter

  • [[]]

Files

External links

Books this chapter is a part of

Android - the practical way

Book TOC | previous chapter | next chapter