天天看點

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 可以非常友善的通信,但是它是非實時的,無法進行實時的像函數調用那樣的實時通信。