调用startActivityForResult启动activity,返回当前页不响应的问题(附带activity携带参数流程)

最近在项目遇到这样一个问题,原始的activity不是为我写,后面我要改成返回activity携带参数。我改好了之后 发现不能调用onActivityResult。调试也没有问题,activity结束时候我也是用finish函数的。这样的话,不细心就不会查到Manifest 配置activity语句上。下面说说不响应的问题。

一、Manifest 配置的启动方式有关

activity跟 Manifest 配置的启动方式有关,不要配置启动方式;android:launchMode="singleTask"。原因是在AndroidManifest.xml 中跳转到的页面我自己设置了android:launchMode="singleTask",因为需要传值的 Activity 不容许设置该属性或者 singleInstance,或只能设为标准模式,不然将在 startActivityForResult()后直接调用 onActivityResult()。另外,requestCode值必须要大于等于0,不然,startActivityForResult就变成了 startactivity。

二、按返回键,也要调用finish这个函数。

在B中必须是setResult()后调用finish(),然后回到A,A才会自动调用onActivityResult()
如果你是直接按Back回去的,肯定不会调。

                startActivityForResult(intent,100); //这句启动activity

		Intent intentSend = new Intent();    //返回时,参数的设置
		Bundle sendBundle = new Bundle();
		intentSend.putExtras(sendBundle);
		setResult(RESULT_OK, intentSend);
		finish();


	// 返回按键调用
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return true;
	}

三、下面说一下一般流程

流程是Aactivity进入Bactivity,进入和返回都携带数据,返回后刷新Aactivity。要有一个标志,就是startActivityForResult(newIntent, 12);这句话很明显,开始新的activity并带有结果。

1、itent Aactivity进入Bactivity,使用Bundle携带数据,标志12

			Intent newIntent = new Intent();
			newIntent.setClass(this, TActivity.class);
			Bundle sentBundle = new Bundle();
			sentBundle.putString("Template", String.format("%.4f", 555));
			newIntent.putExtras(sentBundle);
			startActivityForResult(newIntent, 12);
2、 进入新的Bactivity后的获取上携带的数据

		Bundle bundle = this.getIntent().getExtras();
		if (bundle==null) {
			return;
		}
                             bundle.getString("Template");

3、Bactivity返回时,携带数据到 Aactivity
			Intent intentSend = new Intent();
			Bundle bundleSend = new Bundle();
			bundleSend.putString("Template", "数据");	
			intentSend.putExtras(bundleSend);
			setResult(RESULT_OK, intentSend);
			finish();
4、Aactivity返回时接受数据
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataReceive) {
		if (dataReceive == null)
			return;
		if (requestCode == 12) {
			Bundle bundleReceive = dataReceive.getExtras();
			if (bundleReceive == null)  return;
			
			bundleReceive.getString("Template");
		}
		super.onActivityResult(requestCode, resultCode, dataReceive);
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值