EX05_10.java
上传用户:vip_99
上传日期:2021-03-27
资源大小:61159k
文件大小:3k
- package irdc.EX05_10;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- /*必须引用database.Cursor,Contacts.People
- 与 net.uri等类来使用联系人数据*/
- import android.database.Cursor;
- import android.net.Uri;
- import android.provider.Contacts.People;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- public class EX05_10 extends Activity
- {
- /*声明四个UI变量与一个常数作为Activity接收返回值用*/
- private TextView mTextView01;
- private Button mButton01;
- private EditText mEditText01;
- private EditText mEditText02;
- private static final int PICK_CONTACT_SUBACTIVITY = 2;
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- /*通过findViewById构造器来构造一个TextView,
- 两个EditText,一个Button对象**/
- mTextView01 = (TextView)findViewById(R.id.myTextView1);
- mEditText01 = (EditText)findViewById(R.id.myEditText01);
- mEditText02 = (EditText)findViewById(R.id.myEditText02);
- mButton01 = (Button)findViewById(R.id.myButton1);
-
- /*设置onClickListener 让用户点击Button时搜索联系人*/
- mButton01.setOnClickListener(new Button.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- // TODO Auto-generated method stub
- /*建构Uri来取得联系人的资源位置*/
- Uri uri = Uri.parse("content://contacts/people");
- /*通过Intent来取得联系人数据并返回所选的值*/
- Intent intent = new Intent(Intent.ACTION_PICK, uri);
- /*打开新的Activity并期望该Activity返回值*/
- startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);
- }
- });
- }
-
- @Override
- protected void onActivityResult
- (int requestCode, int resultCode, Intent data)
- {
- // TODO Auto-generated method stub
- switch (requestCode)
- {
- case PICK_CONTACT_SUBACTIVITY:
- final Uri uriRet = data.getData();
- if(uriRet != null)
- {
- try
- {
- /* 必须要有android.permission.READ_CONTACTS权限 */
- Cursor c = managedQuery(uriRet, null, null, null, null);
- /*将Cursor移到资料最前端*/
- c.moveToFirst();
- /*取得联系人的姓名*/
- String strName =
- c.getString(c.getColumnIndexOrThrow(People.NAME));
- /*取得联系人的电话*/
- String strPhone =
- c.getString(c.getColumnIndexOrThrow(People.NUMBER));
- /*将姓名与电话写入EditText01,EditText02中*/
- mEditText01.setText(strName);
- mEditText02.setText(strPhone);
- }
- catch(Exception e)
- {
- /*将错误信息在TextView中显示*/
- mTextView01.setText(e.toString());
- e.printStackTrace();
- }
- }
- break;
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- }