zoukankan      html  css  js  c++  java
  • Android进阶笔记15:选用合适的IPC方式

    1. 相信大家都知道Android进程间通信方式很多,比如AIDL、Messenger等等,接下来我就总结一下这些IPC方式优缺点。

    2. IPC方式的优缺点和适用场景

    3. 附加:使用Intent实现跨进程通信

    Intent分为两种,一种是显式Intent,只适合在同一进程内的不同组件之间通信,例如 new Intent(this,Target.class).

    另外一种是隐式Intent,在AndroidMainifest.xml中注册,一般可以用户跨进程通信,例如new Intent(String action).

    下面就介绍隐式Intent跨进程通信的例子:

    Project A 中的代码比较简单,主要就是在的button onClick事件中:

     1 button.setOnClickListener(new OnClickListener()  
     2         {             
     3             @Override public void onClick(View v)  
     4             {       
     5                 Intent intent = new Intent();  
     6                 intent.setAction("com.example.IPCByIntent");  
     7                 intent.putExtra("data", "this is ipc by intent");  
     8                 startActivity(intent);  
     9                
    10             }  
    11         });  

    其中intent.SetAction里面的值是Project B中定义的

    在Project B中的AndroidMainifest.xml,在MainActivity的第二个intent-filter中,添加在Project A中用到的action值

     1 <activity  
     2       android:name="com.example.adildemo.MainActivity"  
     3       android:label="@string/app_name" >  
     4       <intent-filter>  
     5           <action android:name="android.intent.action.MAIN" />  
     6   
     7           <category android:name="android.intent.category.LAUNCHER" />  
     8       </intent-filter>  
     9       <intent-filter>  
    10           <action android:name="com.example.IPCByIntent"/>  
    11           <category android:name="android.intent.category.DEFAULT"/>  
    12       </intent-filter>  
    13   </activity>  

    在Project B的MainActivity.java的OnCreate方法中,添加如下代码:

    1 Intent intent = this.getIntent();  
    2 if(null != intent.getStringExtra("data")){  
    3     tv.setText(intent.getStringExtra("data"));  
    4 }  


    先运行Project B再运行Project A,点击 Porject A 的button,则Project B上的textview 将会显示 this is ipc by intent.

    Intent 可以非常方便的通信,但是它是非实时的,无法进行实时的像函数调用那样的实时通信。

  • 相关阅读:
    对jquery的 attr()和prop()理解
    你真的了解javascript吗
    js代码的一些小技巧
    导出导入数据库
    Mysql授权root用户远程登录
    Centos 忘记root密码怎么办?
    linux挂载概念简述:
    centos7防火墙设置
    centos 防火墙
    centos共享目录
  • 原文地址:https://www.cnblogs.com/hebao0514/p/5415968.html
Copyright © 2011-2022 走看看