How To Implement Intents In Java - Android Snippets

An Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use-cases:

1. To start an activity
2. To start a service
3. To deliver a broadcast

Intent Structure :

The primary pieces of information in an intent are:
1. action : The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.
2. data : The data to operate on, such as a person record in the contacts database, expressed as a Uri.

Intent Resolution

There are two primary forms of intents you will use.

• Explicit Intents
• Implicit Intents

Explicit Intents :

Explicit Intents have specified a component (via setComponent(ComponentName) or setClass(Context, Class)), which provides the exact class to be run. Often these will not include any other information, simply being a way for an application to launch various internal activities it has as the user interacts with the application. Mostly we used explicit intents to start a component in your application. Because you know the class name of the activity or service or broad-cast which we want to start.In Explicit, we can defined intents in 4 ways.

1.Normal Switching
2.Switching with Data
3.Switching with Result Data
4.Switching with Data and Result Data

1.Normal Switching :

In this, we start a Activity without sending or receiving data.

Example

XML Snippet for first layout

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:text="Open Next Activity"
android:onClick="openNext"/>

XML Snippet for next layout

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am Next"
        android:textSize="30sp"
        android:textColor="#123"
        android:textStyle="bold"/>

Java Snippet for first layout

public class MainActivity extends AppCompatActivity
{

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

    public void openNext(View v)
    {
        Intent i = new Intent(this,NextActivity.class);
        startActivity(i);
    }
}

Java Snippet for next layout

public class NextActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next_layout);
    }
}

2.Switching with Data :

In this, we start next Activity by sending required data to destination class.
Example:

XML for first layout

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:hint="Name"
        android:layout_margin="25dp"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send"
        android:onClick="sendData"
        android:layout_below="@+id/name"
        android:layout_alignLeft="@+id/name"
        android:layout_alignStart="@+id/name"
        android:layout_alignRight="@+id/name"
        android:layout_alignEnd="@+id/name" />

XML for next layout

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:textColor="#123"
        android:textStyle="bold"
        android:text="....."/>

Java snippet for first layout

public class MainActivity extends AppCompatActivity
{
    EditText et;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText)findViewById(R.id.name);
    }

    public void sendData(View v)
    {
        String name = et.getText().toString().trim();

        Intent i = new Intent(this,NextActivity.class);
        i.putExtra("k1",name);
        startActivity(i);
    }
}

Java snippet for next layout

public class NextActivity extends Activity
{
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next_layout);

        tv = (TextView)findViewById(R.id.tv1);

        Intent i = getIntent();
        Bundle b = i.getExtras();
        String name = b.getString("k1");

        tv.setText(name);
    }
}

3.Switching with Result Data :

1. With the help of android, "startActivityForResult()" method, we can send data from one activity to another activity and vice-versa.
2. The android "startActivityForResult()" method requires a result from the second Activity(Activity to be invoked).
3. In such case, we need to override the "onActivityResult()" method that is invoked automatically when second activity returns result.

Example:

XML snippet for first layout

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/sendReq"
        android:text="SendRequest"
        android:onClick="sendRequest"/>

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:text="....."
        android:gravity="center"
        android:textSize="25sp"
        android:layout_margin="25dp"
        android:layout_marginTop="25dp"/>

XML snippet for next layout

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:textColor="#dc8d39"
        android:text="Switching With Result Data"/>

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et1"
        android:layout_margin="25dp"
        android:hint="Enter name"/>

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b1"
        android:onClick="sendData"
        android:background="#18c638"
        android:text="Send Data"/>


Java snippet for first layout

public class MainActivity extends Activity
{
    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        tv1=(TextView)findViewById(R.id.tv1);
    }
    public void sendRequest(View v)
    {
        Intent i=new Intent(this,SecondActivity.class);
        startActivityForResult(i,1234);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
     {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==resultCode)
        {

            Bundle b=data.getExtras();

            String name=b.getString("naveen");

            tv1.setText(name);
        }

        else
        {
            Toast.makeText(MainActivity.this,"wrong value",Toast.LENGTH_LONG).show();
        }

    }
}

Java snippet for next layout

public class SecondActivity extends Activity
{
    EditText et1;
    @Override
    protected void onCreate(Bundle savedInstanceState)
     {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout);

        et1=(EditText)findViewById(R.id.et1);

    }
    public  void sendData(View v)
    {
        String name=et1.getText().toString().trim();

        Intent i=new Intent(this,MainActivity.class);

        i.putExtra("naveen",name);

        setResult(1234,i);
        finish();
    }
}

4.Switching with Data and ResultData


Example:

XML snippet for first layout

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:hint="name"
        android:layout_margin="25dp" />
<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/send"
        android:text="Send"
        android:onClick="send"
        android:layout_margin="25dp"/>

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:text=".........."
        android:layout_margin="20dp"/>

XML snippet for next layout

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv2"
        android:text=".............."
        android:layout_margin="20dp"/>


