Android Intent Handling Between Activities Example

Total Views : 150
Zoom In Zoom Out Read Later Print

In this guide i will show you how you can use intent to start activity with data and its flags. An intent is an abstract description of an operation to be performed. It can be used to launch an Activity, broadcast Intent to send it to any interested BroadcastReceiver components, and to communicate with a background Service.

So What is an Android Intent?

An Intent provides a facility for performing late run-time binding between the code in applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

One of the most powerful features of Intent is that you can send asynchronous messages to other activities and services. it can be used to send data to other activity or service.

There are two primary forms of intents you will use.

Explicit Intents have specified a component, which provides the exact class to be run, used to start a component in your own app, Often these will not include any other information, simply a way for an application to launch various internal activities it has as the user interacts with the application.

Implicit Intents have not specified a component; instead, they must include enough information for the system to determine which of the available components is best to run for that intent. it allows a component from another app to handle it. 

Using intent to launch activities

To create an intent and launch activity with it, we can write the following code within our From  activity (Current Activity):

Activity Start Intent

Intent intent = new Intent(MainActivity.this, SecondsActivity.class);

// Flags You Can Use
//intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // Bring activity in the current stack to the foreground.
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);         // Start the activity in a new task.
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        // If the activity being started is the current activity (at the top of the back stack)
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);       // All of the other activities on top of it are destroyed

//Send Data to Second Activity
intent.putExtra("data", "Hi");

startActivity(intent);

Running this code snippet has the following states:

1. A new instance of SecondActivity is created
2. The instance is pushed on top of the current task’s stack, of the Second Activity is in.
3. The activity is started and brought to the foreground.

Using Android Intent Flags

When you call startActivity(), you can include a flag in the Intent that declares how the new activity should associate with the current task. as you can see in the previous example of code for activity start. you need to set a flag if you want the desired behavior from intent.

Sending data to Activity

if you want to send some data to other activity you can use putExtra() method of intent to put some content on it before calling startActivity(). it can send object but you need to serialize an object.

Project Code for Activity

There is no code it is only 2 to 5 line of code according to your need.

First Screen

MainActivity.java

package com.prodevsblog;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        init();
    }

    void init() {
        AppCompatButton btnToSecond = findViewById(R.id.btnToSecond);

        btnToSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendToSecond();
            }
        });
    }

    void sendToSecond() {
        Intent intent = new Intent(MainActivity.this, SecondsActivity.class);

        // Flags You Can Use
        //intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // Bring activity in the current stack to the foreground.
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);         // Start the activity in a new task.
        //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        // If the activity being started is the current activity (at the top of the back stack)
        //intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);       // All of the other activities on top of it are destroyed


        //Send Data to Second Activity

        intent.putExtra("data", "Hi"); //

        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".SecondsActivity"
    tools:showIn="@layout/activity_second">

    <android.support.v7.widget.AppCompatButton
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/to_second"
        android:theme="@style/Button.Primary"
        android:layout_centerInParent="true"
        android:id="@+id/btnToSecond"/>

</RelativeLayout>


Second Screen

SecondActivity.java

package com.prodevsblog;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class SecondsActivity extends AppCompatActivity {

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        // Call getIntent() to get data sent form previous activity
        getIntent().getStringExtra("data");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondsActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_second" /> <!-- No Content on second screen for now-->

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

This is all of the code for this task but you can do more to look good when switching activity using Animation.

Adding Animations

put these files in res/anim directory.

fadein.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/accelerate_interpolator"
   android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="2000" />

fadeout.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/accelerate_interpolator"
   android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="2000" />

Using Animation

overridePendingTransition(R.anim.fadein, R.anim.fadeout);

You can download the android intent project from below link.

See More

Latest Photos