Activity中setResult(int resultCode, Intent data)与onActivityResult(int requestCode, int resultCode, Intent data)方法的调用
关于Activity的生命周期
onCreate(Bundle savedInstanceState):可以进行一些初始化的工作在activity第一次被创建的时候调用。这里是你做所有初始化设置的地方──创建视图、绑定数据至列表等
onStart():Activity显示在前台,但还不可与用户交互
onRestart():在activity停止后,在再次启动之前被调用
onResume():取得控制权,可以对此Activity进行操作此时activity位于堆栈顶部,并接受用户输入
onPause():暂停,可见,但不可操作,此方法主要用来将未保存的变化进行持久化,停止类似动画这样耗费CPU的动作等
onStop():当activity不再为用户可见时调用此方法
onDestroy():在activity销毁时调用
Android的Activity是堆栈结构,多个Activity之间的切换顺序:
MainActivity跳转到Another
1 08-25 05:02:47.783: INFO/System.out(339): MainActivity------->onPause() 2 08-25 05:02:47.843: INFO/System.out(339): Another------->onCreate() 3 08-25 05:02:47.853: INFO/System.out(339): Another------->onStart() 4 08-25 05:02:47.853: INFO/System.out(339): Another------->onResume() 5 08-25 05:02:48.253: INFO/System.out(339): MainActivity------->onStop()
按Back键返回:
1 08-25 05:03:48.133: INFO/System.out(339): Another------->onPause() 2 08-25 05:03:48.174: INFO/System.out(339): MainActivity------->onRestart() 3 08-25 05:03:48.174: INFO/System.out(339): MainActivity------->onStart() 4 08-25 05:03:48.174: INFO/System.out(339): MainActivity------->onResume() 5 08-25 05:03:48.483: INFO/System.out(339): Another------->onStop() 6 08-25 05:03:48.483: INFO/System.out(339): Another------->onDestroy()
第二个Activity使用了finish()方法,返回:
1 08-25 05:10:48.053: INFO/System.out(366): Another------->onPause() 2 08-25 05:10:48.103: INFO/System.out(366): MainActivity------->onRestart() 3 08-25 05:10:48.103: INFO/System.out(366): MainActivity------->onStart() 4 08-25 05:10:48.103: INFO/System.out(366): MainActivity------->onResume() 5 08-25 05:10:48.423: INFO/System.out(366): Another------->onStop() 6 08-25 05:10:48.453: INFO/System.out(366): Another------->onDestroy()
MainActivity需要在Another执行finished()方法获取传入的值:
Another中:
Intent it = new Intent(); Bundle bundle = new Bundle(); bundle.putString("result", resultString); bundle.putParcelable("bitmap", barcode); it.putExtras(bundle); this.setResult(RESULT_OK, resultIntent);
setResult方法:
public final void setResult(int resultCode, Intent data) { synchronized (this) { mResultCode = resultCode; mResultData = data; } }
MainActivity中重写onActivityResult(int requestCode, int resultCode, Intent data)方法
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SCANNIN_GREQUEST_CODE: if(resultCode == RESULT_OK){ Bundle bundle = data.getExtras(); //显示扫描到的内容 mTextView.setText(bundle.getString("result")); //显示 mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap")); } break; } }