Android使用Intent.putSerializable()進行數據傳遞,或者使用Bundle進行數據傳遞,實質上都是進行的Serializable數據的操作,說白了都是傳遞的原數據的一份拷貝,因此通過對象的傳遞來控制Android應用是不現實的
源代碼如下了:
1 import android.app.Activity; 2 import android.content.Intent; 3 import android.os.Bundle; 4 import android.util.Log; 5 import android.view.View; 6 import android.widget.Button; 7 import com.feng.androidbundle.activity.GetBundleActivity; 8 9 import com.feng.androidbundle.bean.DataBean; 10 11 12 public class AndroidbundleActivity extends Activity { 13 /** Called when the activity is first created. */ 14 @Override 15 public void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.main); 18 19 // 定義一個Bundle按鍵 20 Button gotoBundle = (Button)findViewById(R.id.btnBundle); 21 // 設置監聽事件 22 gotoBundle.setOnClickListener(new View.OnClickListener(){ 23 24 @Override 25 public void onClick(View v) { 26 Intent intent = new Intent(); 27 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 28 intent.setClass(getApplicationContext(), GetBundleActivity.class); 29 30 DataBean temp = new DataBean(); 31 temp.setID(1); 32 temp.setName("曾馳文"); 33 temp.setAddress("xx市xx路xx號"); 34 temp.setMoblie("159xxxxxxxx"); 35 36 Log.i("AndroidbundleActivity", "新建時候的地址" + temp); 37 38 Bundle bundle = new Bundle(); 39 bundle.putSerializable("UserInfo", temp); 40 41 // 設置intent 42 intent.putExtras(bundle); 43 44 // 發送Activity 45 getApplicationContext().startActivity(intent); 46 } 47 48 }); 49 } 50 }
在另外一個Activity中將數據取出來 相應的源代碼如下:
1 import android.app.Activity; 2 import android.content.Intent; 3 import android.os.Bundle; 4 import android.util.Log; 5 import com.feng.androidbundle.R; 6 import com.feng.androidbundle.bean.DataBean; 7 public class GetBundleActivity extends Activity { 8 9 10 @Override 11 public void onCreate(Bundle savedInstanceState) { 12 // 初始化BundleActivity 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.bundle); 15 16 // 獲取意圖 17 Intent intent = getIntent(); 18 Bundle bundle = intent.getExtras(); 19 20 // 獲取對象 21 DataBean temp = (DataBean) bundle.get("UserInfo"); 22 Log.i("GetBundleActivity", "收到的地址" + temp); 23 } 24 }
日志的打印結果
12-19 02:42:49.356: I/AndroidbundleActivity(230): 新建時候的地址com.zcw.androidbundle.bean.DataBean@44c24968
12-19 02:42:49.417: I/GetBundleActivity(230): 收到的地址com.zcw.androidbundle.bean.DataBean@44c33528
由上面的日志可以看出,使用Bundle進行數據的傳遞,實現了serialzable接口實質上是拷貝的傳遞。