Android 简明教程
Android - Intents and Filters
Android Intent
是要执行操作的抽象描述。它可以与 startActivity
一起使用来启动活动,sendBroadcast
将其发送到任何感兴趣的 BroadcastReceiver 组件,以及 bindService(Intent, ServiceConnection, int)
来与后台服务通信。
An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or *bindService(Intent, ServiceConnection, int) * to communicate with a background Service.
例如,让我们假设你有一个活动,需要启动电子邮件客户端并使用安卓设备发送电子邮件。为此目的,你的活动将把 ACTION_SEND 与适当的 Intent
一起发送到 Android 意图解析器。指定的选择器为用户提供了适当的界面,用于选择如何发送电子邮件数据。
For example, let’s assume that you have an Activity that needs to launch an email client and sends an email using your Android device. For this purpose, your Activity would send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your 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..."));
上面的语法调用 startActivity 方法启动电子邮件活动,结果应如下所示 −
Above syntax is calling startActivity method to start an email activity and result should be as shown below −
例如,假设你有一个活动,需要在安卓设备上的网络浏览器中打开 URL。为此目的,你的活动会将 ACTION_WEB_SEARCH 意图发送到安卓意图解析器,以在网络浏览器中打开给定的 URL。意图解析器会解析活动列表,并从中选择最匹配你的意图的那个,在本例中,即网络浏览器活动。然后,意图解析器会将你的网页传递给网络浏览器,并启动网络浏览器活动。
For example, assume that you have an Activity that needs to open URL in a web browser on your Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes your web page to the web browser and starts the Web Browser Activity.
String q = "tutorialspoint";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
以上示例将在安卓搜索引擎中搜索 tutorialspoint
,并在你的活动中给出 tutorialspoint 的结果。
Above example will search as tutorialspoint on android search engine and it gives the result of tutorialspoint in your an activity
向每种类型的组件(活动、服务和广播接收器)递送意图有不同的机制。
There are separate mechanisms for delivering intents to each type of component − activities, services, and broadcast receivers.
Sr.No |
Method & Description |
1 |
Context.startActivity() The Intent object is passed to this method to launch a new activity or get an existing activity to do something new. |
2 |
Context.startService() The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service. |
3 |
Context.sendBroadcast() The Intent object is passed to this method to deliver the message to all interested broadcast receivers. |
Intent Objects
意图对象是一个信息捆绑,由接收该意图的组件以及安卓系统使用的信息使用。
An Intent object is a bundle of information which is used by the component that receives the intent as well as information used by the Android system.
意图对象可以包含以下组件,具体取决于其将要执行或正在传递的内容 −
An Intent object can contain the following components based on what it is communicating or going to perform −
Action
这是意图对象中的必需部分,是一条命名要执行的动作的字符串——或者在广播意图的情况下,就是发生并正在报告的动作。该动作在很大程度上决定了意图对象的其余部分的结构方式。意图类定义了许多与不同意图相对应的动作常量。以下显示 Intent
中可以包含的动作列表:
This is mandatory part of the Intent object and is a string naming the action to be performed — or, in the case of broadcast intents, the action that took place and is being reported. The action largely determines how the rest of the intent object is structured . The Intent class defines a number of action constants corresponding to different intents. Here is a list of Android Intent Standard Actions
Intent 对象中的动作可以通过 setAction() 方法设置,并通过 getAction() 进行读取。
The action in an Intent object can be set by the setAction() method and read by getAction().
Data
将数据规范添加到意图过滤器中。规范可以仅为数据类型(mimeType 属性)、仅为 URI,或者既为数据类型又为 URI。URI 由其每个部分的单独属性指定 −
Adds a data specification to an intent filter. The specification can be just a data type (the mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate attributes for each of its parts −
指定 URL 格式的这些属性是可选的,但也存在相互依赖关系−
These attributes that specify the URL format are optional, but also mutually dependent −
-
If a scheme is not specified for the intent filter, all the other URI attributes are ignored.
-
If a host is not specified for the filter, the port attribute and all the path attributes are ignored.
setData() 方法仅指定数据为 URI,setType() 仅指定为 MIME 类型,而 setDataAndType() 同时将其指定为 URI 和 MIME 类型。getData() 读取 URI,getType() 读取类型。
The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType().
一些动作/数据对的示例如下−
Some examples of action/data pairs are −
Sr.No. |
Action/Data Pair & Description |
1 |
ACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is "1". |
2 |
ACTION_DIAL content://contacts/people/1 Display the phone dialer with the person filled in. |
3 |
ACTION_VIEW tel:123 Display the phone dialer with the given number filled in. |
4 |
ACTION_DIAL tel:123 Display the phone dialer with the given number filled in. |
5 |
ACTION_EDIT content://contacts/people/1 Edit information about the person whose identifier is "1". |
6 |
ACTION_VIEW content://contacts/people/ Display a list of people, which the user can browse through. |
7 |
ACTION_SET_WALLPAPER Show settings for choosing wallpaper |
8 |
ACTION_SYNC It going to be synchronous the data,Constant Value is *android.intent.action.SYNC * |
9 |
ACTION_SYSTEM_TUTORIAL It will start the platform-defined tutorial(Default tutorial or start up tutorial) |
10 |
ACTION_TIMEZONE_CHANGED It intimates when time zone has changed |
11 |
ACTION_UNINSTALL_PACKAGE It is used to run default uninstaller |
Category
类别是 Intent 对象的可选部分,它是一个字符串,包含有关应该处理意图的组件类型的其他信息。addCategory() 方法将类别放置在 Intent 对象中,removeCategory() 删除先前添加的类别,getCategories() 获取当前对象中所有类别的集合。以下是 Android Intent Standard Categories 的列表。
The category is an optional part of Intent object and it’s a string containing additional information about the kind of component that should handle the intent. The addCategory() method places a category in an Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object. Here is a list of Android Intent Standard Categories.
您可以在以下部分查看意图筛选器的详细信息以了解如何使用类别为意图选择合适的活动。
You can check detail on Intent Filters in below section to understand how do we use categories to choose appropriate activity corresponding to an Intent.
Extras
对于应该传送到处理意图的组件的其他信息,它将使用键值对。分别使用 putExtras() 和 getExtras() 方法设置和读取扩展字段。以下是 Android Intent Standard Extra Data 的列表
This will be in key-value pairs for additional information that should be delivered to the component handling the intent. The extras can be set and read using the putExtras() and getExtras() methods respectively. Here is a list of Android Intent Standard Extra Data
Flags
这些标志是 Intent 对象的可选部分,它会指示 Android 系统如何启动 activity,以及在启动之后如何处理 activity 等。
These flags are optional part of Intent object and instruct the Android system how to launch an activity, and how to treat it after it’s launched etc.
Sr.No |
Flags & Description |
1 |
FLAG_ACTIVITY_CLEAR_TASK If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK. |
2 |
FLAG_ACTIVITY_CLEAR_TOP If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent. |
3 |
FLAG_ACTIVITY_NEW_TASK This flag is generally used by activities that want to present a "launcher" style behavior: they give the user a list of separate things that can be done, which otherwise run completely independently of the activity launching them. |
Component Name
此可选字段是一个 android ComponentName 对象,表示 Activity、Service 或 BroadcastReceiver 类。如果已设置,则将 Intent 对象传递到指定类的实例,否则 Android 会使用 Intent 对象中的其他信息来查找合适的目标。
This optional field is an android ComponentName object representing either Activity, Service or BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated class otherwise Android uses other information in the Intent object to locate a suitable target.
组件名称由 setComponent()、setClass() 或 setClassName() 设置,并由 getComponent() 读取。
The component name is set by setComponent(), setClass(), or setClassName() and read by getComponent().
Types of Intents
Android 支持以下两种类型的意图
There are following two types of intents supported by Android
Explicit Intents
将被连接到应用程序内部世界的显式意图,假设你想将一个 activity 连接到另一个 activity,我们可以通过显式意图来执行此引用,以下图片是通过单击按钮将第一个活动连接到第二个活动。
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, below image is connecting first activity to second activity by clicking button.
这些意图通过名称指定目标组件,它们通常用于应用程序内部消息 - 例如 activity 启动从属服务或启动关联 activity。例如 −
These intents designate the target component by its name and they are typically used for application-internal messages - such as an activity starting a subordinate service or launching a 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 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. For example −
Intent read1=new Intent();
read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);
上面的代码将给出如下所示的结果
Above code will give result as shown below
接收意图的目标组件可以使用 getExtras() 方法来获取源组件发送的额外数据。例如 −
The target component which receives the intent can use the getExtras() method to get the extra data 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
以下示例显示了 Android Intent 启动各种 Android 内置应用程序的功能。
Following example shows the functionality of a Android Intent to launch various Android built-in applications.
Step |
Description |
1 |
You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.saira_000.myapplication. |
2 |
Modify src/main/java/MainActivity.java file and add the code to define two listeners corresponding two buttons ie. Start Browser and Start Phone. |
3 |
Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. |
4 |
Run the application to launch Android emulator and verify the result of the changes done in the application. |
以下是修改后的主活动文件 src/com.example.My Application/MainActivity.java 的内容。
Following is the content of the modified main activity file src/com.example.My Application/MainActivity.java.
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);
}
});
}
}
以下是 res/layout/activity_main.xml 文件的内容——
Following will be the content of 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>
以下是 res/values/strings.xml 的内容,用于定义两个新常量——
Following will be 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>
以下是 AndroidManifest.xml 的默认内容−
Following is the default content of AndroidManifest.xml −
<?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>
让我们尝试运行你的 My Application 应用程序。我假设你在进行环境设置时创建了你的 AVD 。若要通过 Android Studio 运行该应用程序,请打开你的一个项目的活动文件,然后从工具栏单击运行图标。Android Studio 将应用程序安装在你的 AVD 上并启动它,如果你的设置和应用程序一切正常,它将显示以下模拟器窗口 −
Let’s try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar.Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
现在单击 Start Browser 按钮,该按钮将启动已配置的浏览器并显示 [role="bare"] [role="bare"]http://www.example.com ,如下所示 −
Now click on Start Browser button, which will start a browser configured and display [role="bare"]http://www.example.com as shown below −
同样地,你可以使用 Start Phone 按钮启动电话界面,该界面将允许你拨打已给定的电话号码。
Similar way you can launch phone interface using Start Phone button, which will allow you to dial already given phone number.
Intent Filters
您已经看到如何使用 Intent 调用另一个 Activity。Android OS 使用过滤器识别一组可使用特定动作、类别和与 Intent 关联的数据方案处理 Intent 的 Activity、服务和广播接收器。您将使用清单文件中的 <intent-filter> 元素列出与任何 Activity、服务或广播接收器关联的动作、类别和数据类型。
You have seen how an Intent has been used to call an another activity. Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent. You will use <intent-filter> element in the manifest file to list down actions, categories and data types associated with any activity, service, or broadcast receiver.
以下是 AndroidManifest.xml 文件一部分的一个示例,用来指定一个 com.example.My Application.CustomActivity Activity,可以通过这两个提到的动作、一个类别和一个数据来调用它 -
Following is an example of a part of AndroidManifest.xml file to specify an activity com.example.My Application.CustomActivity which can be invoked by either of the two mentioned actions, one category, and one 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>
一旦此 Activity 及上面提到的过滤器被定义,其他 Activity 将能够使用 android.intent.action.VIEW 或使用 com.example.My Application.LAUNCH 动作调用此 Activity,前提是它们的类别是 android.intent.category.DEFAULT 。
Once this activity is defined along with above mentioned filters, other activities will be able to invoke this activity using either the android.intent.action.VIEW, or using the com.example.My Application.LAUNCH action provided their category is android.intent.category.DEFAULT.
<data> 元素指定被调用的 Activity 所期望的数据类型,对于上面的示例,我们的自定义 Activity 希望数据以“http://”开头。
The <data> element specifies the data type expected by the activity to be called and for above example our custom activity expects the data to start with the "http://"
可能出现的情况是,一个 Intent 可以通过一个以上 Activity 或服务的过滤器;用户可能被要求激活哪个组件。如果没有找到目标,则会引发异常。
There may be a situation that an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate. An exception is raised if no target can be found.
在调用 Activity 之前,Android 有以下测试 -
There are following test Android checks before invoking an activity −
-
A filter <intent-filter> may list more than one action as shown above but this list cannot be empty; a filter must contain at least one <action> element, otherwise it will block all intents. If more than one actions are mentioned then Android tries to match one of the mentioned actions before invoking the activity.
-
A filter <intent-filter> may list zero, one or more than one categories. if there is no category mentioned then Android always pass this test but if more than one categories are mentioned then for an intent to pass the category test, every category in the Intent object must match a category in the filter.
-
Each <data> element can specify a URI and a data type (MIME media type). There are separate attributes like scheme, host, port, and path for each part of the URI. An Intent object that contains both a URI and a data type passes the data type part of the test only if its type matches a type listed in the filter.
Example
下面的示例是对上面示例的修改。在这里,我们将看到当一个 Intent 调用在 中定义的两个 Activity 时,Android 如何解决冲突,接下来是使用过滤器调用自定义 Activity 的方法,第三个是当 Android 没有为 Intent 定义适当的 Activity 时出现的异常情况。
Following example is a modification of the above example. Here we will see how Android resolves conflict if one intent is invoking two activities defined in , next how to invoke a custom activity using a filter and third one is an exception case if Android does not file appropriate activity defined for an intent.
Step |
Description |
1 |
You will use android studio to create an Android application and name it as My Application under a package com.example.tutorialspoint7.myapplication;. |
2 |
Modify src/Main/Java/MainActivity.java file and add the code to define three listeners corresponding to three buttons defined in layout file. |
3 |
Add a new src/Main/Java/CustomActivity.java file to have one custom activity which will be invoked by different intents. |
4 |
Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. |
5 |
Add one layout XML file res/layout/custom_view.xml to add a simple <TextView> to show the passed data through intent. |
6 |
Modify AndroidManifest.xml to add <intent-filter> to define rules for your intent to invoke custom activity. |
7 |
Run the application to launch Android emulator and verify the result of the changes done in the application. |
以下是修改的主活动文件 src/MainActivity.java 的内容。
Following is the content of the modified main activity file src/MainActivity.java.
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);
}
});
}
}
以下是修改后的主活动文件 src/com.example.My Application/CustomActivity.java 的内容。
Following is the content of the modified main activity file src/com.example.My Application/CustomActivity.java.
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());
}
}
以下是 res/layout/activity_main.xml 文件的内容——
Following will be the content of 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: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>
以下是 res/layout/custom_view.xml 文件的内容 -
Following will be the content of 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>
以下是 res/values/strings.xml 的内容,用于定义两个新常量——
Following will be 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>
以下是 AndroidManifest.xml 的默认内容−
Following is the default content of AndroidManifest.xml −
<?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>
让我们尝试运行您的 My Application 应用程序。我假设您在进行环境设置时已经创建了您的 AVD 。要从 Android Studio 运行应用程序,请打开您的一个项目活动文件,然后单击工具栏中的运行图标。Android Studio 会在您的 AVD 上安装该应用程序并启动它,如果您的设置和应用程序一切都正常的话,它将显示以下模拟器窗口 -
Let’s try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
现在,让我们开始第一个按钮“使用 VIEW 动作启动浏览器”。在这里,我们使用过滤器“android.intent.action.VIEW”定义了我们的自定义 Activity,并且已经由 Android 定义了一个针对 VIEW 动作的默认 Activity,它启动网络浏览器,因此 Android 会显示以下两个选项供您选择要启动的 Activity。
Now let’s start with first button "Start Browser with VIEW Action". Here we have defined our custom activity with a filter "android.intent.action.VIEW", and there is already one default activity against VIEW action defined by Android which is launching web browser, So android displays following two options to select the activity you want to launch.
现在,如果您选择浏览器,则Android将启动网络浏览器并打开example.com网站,但如果您选择IndentDemo选项,那么Android将启动CustomActivity,该活动除了捕获传递的数据并在文本视图中显示以下内容之外什么也不做:
Now if you select Browser, then Android will launch web browser and open example.com website but if you select IndentDemo option then Android will launch CustomActivity which does nothing but just capture passed data and displays in a text view as follows −
现在,使用返回按钮返回并单击“使用启动操作启动浏览器”按钮,此处,Android将应用过滤器以选择定义活动,它只会启动您的自定义活动。
Now go back using back button and click on "Start Browser with LAUNCH Action" button, here Android applies filter to choose define activity and it simply launch your custom activity
再次,使用返回按钮返回并单击“异常条件”按钮,此处,Android尝试为给定的意图查找一个有效的过滤器,但它找不到有效的活动定义,因为这次我们使用了数据作为 https 而不是 http ,尽管我们给出了正确的操作,因此,Android引发异常并显示以下屏幕:
Again, go back using back button and click on "Exception Condition" button, here Android tries to find out a valid filter for the given intent but it does not find a valid activity defined because this time we have used data as https instead of http though we are giving a correct action, so Android raises an exception and shows following screen −