Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

113.9. Activity 间数据传递

113.9.1. Intent 方式

设置数据

			
Intent intent= new Intent();
intent.putExtra("name","zhangsan");			
			
			

取出数据

			
Intent intent = getIntent();
String name=intent.getStringExtra("name");			
			
			

113.9.2. Bundle 方式

		
Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle=new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle);
startActivity(it);		
		
			

获取数据

		
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");		
		
			

113.9.3. Flag 属性

Flag属性用来设定Activity的启动模式

			
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			
			

与清单文件中的设置launchMode属性值相同

			
Intent.FLAG_ACTIVITY_CLEAR_TOP = singleTask
Intent.FLAG_ACTIVITY_SINGLE_TOP = singleTop
Intent.FLAG_ACTIVITY_NEW_TASK = singleInstance			
			
			

113.9.3.1. 在 Service,BroadcastReceiver 中切换 View

FLAG_ACTIVITY_NEW_TASK

				
context.startActivity(new Intent(context, PictureBookFullscreenActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));				
				
				

在非Activity(比如Service,BroadcastReceiver)中startActivity需要添加flag Intent.FLAG_ACTIVITY_NEW_TASK

113.9.4. 返回值

有返回值的跳转

			
Intent intent = new Intent(MainActivity.this,HomeActivity.class);
intent.putExtra("nickname","netkiller");
// 第一个参数Intent对象, 第二个参数 RequestCode
startActivityForResult(intent,REQUSET_CODE);
			
			
			

第一个参数 是不是我要的返回结果 第二个参数 是谁返回给我的 第三个参数 返回的附加信息

			
	@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if(requestCode == REQUSET_CODE && resultCode == HomeActivity.RESULT_CODE){
            String msg = data.getStringExtra("msg");
            Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
        }
    }			
			
			

返回结果

			
Intent intent = new Intent();
Intent oldIntent = getIntent();
String nickname = oldIntent.getStringExtra("nickname");
if(TextUtils.isEmpty(nickname)){
    intent.putExtra("msg",nickname);
}else{
    intent.putExtra("msg","Neo");
}

setResult(RESULT_CODE,intent);
//关闭页面
finish();