Android API Demos学习(4) - Receive Result
2661 点击·0 回帖
![]() | ![]() | |
![]() | 本例展示一个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.atcpu.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是返回的结果数据。 | |
![]() | ![]() |