Android 进程间通信 Intent机制 隐式启动Activity

最近对Android的进程间,程序的通信做了细致的研究,分享一下心得。

构造环境:
A,B两个程序,A在运行中,将某个值传递给B,并启动B程序。
B程序完成处理后,将处理结果返回给A程序,A程序继续后续的执行。

场景中B是被调用模块,需要在其AndroidManifest.xml中添加以下内容
<activity android:name=”.actMain” android:label=”@string/actMain_title” android:screenOrientation=”portrait”>
    <intent-filter>
      <action android:name=”android.intent.action.MAIN” />
      <category android:name=”android.intent.category.LAUNCHER” />
   </intent-filter>
   <intent-filter>
      <action android:name=”net.air_id.android.SAC_RESOLVE.SCAN” />
      <category android:name=”android.intent.category.DEFAULT”/>
   </intent-filter>
</activity>

其中第一个intent-filter块,目的是当B程序自己启动时,默认打开的主activity。
第二个intent-filter块,定义的过滤是当隐式启动Activity的时候,系统会搜索到android:name=”net.air_id.android.SAC_RESOLVE.SCAN”名称,启动该activity。
每一个通过 startActivity() 方法发出的隐式 Intent 都至少有一个 category,就是 “android.intent.category.DEFAULT”,所以只要是想接收一个隐式 Intent 的 Activity 都应该包括 “android.intent.category.DEFAULT” category,不然将导致 Intent 匹配失败。
所以需要加上<category android:name=”android.intent.category.DEFAULT”/>
到此B程序配置完成

A程序中如何调用B程序,并通过Intent传递数据给B:
Intent intent = new Intent(“net.air_id.android.SAC_RESOLVE.SCAN”); //这个为隐式启动Activity的搜索名称
Bundle bundle = new Bundle();
bundle.putString(“RESOLVE”,”ExternalCall”);
bundle.putString(“AUTH_CODE”,”test_dev_air-id0″);
intent.putExtras(bundle);/*将数据绑定推出*/
startActivityForResult(intent, REQUESR_SAC_SCAN);//REQUESR_SAC_SCAN为自定义的返回常量

B程序如何接收由A程序传递过来的数据:
String sExtCall = null;
Bundle bundle = this.getIntent().getExtras();
if (null != bundle) //检查有否收到值
    sExtCall = bundle.getString(“RESOLVE”);//取出收到的值

B程序如何将处理结果返回给A程序:
Bundle bundle = new Bundle();
Intent intent = new Intent();
bundle.putString(“RETURN_STATE”,”NO_SINGL”);
bundle.putString(“ERROR_INFO”, “…”);
intent.putExtras(bundle);/*将数据绑定推出*/
this.setResult(Activity.RESULT_OK, intent);//返回前一个act
this.finish();

A程序如何接收由B程序返回时提交过来的结果数据:
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
    if (REQUESR_SAC_SCAN == requestCode)
    {
      if (resultCode == Activity.RESULT_OK)
      {
         StringBuilder sbTmp = new StringBuilder();
         Bundle bunde = intent.getExtras();
         String sState = bunde.getString(“RETURN_STATE”);
      }
   }
}

至此,完成了整个调用与参数传递的过程。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值