使用startActivityForResult方法进行数据传递。
MainActivity.java:
1 public class MainActivity extends
Activity {
2Buttonbtn;
3@Override
4protected void onCreate(Bundle savedInstanceState) {
5super.onCreate(savedInstanceState);
6setContentView(R.layout.activity_main);
7Button btn=(Button)findViewById(R.id.button1);
8btn.setOnClickListener(new OnClickListener(){
9@Override
10public void onClick(View arg0) {
11Intent intent=newIntent(MainActivity.this,OtherActivity.class);
12startActivityForResult(intent,1);
13}
14});
15
16
17}
18protected void onActivityResult(int requestCode,int resultCode,Intentdata){
19switch(requestCode){
20case 1:
21String result=data.getExtras().getString("result");
22}
23}
24
25 }
OtherActivity.java:
1 public class OtherActivity extends
Activity {
2Button btn2;
3/**
4*@param args
5*/
6protected void onCreate(Bundle savedInstanceState) {
7super.onCreate(savedInstanceState);
8setContentView(R.layout.activity_other);
9Button btn2=(Button)findViewById(R.id.button2);
10btn2.setOnClickListener(new OnClickListener(){
11
12@Override
13public void onClick(View arg0) {
14// TODO Auto-generatedmethod stub
15Intent intent=new Intent();
16intent.putExtra("result", "hello world");
17OtherActivity.this.setResult(resultcode, intent);
18OtherActivity.this.finish();
19}});
20}
21 }
注:
1.请求码requestCode:startActivityForResult(intent,requestCode)和onActivityResult(int
requestCode,int resultCode,Intent data)中的requestCode为请求码,它的作用是用于标识请求来源。例如:一个Activity有两个按钮,点击这两个按钮都会打开同一个Activity,不管是那个按钮打开新Activity,当这个新Activity关闭后,系统都会调用前面Activity的onActivityResult(int requestCode, int resultCode, Intent data)方法。在onActivityResult()方法如果需要知道新Activity是由那个按钮打开的,并且要做出相应的业务处理。
2.结果码resultCode:在一个Activity中,可能会使用startActivityForResult()方法打开多个不同的Activity处理不同的业务,当这些新Activity关闭后,系统都会调用前面Activi
ty的onActivityResult(int requestCode, int resultCode, Intent data)方法。为了知道返回的数据来自于哪个新Activity,在onActivityResult()方法中可以这样做(Result Activity和NewActivity为要打开的新Activity)。
PS:对于APP安全检测一般我都会用:www.ineice.com