Learn intentions and filters in Android

intent is an abstract explanation of what needs to be done. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any BroadcastReceiver, and startService (Intent) or (bindService (Intent ServiceConnection, int) to communicate with background services).

The Intent goal is a passive data structure that provides an abstract description of what needs to be done.

For example, suppose you have an activity that requires you to set up an email client and send an email using your Android device. To do this, your activity can send ACTION_SEND with the appropriate selector to Android Intent Resolver. The selector provides the user with the appropriate interface to choose how to send their email data.

Intent email = new Intent (Intent.ACTION_SEND, Uri.parse (“mailto:”));

email.putExtra (Intent.EXTRA_EMAIL, recipients);

email.putExtra (Intent.EXTRA_SUBJECT, subject.getText (). toString ());

email.putExtra (Intent.EXTRA_TEXT, body.getText (). toString ());

startActivity (Intent.createChooser (email, “Choose an email client from…”));

The above code calls the startActivity method to start the e-mail, the result of which should be as follows –

C: \ Users \ Mr \ Desktop \ send_email.jpg

For example, suppose you have an activity that should open a URL in a web browser on your Android device. To do this, your activity sends the ACTION_WEB_SEARCH Intent to Android Intent Resolver to open the given URL in a web browser. Intent Resolver analyzes the list of activities and selects the one that best suits your Intent, Web Browser Activity. Intent Resolver then moves your webpage to a web browser and launches Web Browser Activity.

String q = “tutorialspoint”;

Intent intent = new Intent (Intent.ACTION_WEB_SEARCH);

intent.putExtra (SearchManager.QUERY, q);

startActivity (intent);

Above, the tutorialspoint is searched in the Android search engine and provides the search result in the activity.

There are separate mechanisms for delivering intent to each component – activities, services, and message recipients.

Number Methods and description
1 () Context.startActivityThe Intent object is passed to this method to launch a new activity or an existing activity to do something new.
۲ () Context.startServiceThe Intent object is passed to this method to start a service or provide new instructions to an ongoing service.
3 () Context.sendBroadcastThe Intent object is passed to this method to send the message to all recipients of the message.

Intent objects

An Intent object is a collection of information used by a component that receives intent as well as information received by an Android system. An intent object can contain the following components based on what is being communicated or executed –

Action

The mandatory part of the object is the Intent, the string that performs the action – or in the case of all-broadcast intentions, the action that occurs and is reported. action largely determines what the remaining structure of the intent object is. The Intent class defines a number of action constraints that relate to different intentions. Here is a list of standard Intent Android actions.

action on an Intent object can be set using the setAction () method and read by getAction ().

Data

Add the data specification to the intent filter. The specification can be just a data type (mimeType attribute), just a URI, or both a data type and a URI. URI is specified for each of its parts with separate features –

These attributes that specify the URL format are optional but interdependent –

  • If the schema is not specified for the intent filter, all other URI properties will be ignored.
  • If the host is not specified for the filter, the port attribute and all path attributes are ignored.

The setData () method specifies the data as the URI only, the setType () specifies it as the MIME type only, and the setDataAndType () specifies both the URI and the MIME type. The URI is read by getData () and its type by getType ().

Some examples of action / data pairs are as follows:

Number Pair action / data and description
1 ACTION_VIEW content: // contacts / people / 1Display information about a person whose ID is “1”.
۲ ACTION_DIAL content: // contacts / people / 1The dialer shows the phone with the numbers of the people in it.
3 ACTION_VIEW tel: 123Displays the phone dialer with the desired phone number in it.
4 ACTION_DIAL tel: 123Displays the phone dialer with the desired number in it 1.
5 ACTION_EDIT content: // contacts / people / 1Edits information about a person whose ID is “1”.
6 ACTION_VIEW content: // contacts / people /Displays a list of people that the user can browse.
7 ACTION_SET_WALLPAPERShow wallpaper selection settings
8 ACTION_SYNCSynchronizes data, has a fixed value of android.intent.action.SYNC.
9 ACTION_SYSTEM_TUTORIALStarts the training platform that runs on the first setup of the device (default training or setup training).
10 ACTION_TIMEZONE_CHANGEDReports time zone change.
۱۱ ACTION_UNINSTALL_PACKAGERuns the program uninstaller.

Category

It is an optional part of the Intent object and is a string that contains additional information about the type of component that should control the intent. The addCategorie () method puts a category in an Intent object, removeCategorie () removes the previously added category, and getCategories () gets a collection of all the categories in the object.

