Activity数据传递之StartActivityForResult(上)

根据Google的Android API介绍,当你启动一个Activity的时候并且还要从中获取数据并返回结果的时候,你应该用StartActivityForResult而不是StartActivity。

例如我们要从一个Activity中启动一个联系人的Activity并且从中选取联系人并且把数据返回给Activity:

首先是布局的XML:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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: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="andysong.com.helloworld.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnStart"
        android:text="@string/app_name"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:id="@+id/tv"
        android:textSize="16sp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="73dp" />
</RelativeLayout>

之后,我们就只需要在MainActivity中进行代码的编辑了:

package andysong.com.helloworld;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView mTv;
    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            mTv.setText(result);

        }
    };
    public static final int PICK_CONTACT_REQUEST = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mBtnStart = (Button) findViewById(R.id.btnStart);
        mTv = (TextView) findViewById(R.id.tv);
        if (mBtnStart!=null)
        {
            mBtnStart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent pickContentIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
                    pickContentIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                    startActivityForResult(pickContentIntent,PICK_CONTACT_REQUEST);
                }
            });
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_CONTACT_REQUEST)
        {
            if (resultCode ==RESULT_OK)
            {
                final Uri contentUri = data.getData();
                final String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Cursor cursor = getContentResolver().query(contentUri,projection,
                                null,null,null);
                        Message msg = Message.obtain();
                        if (cursor.moveToFirst())
                        {
                            int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                            String number = cursor.getString(column);

                            msg.obj =number;
                            mHandler.sendMessage(msg);
                        }else {
                            msg.obj = "找不到";
                            mHandler.sendMessage(msg);
                        }

                    }
                }).start();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

说明:

onActivityResult这里面的三个参数代表的意思:

1.你向startActivityForResult()传递的请求码,这里就是PICK_CONTACT_REQUEST

2.第二个参数代表Activity指定的结果代码:操作成功用RESULT_OK,用户退出或者处于某种失败RESULT_CANCELED

3.传递结果数据的Intent


还要就是查询的方法需要放在子线程里面,以免造成UI线程的阻塞。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值