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

本文转自:http://note.sdo.com/u/jerryli/n/prb71~jPPymOwE0f0001eN

构造环境:

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");

      }

   }

}

 

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

原文地址:https://www.cnblogs.com/freeliver54/p/2565649.html