使用startActivityForResult方法進行數據傳遞。java
MainActivity.java:安全
1 public class MainActivity extends Activity {ide
2 Button btn;this
3 @Overridespa
4 protected void onCreate(Bundle savedInstanceState) {.net
5 super.onCreate(savedInstanceState);code
6 setContentView(R.layout.activity_main);get
7 Button btn=(Button)findViewById(R.id.button1);it
8 btn.setOnClickListener(new OnClickListener(){class
9 @Override
10 public void onClick(View arg0) {
11 Intent intent=new Intent(MainActivity.this,OtherActivity.class);
12 startActivityForResult(intent,1);
13 }
14 });
15
16
17 }
18 protected void onActivityResult(int requestCode,int resultCode,Intent data){
19 switch(requestCode){
20 case 1:
21 String result=data.getExtras().getString("result");
22 }
23 }
24
25 }
OtherActivity.java:
1 public class OtherActivity extends Activity {
2 Button btn2;
3 /**
4 * @param args
5 */
6 protected void onCreate(Bundle savedInstanceState) {
7 super.onCreate(savedInstanceState);
8 setContentView(R.layout.activity_other);
9 Button btn2=(Button)findViewById(R.id.button2);
10 btn2.setOnClickListener(new OnClickListener(){
11
12 @Override
13 public void onClick(View arg0) {
14 // TODO Auto-generated method stub
15 Intent intent=new Intent();
16 intent.putExtra("result", "hello world");
17 OtherActivity.this.setResult(resultcode, intent);
18 OtherActivity.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