<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name2"
        android:hint="name2"
        android:layout_margin="20dp"/>
<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/send"
        android:text="result"
        android:onClick="result"
        android:layout_margin="20dp"/>

Java snippet for first layout

public class MainActivity extends Activity
{
    TextView tv;
    EditText et;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et=(EditText)findViewById(R.id.name);
        tv=(TextView)findViewById(R.id.tv1);
    }
    public void send(View v)
    {
        String name=et.getText().toString().trim();
        Intent i= new Intent(this,NextActivity.class);
        i.putExtra("K1",name);
        startActivityForResult(i,1234);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==resultCode)
        {
            Bundle b=data.getExtras();
            String name2=b.getString("K2");
            tv.setText(name2);
        }
        else
        {
            Toast.makeText(MainActivity.this,"Incorrect",Toast.LENGTH_LONG).show();
        }
    }
}

Java snippet for next layout

public class NextActivity extends Activity
{

    TextView tv;
    EditText et;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);
        et=(EditText)findViewById(R.id.name2);
        tv=(TextView)findViewById(R.id.tv2);

        Intent I2=getIntent();
        Bundle b=I2.getExtras();
        String name=b.getString("K1");
        tv.setText(name);

    }
    public void result(View v)
    {

        String name2=et.getText().toString().trim();
        Intent i=new Intent();
        i.putExtra("K2",name2);
        setResult(1234,i);
        finish();
    }
}

Implicit Intents :

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.When using implicit intents, given such an arbitrary intent we need to know what to do with it. This is handled by the process of Intent resolution, which maps an Intent to an Activity, BroadcastReceiver, or Service (or sometimes two or more activities/receivers) that can handle it.

The intent resolution mechanism basically revolves around matching an Intent against all of the descriptions in the installed application packages. (Plus, in the case of broadcasts, any BroadcastReceiver objects explicitly registered with registerReceiver(BroadcastReceiver, IntentFilter).) More details on this can be found in the documentation on the IntentFilter class. There are three pieces of information in the Intent that are used for resolution: the action, type, and category. Using this information, a query is done on the PackageManager for a component that can handle the intent. The appropriate component is determined based on the intent information supplied in the
AndroidManifest.xml file as follows:

1. The action, if given, must be listed by the component as one it handles.

2. The type is retrieved from the Intent's data, if not already supplied in the Intent. Like the action, if a type is included in the intent (either explicitly or implicitly in its data), then this must be listed by the component as one it handles.

3. For data that is not a content: URI and where no explicit type is included in the Intent, instead the scheme of the intent data (such as http: or mailto:) is considered. Again like the action, if we are matching a scheme it must be listed by the component as one it can handle.

4. The categories, if supplied, must all be listed by the activity as categories it handles. That is, if you include the categories CATEGORY_LAUNCHER and CATEGORY_ALTERNATIVE, then you will only resolve to components with an intent that lists both of those categories. Activities will very often need to support the CATEGORY_DEFAULT so that they can be found by Context.startActivity().

Example:

XML snippet for Implicit Intents:

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b1"
        android:text="Open Sathya Tech"
        android:onClick="display1"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b2"
        android:text="Open W3schools"
        android:onClick="display2"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b3"
        android:text="Open Android"
        android:onClick="display3"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call Us"
        android:onClick="display4"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open Music"
        android:onClick="display5"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open Maps"
        android:onClick="display6"/>

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open HYD"
        android:onClick="display7"/>

Java snippet for Implicit Intents:

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
  /**snippet to open website**/
    public void display1(View v)
    {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        Uri ref = Uri.parse("http://www.sathyatech.com");
        i.setData(ref);
        startActivity(i);
    }

    public void display2(View v)
    {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse("http://w3schools.com"));
        startActivity(i);
    }

    public void display3(View v)
    {
        Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
        startActivity(i);
    }
  /**snippet to open  Dial pad**/
    public void display4(View v)
    {
        Intent i = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:1234567890"));
        startActivity(i);
    }
  /**snippet to open music**/
    public void display5(View v)
    {
        Intent i = new Intent(Intent.ACTION_PICK);
        i.setData(MediaStore.Audio.Albums.INTERNAL_CONTENT_URI);
        startActivity(i);
    }
  /**snippet to open location with lattitude & langitude**/
    public void display6(View v)
    {
        Uri gmmIntentUri = Uri.parse("google.streetview:cbll=46.414382,10.013988");
        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
        mapIntent.setPackage("com.google.android.apps.maps");
        startActivity(mapIntent);
    }

    public void display7(View v)
    {
        Uri gmmIntentUri = Uri.parse("geo:17.415546,78.475202");
        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
        mapIntent.setPackage("com.google.android.apps.maps");
        startActivity(mapIntent);
    }
}
Comment via Facebook
0 Comment via Google

0 تعليقات:

Post a Comment