startActivity()之前的操作

时间:2010-07-22 08:25:57

标签: java android android-activity android-intent

我是Android开发的新手,我在创建新活动时遇到了问题。

我想在开始之前使用我的活动。例如,我试过了:

MyActivity menu = new MyActivity();
menu.setXmppreception(reception);
Intent intent = new Intent(Screen.this,MyActivity.class);
Screen.this.startActivity(intent);

但是,我的“menu”和“MyActivity.class”不是同一个实例。因此我试了一下:

MyActivity menu = new MyActivity();
menu.setXmppreception(reception);
Intent intent = new Intent(Screen.this,menu);
Screen.this.startActivity(intent);

但它不起作用...... 你有帮助我的解决方案吗?

感谢您的帮助,感谢抱歉英语不好。

2 个答案:

答案 0 :(得分:2)

如果您希望在必须使用Extras的活动之间传递数据,并且只能传递Serializable项目,则不能按照您的意愿执行此操作。

第一个上下文(可以是活动/服务等)

您有几个选择:

1)使用Bundle中的Intent

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2)创建一个新的Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3)使用Intent的putExtra()快捷方式

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

新上下文(可以是活动/服务等)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
     String value = myIntent.getExtras().getString(key);
}

注意: Bundles对所有基本类型,Parcelables和Serializables都有“get”和“put”方法。我只是将字符串用于演示目的。

答案 1 :(得分:1)

您不必自己创建新活动,Android系统会为您完成。 如果您想从Screen Activity转到MyActivity,可以执行以下操作:

Intent intent = new Intent(Screen.this,MyActivity.class);
startActivity(intent);

然后,在你的MyClass java文件中,在onCreate方法中,你可以这样做:

this.setXmppreception(reception);

这样,我觉得你想要你,不是吗?