与其他app进行交互
将用户发送给另一个app
创建隐式意图
- 隐式意图没有声明类型,但是声明了执行的动作
隐式意图的数据可能是一个Uri
Uri number = Uri.parse("tel:5551234"); Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
查看地图
// Map point based on address Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"); // Or map point based on latitude/longitude // Uri location = Uri.parse("geo:37.422219,-122.08364?z=14"); // z param is zoom level Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
查看网页
Uri webpage = Uri.parse("http://www.android.com"); Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
其他类型的隐式意图需要额外的数据
发送Email
Intent emailIntent = new Intent(Intent.ACTION_SEND); // The intent does not have a URI, so declare the "text/plain" MIME type emailIntent.setType(HTTP.PLAIN_TEXT_TYPE); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"jon@example.com"}); // recipients emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text"); emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment")); // You can also attach multiple items by passing an ArrayList of Uris
创建日历
Intent calendarIntent = new Intent(Intent.ACTION_INSERT, Events.CONTENT_URI); Calendar beginTime = Calendar.getInstance().set(2012, 0, 19, 7, 30); Calendar endTime = Calendar.getInstance().set(2012, 0, 19, 10, 30); calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis()); calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis()); calendarIntent.putExtra(Events.TITLE, "Ninja class"); calendarIntent.putExtra(Events.EVENT_LOCATION, "Secret dojo");
如果你想要显示图片,应该设置MIME类型image/*
验证App接收到意图
在调用意图之前应总要包含一个验证步骤
如果你调用了意图但在设备上却没有可以处理意图的App,你的app将会崩溃
验证有可用的activity可以回复意图,调用queryIntentActivities() 获得处理你的意图的可用activities的集合。如果这个集合是非空,你可以安全地使用意图
PackageManager packageManager = getPackageManager(); List activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); boolean isIntentSafe = activities.size() > 0;
使用意图启动Activity
// Build the intent
Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
// Verify it resolves
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(mapIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(mapIntent);
}
显示App选择器
- 当用户每次都想从多种app中选择一种,你应该创建一个意图,使用createChooser()并将它传递给 startActivity()
Intent intent = new Intent(Intent.ACTION_SEND);
...
// Always use string resources for UI text.
// This says something like "Share this photo with"
String title = getResources().getString(R.string.chooser_title);
// Create intent to show chooser
Intent chooser = Intent.createChooser(intent, title);
// Verify the intent will resolve to at least one activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
}
从一个Activity中得到结果
启动一个活动
- 调用startActivityForResult()启动Activity,调用onActivityResult()得到结果
- startActivityForResult()第二个参数是请求码,用来标识你的请求
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
接受结果
- onActivityResult()三个参数
- 你传递给startActivityForResult()的请求码
- 指定第二个活动的结果码。如果操作成功将返回 RESULT_OK,如果按下返回键或者失败将返回RESULT_CANCELED
- 携带结果数据的意图
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == PICK_CONTACT_REQUEST) { // Make sure the request was successful if (resultCode == RESULT_OK) { // The user picked a contact. // The Intent's data Uri identifies which contact was selected. // Do something with the contact here (bigger example below) } } }
- 你传递给startActivityForResult()的请求码
读取联系人的数据
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
允许其他app启动你的活动
- 为了允许其他的app启动你的活动,你需要在清单文件里为你的活动添加 的属性与你的
添加意图过滤器
- 系统将会发送一个规定的意图,如果活动有意图过滤器并且满足关于Intent object的以下规定
- Action:执行动作的字符串名字
- Data:和意图联系的数据描述
在意图过滤器的元素指定它,在这个元素中指定一种或多种属性,你可以只指定MIME类型,或是URI前缀,抑或是URI组合,或者是这三种的组合和其他可以指定接受数据的类型
如果你不需要指定一个数据URI,你应该仅仅使用android:mimeType属性来声明你活动处理的数据,例如text/plain or image/jpeg
- Category:提供一种额外的方法来描述处理意图的活动的特征,所有的隐式意图默认都有CATEGORY_DEFAULT的定义
在意图过滤器的 元素下指定
* 每个即将到来的意图都会指定 only one action and one data type,但在每个 中都可以声明多种, , and 元素的实例<activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> <data android:mimeType="image/*"/> </intent-filter> </activity>
<activity android:name="ShareActivity"> <!-- filter for sending text; accepts SENDTO action with sms URI schemes --> <intent-filter> <action android:name="android.intent.action.SENDTO"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="sms" /> <data android:scheme="smsto" /> </intent-filter> <!-- filter for sending text or images; accepts SEND action and text or image data --> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="image/*"/> <data android:mimeType="text/plain"/> </intent-filter> </activity>
为了接受到隐式意图,在你的意图过滤器中必须包含 CATEGORY_DEFAULT category ,如果不声明它,将没有隐式意图能够决定你的活动
在你的App中处理意图
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the intent that started this activity Intent intent = getIntent(); Uri data = intent.getData(); // Figure out what to do based on the intent type if (intent.getType().indexOf("image/") != -1) { // Handle intents with image data ... } else if (intent.getType().equals("text/plain")) { // Handle intents with text ... } }
返回结果
- 如果你想要将结果返回给传唤你的应用,仅仅调用setResult()指定结果码和结果意图。当你的操作完成并且用户应该返回到你原来的活动,调用finish()关闭你的应用
// Create intent to deliver some kind of result data Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri")); setResult(Activity.RESULT_OK, result); finish();
- 如果你仅仅需要返回一个整数,你可以将结果码设置为任何一个大于0的数值,并且你不再需要去传递意图
-
setResult(RESULT_COLOR_RED);
finish();