You can check out the details of Intent filters below to find out how we use categories to select the right activity for Intent.

Extras

This section contains pairs of key values ​​for additional information about intentes and is delivered to the component that interacts with the intent. Additional information can be set and read using the putExtras () and getExtras () methods, respectively.

Flags

These flags are an optional part of the Intent object and teach the Android system how to launch an activity and how to operate after launching and so on.

Number Flags and descriptions
1 FLAG_ACTIVITY_CLEAR_TASKIf an Intent is sent to Context.startActivity (), this flag will release existing activities that were processing the activity before it started. This only applies to FLAG_ACTIVITY_NEW_TASK.
۲ FLAG_ACTIVITY_CLEAR_TOPIf you use this flag, when you start an activity, if a system unit is processing this type of activity, instead of launching a new instance, all existing activities will be closed and intent as an intent The new is left to them.
3 FLAG_ACTIVITY_NEW_TASKThis flag is usually used by activities that want to be launched. They give the user a list of things that can be done, which would otherwise be completely independent of the activity they are performing.

Component Name

The optional part is a ComponentName object that represents the class or activity, service, or BroadcastReceiver. If configured, the Intent object will be delivered to an instance of the specified class, otherwise Android will use other information in the Intent object to find a suitable object.

The component name is set by setComponent () (), setClass or setClassName () and read by getComponent ().

Types of intentions

There are two types of intent that are supported by Android

C: \ Users \ Mr \ Desktop \ intent.jpg

Explicit Intents

They are used to communicate between the internal parts of a software. Suppose you want to connect one activity to another, this connection can be made with an Explicit Intents. The image below shows the relationship between the first activity and the second activity after clicking the button.

C: \ Users \ Mr \ Desktop \ intent1.jpg

These intentes specify the target component by its name and are commonly used to communicate between internal components of the software – such as an activity that starts to create a subservice or sister activity. for example –

// Explicit Intent by specifying its class name

Intent i = new Intent (FirstActivity.this, SecondActivity.class);

// Starts TargetActivity

startActivity (i);

Implicit Intents

These intentions do not specify the destination, and the component name field is empty. Implicit intent is often used to enable components in other applications. for example –

Intent read1 = new Intent ();

read1.setAction (android.content.Intent.ACTION_VIEW);

read1.setData (ContactsContract.Contacts.CONTENT_URI);

startActivity (read1);

The above code shows the following result.

C: \ Users \ Mr \ Desktop \ intent4.jpg

The destination component that receives the intent can use the getExtras () method to receive additional information sent by the source component. for example –

// Get bundle object at appropriate place in your code

Bundle extras = getIntent (). GetExtras ();

// Extract data using passed keys

String value1 = extras.getString (“Key1”);

String value2 = extras.getString (“Key2”);

Example

The following example shows the performance of Android intent in launching various internal Android applications.

Number Description
1 You can use Android studio IDE to create an Android application and create it as My Application under the package com.example.saira_000.myapplication.
۲ Modify the src / main / java / MainActivity.java file and add code to define two corresponding listeners with two buttons. That is, Start Browser and Start Phone.
3 Modify the res / layout / activity_main.xml / paging XML file to add three buttons in linear order.
4 Run the program to launch the Android emulator and display the result of the changes made in the program.

Below is the contents of the modified src / com.example.My Application / MainActivity.java main activity file.

package com.example.saira_000.myapplication;

import android.content.Intent;

import android.net.Uri;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button b1, b2;

@Override

