intent =new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, intresultCode, Intent data) {
// If the requestwent well (OK) and the request was PICK_CONTACT_REQUEST
if (resultCode== Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
// Perform aquery to the contact's content provider for the contact's name
Cursorcursor = getContentResolver().query(data.getData(),new String[]{Contacts.DISPLAY_NAME}, null, null, null);
if(cursor.moveToFirst()) { // True if the cursor is not empty
intcolumnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
String name =cursor.getString(columnIndex);
// Dosomething with the selected contact's name...
}
}
}
此例子展示了在onActivityResult()中的基本逻辑流程。首选检查所启动的Activity是否正确运行,resultCode为Activity.RESULT_OK表示正常,其次,查看requestCode是否与当时请求的一致,即是否为PICK_CONTACT_REQUEST。都通过后,开始操作返回的数据,也就是data参数。
Data是这样处理的,用ContentResolver向内容提供者发出请求,这个请求会返回一个游标,通过这个游标读取数据,这很像数据库表的操作。要理解此处,请查阅Content Providers一节。
Activity可以内部调用finish()方法关闭它自己,也可以调用finishActivity()方法关闭其它的activity。
注意:大多数情况下,你不应主动结束一个activity。系统掌管着activity的生命,所以你也不必结束自己的activity。使用上述方法会破坏用户体验。除非你觉得很必要时,否则就不要做!