Android - Intents/Filters

Android - Intents/Filters 首页 / Android入门教程 / Android - Intents/Filters

Android Intent 是要执行的操作的抽象描述。它可以与 startActivity 一起启动Activity,将 broadcastIntent 发送给任何BroadcastReceiver组件,并与 startService(Intent)或 bindService(Intent,ServiceConnection,int)与后台服务进行通信。

假设您有一个Activity,该Activity需要启动电子邮件客户端并使用Android设备发送电子邮件,为此,您的"Activity"会将ACTION_SEND和相应的 chooser 发送到Android Intent解析器。指定的selector为用户提供适当的界面,以选择如何发送您的电子邮件数据。

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方法来启动电子邮件Activity,输出应如下所示-

Send Email

假设您有一个Activity,需要在Android设备上的网络浏览器中打开URL。为此,您的"Activity"会将ACTION_WEB_SEARCH Intent发送到Android Intent Resolver,以在网络浏览器中打开给定的URL。 Intent解析器将解析一系列Activity,然后选择最适合您的Intent的Activity。然后,Intent Resolver将您的网页传递到Web浏览器并启动Web浏览器Activity。

String q = "learnfk";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);

上面的示例将在android搜索引擎上以 learnfk 搜索,并在您的Activity中提供了learnfk的输出

Sr.NoMethod & 描述
1

Context.startActivity()

Intent对象将传递给此方法以启动新Activity或获取现有Activity以执行新操作。

2

Context.startService()

Intent对象将传递给此方法以启动服务或将新指令传递给正在进行的服务。

3

Context.sendBroadcast()

Intent对象将传递给此方法,以将消息传递给所有感兴趣的广播接收者。

Intent对象

Intent意图是一种信息,供接收该Intent的组件使用以及Android系统使用的信息,一个Intent对象可以根据其正在通信或将要执行的内容包含以下组件-

Action

这是意图对象的必需部分,并且是一个字符串,用于命名要执行的动作-或在广播意图的情况下,是已发生并要报告的动作。动作很大程度上决定了其余意图对象的结构。意图类定义了许多与不同意图对应的动作常量。这是 Android Intent Standard Actions 

可以通过setAction()方法设置意图对象中的动作,并通过getAction()读取该动作。

Data

将数据规范添加到意图过滤器。规范可以只是数据类型(mimeType属性),只是URI,或者既是数据类型又是URI, URI由其每个部分的单独属性指定-

这些指定URL格式的属性是可选的,但也相互依赖-

  • 如果未为意图过滤器指定方案,则会忽略所有其他URI属性。
  • 如果未为过滤器指定主机,则将忽略端口属性和所有路径属性。

action/data对的一些示例是-

Sr.No.行动/Data Pair & 描述
1

ACTION_VIEW content://contacts/people/1

显示有关其标识符为" 1"的人的信息。

2

ACTION_DIAL content://contacts/people/1

显示电话拨号器,并填写人员。

3

ACTION_VIEW tel:123

显示填写了给定number的电话拨号器。

4

ACTION_DIAL tel:123

显示填写了给定number的电话拨号器。

5

ACTION_EDIT content://contacts/people/1

编辑有关其标识符为" 1"的人的信息。

6

ACTION_VIEW content://contacts/people/

显示人员列表,用户可以浏览。

7

ACTION_SET_WALLPAPER

显示选择墙纸的设置

8

ACTION_SYNC

它将同步数据,常量值为 android.intent.action.SYNC

无涯教程网

9

ACTION_SYSTEM_TUTORIAL

它将启动平台定义的教程(默认教程或启动教程)

10

ACTION_TIMEZONE_CHANGED

时区变化时提示

11

ACTION_UNINSTALL_PACKAGE

它用于运行默认卸载程序

Category

类别是意图对象的可选部分,它是一个字符串,其中包含有关应处理该意图的组件类型的其他信息。addCategory()方法将类别放置在意图对象中,removeCategory()删除先前添加的类别,并且getCategories()获取对象中当前所有类别的集合。这是Android Intent Standard Categories.

这些标志是意图对象的可选部分,用于指示Android系统如何启动Activity以及启动Activity后如何对其进行处理等。

Extras

这将在键值对中提供附加信息,这些附加信息应传递给处理该intents(意图)的组件。可以分别使用putExtras()和getExtras()方法设置和读取附加函数。这是Android Intent Standard Extra Data

Flags

这些标志是Intent对象的可选部分,用于指示Android系统如何启动Activity以及启动Activity后如何对其进行处理等。

Sr.NoFlags & 描述
1

FLAG_ACTIVITY_CLEAR_TASK

