Android API Demos學習(4) – Receive Result

本例展示一個Activity怎麼接受通過它打開的另外一個Activity返回的結果。

比較常見的例子是,發送短信的時候,需要打開聯系人程序選擇聯系人,然後返回選擇的信息到發送程序。

setResult()方法負責發送信息,onActivityResult()方法負責接受信息。
// Definition of the one requestCode we use for receiving resuls.
    static final private int GET_CODE = 0;

    private OnClickListener mGetListener = new OnClickListener() {
        public void onClick(View v) {
            // Start the activity whose result we want to retrieve.  The
            // result will come back with request code GET_CODE.
            Intent intent = new Intent(ReceiveResult.this, SendResult.class);
            startActivityForResult(intent, GET_CODE);
        }
    };

 

startActivityForResult方法啟動我們想從那裡取得信息的Activity,GET_CODE會在返回信息的時候一起返回,那樣我們就通過GET_CODE出來返回的結果。

www.aiwalls.com
在SendResult.java中:
private OnClickListener mCorkyListener = new OnClickListener()
    {
        public void onClick(View v)
        {
            // To send a result, simply call setResult() before your
            // activity is finished.
            setResult(RESULT_OK, (new Intent()).setAction("Corky!"));
            finish();
        }
    };

    private OnClickListener mVioletListener = new OnClickListener()
    {
        public void onClick(View v)
        {
            // To send a result, simply call setResult() before your
            // activity is finished.
            setResult(RESULT_OK, (new Intent()).setAction("Violet!"));
            finish();
        }
    };

在程序停止前調用setResult方法返回結果。
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
        // You can use the requestCode to select between multiple child
        // activities you may have started.  Here there is only one thing
        // we launch.
        if (requestCode == GET_CODE) {

            // We will be adding to our text.
            Editable text = (Editable)mResults.getText();

            // This is a standard resultCode that is sent back if the
            // activity doesn't supply an explicit result.  It will also
            // be returned if the activity failed to launch.
            if (resultCode == RESULT_CANCELED) {
                text.append("(cancelled)");

            // Our protocol with the sending activity is that it will send
            // text in 'data' as its result.
            } else {
                text.append("(okay ");
                text.append(Integer.toString(resultCode));
                text.append(") ");
                if (data != null) {
                    text.append(data.getAction());
                }
            }

            text.append("\n");
        }
    }

 

onActivityResult方法接受返回的結果,在onResume方法前執行。三個參數的意思分別是:
1. requestCode就是startActivityForResult中的第二個參數,可以用來區分是哪一個activity發送的請求。
2. resultCode是子activity返回的code,一般為RESULT_OK和RESULT_CANCELLED。
3. data是返回的結果數據。

發佈留言