Available for hire
Switching Between Activities in an Android App

To move between activities in Android development you can simply use intents.

1
2
3
// new Intent(CurrentActivity instance, targetActivity class)
Intent i = new Intent(MainActivity.this, ResultActivity.class);
startActivity(i);

Before starting the activity we can even send some information around

1
2
3
Intent i = new Intent(MainActivity.this, ResultActivity.class);
i.putExtra("label", "A value which will be passed");
startActivity(i);

And then in your ResultActivity you can fetch the information

1
myLabel = getIntent().getStringExtra("label");

But what happens if we want to do something tricky? Perhaps from the MainActivity load the ResultActivity but automatically take the user back to the MainActivity.

It’s easy, you simply create a new runnable with a timeout as the last argument. In the below case, it’s 2000ms (2 seconds).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ResultActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // do your usual on create stuff!
    new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
        final Intent mainIntent = new Intent(ResultActivity.this, MainActivity.class);
        ResultActivity.this.startActivity(mainIntent);
        ResultActivity.this.finish();
      }
    }, 2000);

  }
}

Comments