前面我们介绍完Android系统的四大组件:Activity、Service、ContentProvider、BroadCastReceiver,现在,我们来介绍他们之间的联系枢纽————Intent
Intent,意思是“意图”,Intent是Android系统提供的用于应用之间或应用内部Activity、Service、BroadCastReceiver之间进行交互的一种机制。Intent在程序运行时连接不同的组件,我们可以通过Intent向Android系统发出请求,Android系统会根据请求选择合适的组件进行响应。(ContentProvider本身就是一种通信机制,不需要通过Intent通信)
如果AActivity想要向BActivity或者Android系统的其他组件传递参数,或者启动其他组件,不需要直接联系,通过Intent作为桥梁,简单的说就是,用Intent来作为中介联系其他组件。
例如可以通过下面这几种方法传递Intent实现启动Activity、启动Service或者绑定Service,发送广播
发送广播:Context.sendBroadcast(),Context.sendOrderedBroadcast(),或者Context.sendStickyBroadcast()
Intent有两种:显式Intent和隐式Intent。显式Intent通过具体的组件名去启动组件,一次只能启动一个组件;隐式Intent不指定具体的组件名,而是指定Intent的Action、category等信息,交给Android系统去分析这个Intent,并帮我们选择合适的组件去启动,当有多个组件符合的时候,显示所有分组件给我们选择。
Intent由以下各个组成部分:
下面分别介绍各个属性:
ComponentName明确指定目标组件的名称,属于显式Intent
btn_component = (Button) findViewById(R.id.btn_component);
btn_component.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
ComponentName componentName = new ComponentName(MainActivity.this, ComponentActivity.class);
intent.setComponent(componentName);
startActivity(intent);
}
});
或者可以这样写:
btn_component = (Button) findViewById(R.id.btn_component);
btn_component.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
// ComponentName componentName = new ComponentName(MainActivity.this, ComponentActivity.class);
// intent.setComponent(componentName);
intent.setClass(MainActivity.this, ComponentActivity.class);
startActivity(intent);
}
});
还可以这样写:这是最常用的写法
btn_component = (Button) findViewById(R.id.btn_component);
btn_component.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,ComponentActivity.class);
// ComponentName componentName = new ComponentName(MainActivity.this, ComponentActivity.class);
// intent.setComponent(componentName);
// intent.setClass(MainActivity.this, ComponentActivity.class);
startActivity(intent);
}
});
action是用户定义的一个字符串,用于描述Android系统的应用组件。Intent不直接指明这个组件,交给Android系统去根据Intent-Filter做筛选,选择符合的组件去启动。例如下面的例子:
Activity代码:
btn_action = (Button) findViewById(R.id.btn_action);
btn_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("com.example.ActionActivity");
startActivity(intent);
}
});
package com.example.intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* Created by Administrator on 2016/6/23.
*/
public class ActionActivity extends AppCompatActivity {
private TextView tv_say;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_component);
tv_say = (TextView) findViewById(R.id.tv_say);
tv_say.setText("这是通过Action启动Activity");
}
}
清单文件配置:
<activity android:name=".ActionActivity">
<intent-filter>
<action android:name="com.example.ActionActivity" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
同样是一个字符串,category为action添加额外的描述信息,同样是在Intent-Filter中指定,一个Intent可以设置多个category,但是只能设置一个action。category通常和action一起使用,例子代码可以参考上面action的例子代码。
data属性与action和category的生命方法一样,也是在intent-filter中,通常用于向Android提供数据,当有多个组件匹配的时候,优先级高的优先显示,优先级相同的显示列表。data接收一个uri对象,uri对象的格式是:协议头:主机,端口:路径。
例子代码如下:
btn_data = (Button) findViewById(R.id.btn_data);
btn_data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.parse("http://blog.csdn.net/");
intent.setData(uri);
startActivity(intent);
}
});
Type属性用于明确Data属性的数据类型或MIME类型,当Intent不指定Data属性时,Type属性才会起作用,如果有指定Data属性时,Android系统将会根据Data属性值来分析数据的类型,所以无需指定Type属性。data和type属性一般只需要一个,通过setData方法会把type属性设置为null,相反设置setType方法会把data设置为null,如果想要两个属性同时设置,要使用Intent.setDataAndType()方法。
使用extras可以为组件提供扩展信息,比如,如果要执行“发送短信”这个动作,可以将短信的接收人、美容等保存在extras里,传给短信发送组件。
一个应用启动后系统会为这个应用分配一个栈(task)供其使用,另外同一个task里面可以拥有不同应用程序的activity。
注:android中一组逻辑上在一起的activity被叫做task,自己认为可以理解成一个activity堆栈。
常用的Intent系统应用
package com.example.intent;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private Button btn_component;
private Button btn_action;
private Button btn_data;
private Button btn_tel;
private Button btn_send;
private Button btn_open;
private Button btn_install;
private Button btn_unuinstall;
private Button btn_contact;
private Button btn_contact_set;
private Button btn_open_anthor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_component = (Button) findViewById(R.id.btn_component);
btn_component.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, ComponentActivity.class);
// ComponentName componentName = new ComponentName(MainActivity.this, ComponentActivity.class);
// intent.setComponent(componentName);
// intent.setClass(MainActivity.this, ComponentActivity.class);
startActivity(intent);
}
});
btn_action = (Button) findViewById(R.id.btn_action);
btn_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("com.example.ActionActivity");
startActivity(intent);
}
});
btn_data = (Button) findViewById(R.id.btn_data);
btn_data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.parse("http://blog.csdn.net/");
intent.setData(uri);
startActivity(intent);
}
});
btn_tel = (Button) findViewById(R.id.btn_tel);
btn_tel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse("tel:10086");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
}
});
btn_send = (Button) findViewById(R.id.btn_send);
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse("smsto:10086");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "发送短信啦");
startActivity(intent);
}
});
btn_open = (Button) findViewById(R.id.btn_open);
btn_open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
btn_install = (Button) findViewById(R.id.btn_install);
btn_install.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(new File("/storage/sdcard0/AndroidTest/intent.apk"));
intent.setDataAndType(data, "application/vnd.android.package-archive");
startActivity(intent);
}
});
btn_unuinstall = (Button) findViewById(R.id.btn_unuinstall);
btn_unuinstall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_DELETE);
Uri data = Uri.parse("package:com.example.intent");
intent.setData(data);
startActivity(intent);
}
});
btn_contact = (Button) findViewById(R.id.btn_contact);
btn_contact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Contacts.People.CONTENT_URI);
startActivity(intent);
}
});
btn_contact_set = (Button) findViewById(R.id.btn_contact_set);
btn_contact_set.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(Contacts.People.CONTENT_ITEM_TYPE);
intent.putExtra(Contacts.Intents.Insert.NAME, "Name");
intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");
intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE, Contacts.PhonesColumns.TYPE_MOBILE);
intent.putExtra(Contacts.Intents.Insert.EMAIL, "[email protected]");
intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, Contacts.ContactMethodsColumns.TYPE_WORK);
startActivity(intent);
}
});
btn_open_anthor = (Button) findViewById(R.id.btn_open_anthor);
btn_open_anthor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.example.intent","com.example.intent");
intent.setComponent(componentName);
intent.setAction("android.intent.action.MAIN");
startActivityForResult(intent, RESULT_OK);
}
});
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
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.intent.MainActivity">
<Button
android:id="@+id/btn_component"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显式启动Intent" />
<Button
android:id="@+id/btn_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Action启动Intent" />
<Button
android:id="@+id/btn_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开一个网页" />
<Button
android:id="@+id/btn_tel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="直接拨打电话" />
<Button
android:id="@+id/btn_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送短信" />
<Button
android:id="@+id/btn_open"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开摄像头" />
<Button
android:id="@+id/btn_install"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="安装程序" />
<Button
android:id="@+id/btn_unuinstall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="卸载程序" />
<Button
android:id="@+id/btn_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开联系人界面" />
<Button
android:id="@+id/btn_contact_set"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="编辑添加联系人" />
<Button
android:id="@+id/btn_open_anthor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开另一程序" />
</LinearLayout>
效果图:
需要注意权限问题,打开网页需要访问网络的权限,发送短信和拨打电话需要相应的权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS"/>
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtra("message", 10000);
startActivity(intent);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtra("message2", "这是一组字符串数据");
startActivity(intent);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
Bundle bundle = new Bundle();
bundle.putStringArray("message3", new String[]{"你好", "Intent"});
intent.putExtras(bundle);
startActivity(intent);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
List<String> list = new ArrayList<String>();
list.add("你是1");
list.add("你是2");
list.add("你是3");
list.add("你是4");
intent.putStringArrayListExtra("message4", (ArrayList<String>) list);
startActivity(intent);
Map<String, String> map = new HashMap<String, String>();
map.put("first", "第一个数据");
map.put("second", "第二个数据");
map.put("third", "第三个数据");
map.put("fourth", "第四个数据");
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map);
Bundle bundle = new Bundle();
ArrayList list1 = new ArrayList();
list1.add(list);
bundle.putParcelableArrayList("message5", list1);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtras(bundle);
startActivity(intent);
Person person1 = new Person("张三", "男", 24);
Person person2 = new Person("李四", "男", 24);
Person person3 = new Person("王五", "女", 22);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtra("p1", person1);
intent.putExtra("p2", person2);
intent.putExtra("p3", person3);
startActivity(intent);
这个对象需要实现Parcelable接口,这个接口前面有简单的介绍
package com.example.intent;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Administrator on 2016/6/23.
*/
public class Person implements Parcelable {
String name;
String sex;
Integer age;
protected Person(Parcel in) {
name = in.readString();
sex = in.readString();
age = in.readInt();
}
public Person(String name, String sex, Integer age) {
this.name = name;
this.sex = sex;
this.age = age;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(sex);
parcel.writeInt(age);
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
bitmap对象默认实现Parcelable接口,注意,不能传递大于40K的图片,否则会报错
Bitmap bitmap=null;
Intent intent=new Intent(IntentActivity.this,DataActivity.class);
intent.putExtra("message6",bitmap);
startActivity(intent);
界面如下:
完整的代码:
package com.example.intent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2016/6/23.
*/
public class IntentActivity extends AppCompatActivity {
private Button btn_send_int;
private Button btn_send_string;
private Button btn_send_array;
private Button btn_send_list;
private Button btn_send_map;
private Button btn_send_object;
private Button btn_send_bitmap;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent);
btn_send_int = (Button) findViewById(R.id.btn_send_int);
btn_send_int.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtra("message", 10000);
startActivity(intent);
}
});
btn_send_string = (Button) findViewById(R.id.btn_send_string);
btn_send_string.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtra("message2", "这是一组字符串数据");
startActivity(intent);
}
});
btn_send_array = (Button) findViewById(R.id.btn_send_array);
btn_send_array.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
Bundle bundle = new Bundle();
bundle.putStringArray("message3", new String[]{"你好", "Intent"});
intent.putExtras(bundle);
startActivity(intent);
}
});
btn_send_list = (Button) findViewById(R.id.btn_send_list);
btn_send_list.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
List<String> list = new ArrayList<String>();
list.add("你是1");
list.add("你是2");
list.add("你是3");
list.add("你是4");
intent.putStringArrayListExtra("message4", (ArrayList<String>) list);
startActivity(intent);
}
});
btn_send_map = (Button) findViewById(R.id.btn_send_map);
btn_send_map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String, String> map = new HashMap<String, String>();
map.put("first", "第一个数据");
map.put("second", "第二个数据");
map.put("third", "第三个数据");
map.put("fourth", "第四个数据");
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map);
Bundle bundle = new Bundle();
ArrayList list1 = new ArrayList();
list1.add(list);
bundle.putParcelableArrayList("message5", list1);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
btn_send_object = (Button) findViewById(R.id.btn_send_object);
btn_send_object.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Person person1 = new Person("张三", "男", 24);
Person person2 = new Person("李四", "男", 24);
Person person3 = new Person("王五", "女", 22);
Intent intent = new Intent(IntentActivity.this, DataActivity.class);
intent.putExtra("p1", person1);
intent.putExtra("p2", person2);
intent.putExtra("p3", person3);
startActivity(intent);
}
});
btn_send_bitmap = (Button) findViewById(R.id.btn_send_bitmap);
btn_send_bitmap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap bitmap=null;
Intent intent=new Intent(IntentActivity.this,DataActivity.class);
intent.putExtra("message6",bitmap);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
解析获取数据的代码
package com.example.intent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* Created by Administrator on 2016/6/23.
*/
public class DataActivity extends AppCompatActivity {
private TextView textView;
private TextView textView2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_component);
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
// int data = intent.getExtras().getInt("message");
// textView.setText("接收到数据是:" + data);
// String data2 = intent.getExtras().getString("message2");
// textView2.setText("接收到数据是:" + data2);
// Bundle bundle = intent.getExtras();
// String[] data3 = bundle.getStringArray("message3");
// StringBuffer buffer = new StringBuffer();
// for (int i = 0; i < data3.length; i++) {
// buffer.append(data3[i]);
// }
// ArrayList<String> list = intent.getStringArrayListExtra("message4");
StringBuffer buffer = new StringBuffer();
// Bundle bundle = intent.getExtras();
// ArrayList list1 = bundle.getParcelableArrayList("message5");
// List<Map<String, String>> mapList = (List<Map<String, String>>) list1.get(0);
// Map<String, String> map = mapList.get(0);
// for (Map.Entry<String, String> entry : map.entrySet()) {
// buffer.append("键是:" + entry.getKey() + ",值是:" + entry.getValue());
// }
// Person p1 = intent.getParcelableExtra("p1");
// Person p2 = intent.getParcelableExtra("p2");
// Person p3 = intent.getParcelableExtra("p3");
Bitmap bitmap = intent.getParcelableExtra("message6");
textView2.setText("接收到数据是:");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
至此,Android系统的四大组件和Intent对象基本介绍完成,下面介绍Android系统提供的简单UI控件。