調用startActivityForResult啟動activity,返回當前頁不響應的問題(附帶activity攜帶參數流程),startactivityresult
最近在項目遇到這樣一個問題,原始的activity不是為我寫,後面我要改成返回activity攜帶參數。我改好了之後 發現不能調用onActivityResult。調試也沒有問題,activity結束時候我也是用finish函數的。這樣的話,不細心就不會查到Manifest 配置activity語句上。下面說說不響應的問題。
一、Manifest 配置的啟動方式有關
activity跟 Manifest 配置的啟動方式有關,不要配置啟動方式;android:launchMode="singleTask"。原因是在AndroidManifest.xml 中跳轉到的頁面我自己設定了android:launchMode="singleTask",因為需要傳值的 Activity 不容許設定該屬性或者 singleInstance,或只能設為標準模式,不然將在 startActivityForResult()後直接調用 onActivityResult()。另外,requestCode值必須要大於等於0,不然,startActivityForResult就變成了 startactivity。
二、按返回鍵,也要調用finish這個函數。
在B中必須是setResult()後調用finish(),然後回到A,A才會自動調用onActivityResult()
如果你是直接按Back回去的,肯定不會調。
startActivityForResult(intent,100); //這句啟動activityIntent intentSend = new Intent(); //返回時,參數的設定Bundle sendBundle = new Bundle();intentSend.putExtras(sendBundle);setResult(RESULT_OK, intentSend);finish();// 返回按鍵調用public boolean onKeyDown(int keyCode, KeyEvent event) {// TODO Auto-generated method stubif (keyCode == KeyEvent.KEYCODE_BACK) {finish();}return true;}
三、下面說一下一般流程
流程是Aactivity進入Bactivity,進入和返回都攜帶資料,返回後重新整理Aactivity。要有一個標誌,就是startActivityForResult(newIntent, 12);這句話很明顯,開始新的activity並帶有結果。
1、itent Aactivity進入Bactivity,使用Bundle攜帶資料,標誌12
Intent newIntent = new Intent();newIntent.setClass(this, TActivity.class);Bundle sentBundle = new Bundle();sentBundle.putString("Template", String.format("%.4f", 555));newIntent.putExtras(sentBundle);startActivityForResult(newIntent, 12);
2、 進入新的Bactivity後的擷取上攜帶的資料
Bundle bundle = this.getIntent().getExtras();if (bundle==null) {return;} bundle.getString("Template");
3、Bactivity返回時,攜帶資料到 Aactivity
Intent intentSend = new Intent();Bundle bundleSend = new Bundle();bundleSend.putString("Template", "資料");intentSend.putExtras(bundleSend);setResult(RESULT_OK, intentSend);finish();
4、Aactivity返回時接受資料
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent dataReceive) {if (dataReceive == null)return;if (requestCode == 12) {Bundle bundleReceive = dataReceive.getExtras();if (bundleReceive == null) return;bundleReceive.getString("Template");}super.onActivityResult(requestCode, resultCode, dataReceive);}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。