Sunday 8 April 2018

Intent using Kotlin in Android



What is Intent?
An Intent is an object that provides runtime binding between separate components, such as two activities. The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks.

Types of Intents:

1). Explicit Intents
Explicit intent going to be connected internal world of application,suppose if you wants to connect one activity to another activity, we can do this quote by explicit intent.
2). Implicit Intents
These intents do not name a target and the field for the component name is left blank. Implicit intents are often used to activate components in other applications.

Description: In this Intent Example we Go through both type of Intent.
1).Explicit Intent : We Open Different activity By Click on button which is on MainActivity.
If user Click on Explicit Button than we pass data from one Activity to another Activtiy.
If user Click on Implicit Button than we do not pass data only open new activity.
2).Implicit Intent : we open camera or map based on button click by user.
   To open Specific location on map we have to pass Latitude   and Longitude to map.We also need uses permission in Manifest file.

1. Creating New Project in Kotlin.
  • Open Android Studio.
  • Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
  • Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
  • Then, select Empty Activity => click next => click finish.
2.For this example we need 3 XML file.(res->layout->our Files)
  1.  activity_main
  2.  implicit_intent_activity
  3.  explicit_intent_activity

main_activity.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"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/implicit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="166dp"
        android:text="Implicit Intent" />

    <Button
        android:id="@+id/explicit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="202dp"
        android:text="Explicit Intent" />
</RelativeLayout>


implicit_intent_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="133dp"
        android:text="Open Camera" />

    <Button
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Open Map" />
</RelativeLayout>


explicit_intent_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/number"
        android:padding="5dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


</LinearLayout>

3.Here we have 3 kotlin Class
  1. MainActivity
  2. ImplicitIntentActivity
  3. ExplicitIntentActivity

MainActivity.kt

package com.dharmendra.intentexample

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button

class MainActivity : AppCompatActivity(), View.OnClickListener {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Find View By Id for Both Button

        val implicitIntent = findViewById(R.id.implicit) as Button
        val explicitIntent = findViewById(R.id.explicit) as Button

        /* Set On Click Listerner for both button Here we have implement OnClickListerner
            On Click is Handle in onClick Method.
        */

        implicitIntent.setOnClickListener(this)
        explicitIntent.setOnClickListener(this)
    }

    override fun onClick(v: View?) {

        //Get selected Button Id
        val selectedButtonId = v!!.id

        //Initialize Intent
        val intent: Intent

        when (selectedButtonId) {

            R.id.implicit -> {

                //This is Explicit Intent Without Passing Data
                intent = Intent(this@MainActivity, ImplicitIntentActivity::class.java)

                //StartActivity Open our Intent Activity.
                startActivity(intent)
            }

            R.id.explicit -> {

                //This Is Explicit Intent With Passing Data to Another Activity.

                intent = Intent(this@MainActivity, ExplicitIntentActivity::class.java)

                //Pass String Value
                intent.putExtra("name", "Dharmendra")

                //Pass Integer value
                intent.putExtra("contact", 1234567890)


                //StartActivity Open our Intent Activity.
                startActivity(intent)
            }
        }

    }
}


ImplicitIntentActivity.kt

package com.dharmendra.intentexample


import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.Toast


class ImplicitIntentActivity : AppCompatActivity(), View.OnClickListener {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.implicit_intent_activity)

        //Find View By Id for both Button

        val camera = findViewById<Button>(R.id.camera)
        val map = findViewById<Button>(R.id.map)

        //Set on Click for both handle in onClick method

        camera.setOnClickListener(this)
        map.setOnClickListener(this)

    }

    override fun onClick(v: View?) {

        //Get selected Button Id
        val selectedButtonId = v!!.id

        //Initialize Intent
        val intent: Intent

        when (selectedButtonId) {
            R.id.map -> {

                //If Google Map in Not install Or any other Error occurs So we use try-catch block

                try {
                    intent = Intent(Intent.ACTION_VIEW)

                    //We need to pass Latitude And Longitude to open Location On Map
                    intent.data = Uri.parse("geo:20.379146,72.913831")
                    startActivity(intent)
                } catch (error: Exception) {

                    Toast.makeText(this, error.message, Toast.LENGTH_LONG).show()

                }

            }
            R.id.camera -> {

                //If Camera in Not install Or any other Error occurs So we use try-catch block
                try {
                    intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                    startActivity(intent)
                } catch (error: Exception) {

                    Toast.makeText(this, error.message, Toast.LENGTH_LONG).show()

                }


            }
        }
    }
}


ExplicitIntentActivity.kt

package com.dharmendra.intentexample

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.TextView

class ExplicitIntentActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.explicit_intent_activity)

        //Find View By Id for Our textView

        val name = findViewById<TextView>(R.id.name)
        val number = findViewById<TextView>(R.id.number)

        //Create Object to get Intent Data
        val i = intent.extras

        //get name Pass from MainActivity
        val myname = i.getString("name")


        //get Contact Number Pass from MainActivity
        val myContact = i.getInt("contact")

        /* You can set Text in TextView in both way as Shown Below*/
        name.setText(myname)

        number.text = myContact.toString()


    }

}

4.we have to take Internet Permission and also register Our classes in AndroidManifest file.


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dharmendra.intentexample">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ExplicitIntentActivity" />
        <activity android:name=".ImplicitIntentActivity" />
    </application>

</manifest>

Output:




No comments:

Post a Comment