protected void onCreate (Bundle savedInstanceState) {

super.onCreate (savedInstanceState);

setContentView (R.layout.activity_main);

b1 = (Button) findViewById (R.id.button);

b1.setOnClickListener (new View.OnClickListener () {

@Override

public void onClick (View v) {

Intent i = new Intent (android.content.Intent.ACTION_VIEW,

Uri.parse (“http://www.example.com”));

startActivity (i);

}

});

b2 = (Button) findViewById (R.id.button2);

b2.setOnClickListener (new View.OnClickListener () {

@Override

public void onClick (View v) {

Intent i = new Intent (android.content.Intent.ACTION_VIEW,

Uri.parse (“tel: 9510300000”));

startActivity (i);

}

});

}

}

.

The following is the contents of the res / layout / activity_main.xml file:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<RelativeLayout xmlns: android = ”http://schemas.android.com/apk/res/android”

xmlns: tools = ”http://schemas.android.com/tools”

android: layout_width = ”match_parent”

android: layout_height = ”match_parent”

android: paddingLeft = ”@ dimen / activity_horizontal_margin”

android: paddingRight = ”@ dimen / activity_horizontal_margin”

android: paddingTop = ”@ dimen / activity_vertical_margin”

android: paddingBottom = ”@ dimen / activity_vertical_margin”

tools: context = ”. MainActivity”>

<TextView

android: id = ”@ + id / textView1 ″

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Intent Example”

android: layout_alignParentTop = ”true”

android: layout_centerHorizontal = ”true”

android: textSize = ”30dp” />

<TextView

android: id = ”@ + id / textView2 ″

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Tutorials point”

android: textColor = ”# ff87ff09 ″

android: textSize = ”30dp”

android: layout_below = ”@ + id / textView1 ″

android: layout_centerHorizontal = ”true” />

<ImageButton

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: id = ”@ + id / imageButton”

android: src = ”@ drawable / abc”

android: layout_below = ”@ + id / textView2 ″

android: layout_centerHorizontal = ”true” />

<EditText

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: id = ”@ + id / editText”

android: layout_below = ”@ + id / imageButton”

android: layout_alignRight = ”@ + id / imageButton”

android: layout_alignEnd = ”@ + id / imageButton” />

<Button

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Start Browser”

android: id = ”@ + id / button”

android: layout_alignTop = ”@ + id / editText”

android: layout_alignRight = ”@ + id / textView1 ″

android: layout_alignEnd = ”@ + id / textView1 ″

android: layout_alignLeft = ”@ + id / imageButton”

android: layout_alignStart = ”@ + id / imageButton” />

<Button

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Start Phone”

android: id = ”@ + id / button2 ″

android: layout_below = ”@ + id / button”

android: layout_alignLeft = ”@ + id / button”

android: layout_alignStart = ”@ + id / button”

android: layout_alignRight = ”@ + id / textView2 ″

android: layout_alignEnd = ”@ + id / textView2 ″ />

</RelativeLayout>

The following is the content of res / values ​​/ strings.xml to define two new constants:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<resources>

<string name = ”app_name”> My Applicaiton </string>

</resources>

The following is the default AndroidManifest.xml content:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<manifest xmlns: android = ”http://schemas.android.com/apk/res/android”

package = ”com.example.saira_000.myapplication”>

<application

android: allowBackup = ”true”

android: icon = ”@ mipmap / ic_launcher”

android: label = ”@ string / app_name”

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>

</application>

</manifest>

Launch My Application. Let’s say you created your AVD while making environmental settings. To run the program in Android Studio, open one of your project activity files and click on Run Eclipse Run Icon from the toolbar. Android Studio installs the program on your AVD and launches it. If the thing is correct, it shows the following page –

C: \ Users \ Mr \ Desktop \ intent5.png

Now click on the Start Browser button, which configures a browser and displays http://www.example.com as shown below –

C: \ Users \ Mr \ Desktop \ android_intent_browser.png

In the same way, you can set up the phone interface using the Start Phone button, which allows you to dial a phone number already given to the system.

Intent Filters

See how Intent is used to call other activities. The Android operating system uses filters to specify a set of activities, services, and message recipients that interact with a set of Intent-related actions, categories, and data schema. You can use the <intent-filter> tag in the manifest file to list Intent-related actions, categories, and data schema, services, and messengers.

Below is an example of the AndroidManifest.xml file to specify the com.example.My Application.CustomActivity activity that can be accessed using both methods and defines a category and a data –

<activity android: name = ”. CustomActivity”

android: label = ”@ string / app_name”>

<intent-filter>

<action android: name = ”android.intent.action.VIEW” />

<action android: name = ”com.example.My Application.LAUNCH” />

<category android: name = ”android.intent.category.DEFAULT” />

<data android: scheme = ”http” />

</intent-filter>

</activity>

After defining this activity along with the filters mentioned above, other activities will be able to call this activity using android.intent.action.VIEW or using com.example.My Application.LAUNCH. Provided their classification is android.intent.categor.DEFAULT.

The <data> tag specifies the type of data that is expected to be called by the activity, and in the example above our custom activity expects the data to start with “//: http”.

There may be situations where an intent can be given to multiple filters or more than one activity or service. The user may be asked which component to enable. If no destination is found, an exception is made.

Before calling an activity, the following Android checks are done –

  • A <intent-filter> filter can list more than one action, as shown above, but this list cannot be empty. A filter must have at least one <action> element, otherwise it blocks all intentions. If more than one action is mentioned, Android tries to match one of the mentioned actions before calling the activity.
  • A <intent-filter> filter may have zero, one, or more categories. If no category is mentioned, Android always passes this test, but if more than one category is mentioned, in order for an intent to pass this test, all categories in the Intent object must match the category in the filter. To match.
  • Each <data> tag can specify a URI and a data type (MIME media type). There are separate properties for each part of the URI such as schema, host, port and path. An Intent object that contains a URI and a data type only passes the data type test if its type matches the type specified in the filter.

Example

The following example modifies the example above. Here we will see how Android intends to resolve the inconsistency with the two activities defined in intent, and then how to call a custom activity with a filter and finally go to the exception, when no appropriate activity Not defined for intent.

the level Description
1 You can use android studio to create an Android application and create it under the name My Application and under the package com.example.tutorialspoint7.myapplication.
۲ Modify the src / Main / Java / MainActivity.java file and add the code for the three listeners to the three defined buttons in the layout file.
3 Add a new src / Main / Java / CustomActivity.java file to have a custom activity called with different intentions.
4 Modify the res / layout / activ_main.xml paging XML file to add three buttons in linear order.
5 Add res / layout / custom_view.xml paging XML file to add a <TextView> tag to display data sent via intent.
6 Modify AndroidManifest.xml to add <intent-filter> to define rules for your intent to cite custom activities.
7 Run the program to launch the Android emulator and display the result of changes in the program.

Below is the content of the src / MainActivity.java main activity file.

package com.example.tutorialspoint7.myapplication;

import android.content.Intent;

import android.net.Uri;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button b1, b2, b3;

@Override

protected void onCreate (Bundle savedInstanceState) {

super.onCreate (savedInstanceState);

setContentView (R.layout.activity_main);

b1 = (Button) findViewById (R.id.button);

b1.setOnClickListener (new View.OnClickListener () {

@Override

public void onClick (View v) {

Intent i = new Intent (android.content.Intent.ACTION_VIEW,

Uri.parse (“http://www.example.com”));

startActivity (i);

}

});

b2 = (Button) findViewById (R.id.button2);

b2.setOnClickListener (new View.OnClickListener () {

@Override

public void onClick (View v) {

Intent i = new Intent (“com.example.

tutorialspoint7.myapplication.

LAUNCH ”, Uri.parse (“ http://www.example.com ”));

startActivity (i);

}

});

b3 = (Button) findViewById (R.id.button3);

b3.setOnClickListener (new View.OnClickListener () {

@Override

public void onClick (View v) {

Intent i = new Intent (“com.example.

My Application.LAUNCH ”,

Uri.parse (“https://www.example.com”));

startActivity (i);

}

});

}

}

Below is the contents of the main src / com.example.My Application / CustomActivity.java activity file.

package com.example.tutorialspoint7.myapplication;

import android.app.Activity;

import android.net.Uri;

import android.os.Bundle;

import android.widget.TextView;

/ **

* Created by TutorialsPoint7 on 8/23/2016.

* /

public class CustomActivity extends Activity {

@Override

public void onCreate (Bundle savedInstanceState) {

super.onCreate (savedInstanceState);

setContentView (R.layout.custom_view);

TextView label = (TextView) findViewById (R.id.show_data);

Uri url = getIntent (). GetData ();

label.setText (url.toString ());

}

}

The following is the contents of the res / layout / activ_main.xml file:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<RelativeLayout

xmlns: android = ”http://schemas.android.com/apk/res/android”

xmlns: tools = ”http://schemas.android.com/tools”

android: layout_width = ”match_parent”

android: layout_height = ”match_parent”

android: paddingBottom = ”@ dimen / activity_vertical_margin”

android: paddingLeft = ”@ dimen / activity_horizontal_margin”

android: paddingRight = ”@ dimen / activity_horizontal_margin”

android: paddingTop = ”@ dimen / activity_vertical_margin”

tools: context = ”com.example.tutorialspoint7.myapplication.MainActivity”>

<TextView

android: id = ”@ + id / textView1 ″

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Intent Example”

android: layout_alignParentTop = ”true”

android: layout_centerHorizontal = ”true”

android: textSize = ”30dp” />

<TextView

android: id = ”@ + id / textView2 ″

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Tutorials point”

android: textColor = ”# ff87ff09 ″

android: textSize = ”30dp”

android: layout_below = ”@ + id / textView1 ″

android: layout_centerHorizontal = ”true” />

<ImageButton

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: id = ”@ + id / imageButton”

android: src = ”@ drawable / abc”

android: layout_below = ”@ + id / textView2 ″

android: layout_centerHorizontal = ”true” />

<EditText

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: id = ”@ + id / editText”

android: layout_below = ”@ + id / imageButton”

android: layout_alignRight = ”@ + id / imageButton”

android: layout_alignEnd = ”@ + id / imageButton” />

<Button

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Start Browser”

android: id = ”@ + id / button”

android: layout_alignTop = ”@ + id / editText”

android: layout_alignLeft = ”@ + id / imageButton”

android: layout_alignStart = ”@ + id / imageButton”

android: layout_alignEnd = ”@ + id / imageButton” />

<Button

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Start browsing with launch action”

android: id = ”@ + id / button2 ″

android: layout_below = ”@ + id / button”

android: layout_alignLeft = ”@ + id / button”

android: layout_alignStart = ”@ + id / button”

android: layout_alignEnd = ”@ + id / button” />

<Button

android: layout_width = ”wrap_content”

android: layout_height = ”wrap_content”

android: text = ”Exceptional condition”

android: id = ”@ + id / button3 ″

android: layout_below = ”@ + id / button2 ″

android: layout_alignLeft = ”@ + id / button2 ″

android: layout_alignStart = ”@ + id / button2 ″

android: layout_toStartOf = ”@ + id / editText”

android: layout_alignParentEnd = ”true” />

</RelativeLayout>

The following is the contents of the res / layout / custom_view.xml file:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<LinearLayout xmlns: android = ”http://schemas.android.com/apk/res/android”

android: orientation = ”vertical” android: layout_width = ”match_parent”

android: layout_height = ”match_parent”>

<TextView android: id = ”@ + id / show_data”

android: layout_width = ”fill_parent”

android: layout_height = ”400dp” />

</LinearLayout>

The following is the content of res / values ​​/ strings.xml to define two new constants:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<resources>

<string name = ”app_name”> My Application </string>

</resources>

The following is the default AndroidManifest.xml content:

<? xml version = ”1.0 ″ encoding =” utf-8 ″?>

<manifest xmlns: android = ”http://schemas.android.com/apk/res/android”

package = ”com.example.tutorialspoint7.myapplication”>

<application

android: allowBackup = “true”

android: icon = “@ mipmap / ic_launcher”

android: label = “@ string / app_name”

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 = ”com.example.tutorialspoint7.myapplication.CustomActivity”>

<intent-filter>

<action android: name = “android.intent.action.VIEW” />

<action android: name = “com.example.tutorialspoint7.myapplication.LAUNCH” />

<category android: name = “android.intent.category.DEFAULT” />

<data android: scheme = “http” />

</intent-filter>

</activity>

</application>

</manifest>

Launch your My Application. Let’s say you created your AVD while making environmental settings. To run the program in Android Studio, open one of your project activity files and from the toolbar, click Run Eclipse Run Icon. Android Studio installs the program on your AVD and launches it, and if everything is correct, the following Emulator window is displayed –

C: \ Users \ Mr \ Desktop \ intent6.png

Now let’s start with the first “Start Browser with VIEW Action” button. Here we define our custom activity with the filter “android.intent.action.VIEW”, and there is now a default activity against the VIEW function defined by Android that is launching the web browser, so Android Displays the following two options for selecting your activity.

C: \ Users \ Mr \ Desktop \ intent7.png

Now if you select Browser, Android launches the web browser and opens example.com, but if you select IndentDemo, Android launches CustomActivity, which does nothing but capture the imported data and display it. Does not dominate the text –

C: \ Users \ Mr \ Desktop \ intent8.png

Now use the back button and click on the “Start Browser with LAUNCH Action” button, here Android applies a filter to select the activity definition and easily launches your custom activity.

Go back again using the back button and click on the “Exception Condition” button, here Android tries to find a valid filter for a specific intent but does not find a valid defined activity because this time we We used https instead of http. So Android announces an exception and displays the following window –

C: \ Users \ Mr \ Desktop \ intent9.png

Leave a Reply

Your email address will not be published. Required fields are marked *