上代码:在活动一中放置触发代码
public boolean onKeyDown(int keyCode ,KeyEvent enent){ if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){ Intent i = new Intent("net.learn2devlop.ACTIVITY2"); Bundle extras = new Bundle(); extras.putString("Name", "Your name here"); i.putExtras(extras) ; startActivityForResult(i, 1); } return false; }
在net.learn2devlop.ACTIVITY2中接收参数:
public class ACTIVITY2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String defaultName = ""; Bundle extras = getIntent().getExtras(); if(extras != null){ defaultName = extras.getString("Name"); } System.out.println("传过来的值是:"+defaultName); } }
代码说明:
1)要使用Intent对象承载数据并传送给目标活动,您要使用Bundle对象
Bundle extras = new Bundle(); extras.putString("Name", "Your name here"); i.putExtras(extras) ;
一个Bundle对象基本上是一个字典对象,使您可以按键/值对的方式设置数据。在这种情况下,建立一个名为Name的键并赋给其值为"Yournamehere"。然后使用putExtras()方法将Bundle对象添加到Intent对象中。
2)在目标活动中,首先使用getIntent()方法来获得启动该活动的Intent,然后使用gettExtras()方法来获得Bundle对象.
String defaultName = ""; Bundle extras = getIntent().getExtras(); if(extras != null){ defaultName = extras.getString("Name"); }
getString()方法从Bundle对象中检索名为name的键名.然后就可以进行自己的操作了。