获取Activity返回的结果

2016-07-05 · 🙈Lei · 0条 · 387次

启动一个Activity(表象上应该是跳转)如果采用startActivityForResult()的方法可以获取Activity返回的结果。获取结果时,采用显示意图(即利用显示意图将结果返回给自己的activity)。

>_ start Activity

startActivityForResult()需要提供一个额外的整数参数——request code。当收到Intent返回的结果时,回掉函数使用相同的请求代码,可以正确识别结果并确定如何处理结果。

//启动用户选择联系人的Activity
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);
}

>_ 接收结果

当用户返回Activity时,调用onActivityResult()方法获取。包括三个参数:向startActivityForResult()传递的request code;第二个activity指定的结果代码,操作成功,为RESULT_OK,如果用户退出或操作出于某种原因失败,是RESULT_CANCELED;传输结果数据的Intent。

@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)
}
}
}

返回结果的Intent的格式:如果返回结果的activity是自己写的,那么结果很容易获取。如果是系统自带应用返回的结果数据,需要注意一些。这些app提供自己的api,返回的数据不尽相同,例如,“联系人”返回URI,“照相机”在data中返回bitmap。

如下是获取手机号码的例子。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// 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...
}
}
}

注:在android2.3(API 9)以前,在 Contacts Provider 上执行查询需要应用声明READ_CONTACTS权限。自2.3开始,“联系人”授予可以临时读取信息的权限,该临时权限可用于获取特定联系人——意图的URI中指定的联系人,除非声明READ_CONTACTS权限。


  0