經過 startActivity(Intent) 方法啓動 Activity,啓動後的兩個 Activity 之間相互獨立,沒有任何的關聯。但一般狀況下,須要後啓動的 Activity 關閉時返回信息給先前啓動的 Activity 。後啓動的稱爲「子Activity」,先啓動的稱爲「父Activity」。java
以 Sub-Activity 方式啓動子Activity,須要調用 startActivityForResult(Intent,requestCode) 函數ide
int SUBACTIVITY1 = 1; Intent intent = new Intent(MainActivity.this,SubActivity1.class); startActivityForResult(intent, SUBACTIVITY1);
int SUBACTIVITY1 = 1; Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("https://my.oschina.net/zhangyujian/blog")); startActivityForResult(intent,SUBACTIVITY1);
Uri data = Uri.parse("tel:"+tel_number); Intent result = new Intent(null,data); // putExtra 用於附加額外信息 result.putExtra("address","SWUST"); setResult(RESULT_OK,result); finish();
說明:子Activity 調用 finish() 函數關閉以前,調用 setResult() 函數設定須要返回給 父Activity 的數據函數
private static int SUBACTIVITY1 = 1; private static int SUBACTIVITY2 = 2; @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); switch(requestCode){ case SUBACTIVITY1: if(resultCode == RESULT_OK){ Uri uriData = data.getData(); //響應操做,經過textView查看返回值 textView.setText(uriData.toString()); }else if(resultCode == RESULT_CANCELED) {} break; case SUBACTIVITY2: if(resultCode == RESULT_OK){ Uri uriData = data.getData(); //響應操做,經過textView查看返回值 textView.setText(uriData.toString()); }else if(resultCode == RESULT_CANCELED) {} break; } }
說明:重載 onActivityResult() 函數實現this
經過簡單的監聽事件加關鍵代碼便可驗證功能。spa