Three ways to open new Activity in Android

The idea that come to my mind to write this post was to help some beginners in Android to let them know how to link two or more activities in Android. I am going to mention 3 ways in which you can do this.

This post is gonna be a very basic one but my main motive in it was that beginners sometimes don't know about this and they ask some dumb questions on StackOverflow. So here I am getting started with it. But first you need to have at-least two activities in your project. Suppose they are Activity1 and Activity2. The java files associated with them are: and Here I am assuming that you want to navigate from Activity1 to the Activity2

We will move from the easiest one to the difficult one and I'll explain why that method is used.

  1. The simple one
  2. So this method is the simplest one. You need to do is this:
    startActivity(new Intent(Activity1.this, Activity2.class));
    This is used when you simply want to navigate to other activities

  3. A bit complex one
  4. This one is the copy of the first one but splitted into declaration and usage like this:
    Intent openActivity = new Intent(Activity1.this, Activity2.class);
    Explanation: This method is used when we want to pass some custom parameters to the Intent. You will come to know more about flags attached to Intents in the later posts.

  5. The difficult one
  6. So have you ever thought that when you select a file in android and click the share button, you see a list of apps that can perform the action, they use a kind of this method. First, edit the Activity2 in the AndroidManifest.xml file like this and add an <intent-filter> like this:
        android:name = "Activity2">
            <action android:name = "com.test.Activity2" /> <!-- Change com.test with your own package name -->
            <category android:name = "android.intent.category.DEFAULT" />
    And add the code in the file:
    Intent openActivity = new Intent("com.test.Activity2"); //Change com.test with your own package name
    As I said this method is used to receive data from other apps, it can also be used to open your activity from other apps. But for this, the app must be installed on the device.

So these were the three methods you saw how to open another Activities from one Activity. Hope you liked it. If yes, please let me know about it in the comments section below.


Popular Posts