如果在传递给Context.startActivity()的Intent中进行设置,则此标志将导致在Activity开始之前清除与该Activity关联的所有现有任务。

2

FLAG_ACTIVITY_CLEAR_TOP

如果已设置,并且正在启动的Activity已经在当前任务中运行,那么与其启动该Activity的新,不如关闭该Activity之上的所有其他Activity,并将此意图传递给(现在顶部)将旧Activity作为新的意图

3

FLAG_ACTIVITY_NEW_TASK

希望呈现"启动器"样式行为的Activity通常使用此标志:它们为用户提供了可以完成的单独操作的列表,否则这些操作完全独立于启动它们的Activity。

Component Name

此可选字段是android ComponentName 对象,代表Activity,Service或BroadcastReceiver类。如果已设置,则将Intent对象传递到指定类的,否则Android使用Intent对象中的其他信息来定位合适的目标。

组件名称由setComponent(),setClass()或setClassName()设置,并由getComponent()读取。

Intents类型

Android支持以下两种类型的意图

Intent

Explicit Intents

Explicit intents(显示意图)将被连接到应用程序的内部,假设您想将一个Activity连接到另一个Activity,无涯教程可以通过显式意图进行引用,下图是通过单击按钮将第一个Activity连接到第二个Activity。

明确intents(意图)(意图)
//通过指定其类名来显式意图
Intent i = new Intent(FirstActivity.this, SecondActivity.class);

//启动 TargetActivity
startActivity(i);

Implicit Intents

Implicit Intents(隐式意图)这些意图不会命名目标,并且组件名称的字段保留为空。如-

Intent read1=new Intent();
read1.setActive(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);

上面的代码将给出如下所示的输出

Intent

接收到意图的目标组件可以使用getExtras()方法获取源组件发送的数据。例如-

//在代码中的适当位置获取捆绑对象
Bundle extras = getIntent().getExtras();

//使用传递的键提取数据
String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");

以下示例显示了用于启动各种Android内置应用程序的Android Intent意图函数,以下是修改后的主要Activity文件 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 文件的内容-

<?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="Learnfk 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 的内容,以定义两个新的常量-

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">My Applicaiton</string>
</resources>

以下是 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>

在模拟器中显示内容如下

Android Intent Screen

现在单击启动浏览器按钮,这将跳转到 http://www.example.com 链接,如下所示-

Android Intent Browser

您可以使用启动电话会弹出拨打已经给定电话的界面。

Intents过滤器

您已经了解了如何使用Intent调用另一个Activity。Android OS使用过滤器来确定是哪个Activity执行,您将在文件中使用<intent-filter>元素列出与任何Activity,Service或Broadcast动作,Category和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>android.intent.action.VIEW 或 com.example.My应用程序来调用此Activity.LAUNCH 操作,前提是其类别为 android.intent.category.DEFAULT 。

<data>    -  元素指定Activity将要调用的数据类型,例如,在上面的示例中,无涯教程的自定义Activity期望数据以“ http://”开头

以下是修改后的主要Activity文件 src/MainActivity.java 的内容。

package com.example.learnfk7.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.
               learnfk7.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);
         }
      });
   }
}

以下是修改后的主要Activity文件 src/com.example.My Application/CustomActivity.java 的内容。

package com.example.learnfk7.myapplication;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

/**
 * Created by LearnFk7 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 文件的内容-

<?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.learnfk7.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="Learnfk 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 文件的内容-

<?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 的内容,以定义两个新的常量-

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 AndroidManifest.xml 的默认内容-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.learnfk7.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.learnfk7.myapplication.CustomActivity">

         <intent-filter>
            <action android:name = "android.intent.action.VIEW" />
            <action android:name = "com.example.learnfk7.myapplication.LAUNCH" />
            <category android:name = "android.intent.category.DEFAULT" />
            <data android:scheme = "http" />
         </intent-filter>

      </activity>
   </application>

</manifest>

在模拟器中执行结果下如:

Android Custom Activity

当点击 通过View 动作启动浏览器时,显示内容如下:

Android Two Activities

现在,如果您选择浏览器,则Android将启动Web浏览器并打开example.com网站,但是如果您选择Indent filter选项,则Android将启动CustomActivity,如下所示-

Android Custom Activity Runs

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

持续交付36讲 -〔王潇俊〕

TypeScript开发实战 -〔梁宵〕

研发效率破局之道 -〔葛俊〕

即时消息技术剖析与实战 -〔袁武林〕

Java业务开发常见错误100例 -〔朱晔〕

职场求生攻略 -〔臧萌〕

Flink核心技术与实战 -〔张利兵〕

玩转Vue 3全家桶 -〔大圣〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

好记忆不如烂笔头。留下您的足迹吧 :)