Android開(kāi)發(fā)高級(jí)進(jìn)階
第二章學(xué)習(xí)
Service的跨進(jìn)程開(kāi)發(fā)####
概要:
Service的跨進(jìn)程通信主要由兩種Android提供的方法進(jìn)行摸吠,一個(gè)是AIDL就缆,通過(guò)創(chuàng)建一個(gè)AIDL文件來(lái)完成奥帘,另一個(gè)是利用Messenger,發(fā)送Message來(lái)實(shí)現(xiàn)
參考:
http://blog.csdn.net/lmj623565791/article/details/38461079
http://blog.csdn.net/lmj623565791/article/details/47017485
什么是進(jìn)程
打個(gè)比方,打開(kāi)Windows的任務(wù)管理器旧困,默認(rèn)就顯示了正在電腦上運(yùn)行的進(jìn)程,甚至你會(huì)看到多標(biāo)簽瀏覽器會(huì)產(chǎn)生多個(gè)進(jìn)程稼锅,他們基本上都是資源獨(dú)立存在而運(yùn)行著的吼具,其中一個(gè)未響應(yīng)并不會(huì)導(dǎo)致其他進(jìn)程的崩潰。
為什么要使用多進(jìn)程
首要原因是為了穩(wěn)定矩距,而第二個(gè)原因是擴(kuò)充App的可用內(nèi)存拗盒,因?yàn)锳ndroid為每一個(gè)進(jìn)程都設(shè)置了內(nèi)存上限,超越了就會(huì)Out Of Memory锥债。
先創(chuàng)建一個(gè)新工程陡蝇,叫做Demo,包名為com.einsteinford.demo哮肚。創(chuàng)建時(shí)包含一個(gè)空的MainActivity登夫,暫時(shí)不刪除它。
AIDL
在Android Studio中使用AIDL并不困難允趟,分為以下幾步進(jìn)行
1.新建AIDL文件
新建好的文件內(nèi)容為
// IMyAidlInterface.aidl
package com.einsteinford.demo;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,double aDouble, String aString);
}
basicTypes就是一個(gè)默認(rèn)給出的抽象方法范例恼策,括號(hào)內(nèi)表示Aidl支持的基本數(shù)據(jù)類型。
2.自定義內(nèi)部方法
interface IMyAidlInterface {
boolean createPerson(String name,int age);
}
然后按F9進(jìn)行Make Project操作拼窥,此時(shí)戏蔑,在下圖目錄中的位置會(huì)自動(dòng)新建一個(gè)IMyAidlInterface的java文件,
package com.einsteinford.demo;
public interface IMyAidlInterface extends android.os.IInterface
{...}
關(guān)于其中的代碼鲁纠,上文中的鏈接會(huì)有較為詳細(xì)的講述总棵,筆者水平有限,不便贅述改含,只需記得上述2個(gè)文件的包名情龄。
3.在一個(gè)Service中新建此類
private IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
@Override
public boolean createPerson(String name, int age) throws RemoteException {
Log.i("new Person","名字:"+name+" 年齡:"+age);
return true;
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
重寫(xiě)我之前定義的抽象方法,并在Service 的 onBind中返回此實(shí)例。自此骤视,其它綁定服務(wù)的進(jìn)程里便可通過(guò)mBinder調(diào)用其中的方法了鞍爱。
4.別忘了在AndroidManifest中注冊(cè)
<service
android:name=".MessengerService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.einsteinford.demo.service"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
5.在其它應(yīng)用中調(diào)用create方法
這方法研究了挺久,不過(guò)专酗,最終還是成功啦~
退出Project睹逃,在Android Studio里新建一個(gè)應(yīng)用,取名PrecessDemo祷肯,包名是com.einsteinford.precessdemo沉填。
為了能在新的App中正常實(shí)例化IMyAidlInterface,必須將之前在Service中創(chuàng)建的那兩個(gè)文件拷貝到新建的App的文件夾中佑笋,如下圖翼闹。
文件目錄跟Service的App包名保持一致。
此時(shí)蒋纬,可以正常在MainActivity中編寫(xiě)代碼了
package com.einsteinford.precessdemo;
import com.einsteinford.demo.IMyAidlInterface;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private IMyAidlInterface mIMyAidlInterface;
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
Log.i("new process", "onServiceConnected: ");
}
@Override
public void onServiceDisconnected(ComponentName name) {
mIMyAidlInterface = null;
}
};
public Button mBtnBind;
public Button mBtnCreate;
public Button mBtnUnbind;
public Intent mServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnBind = (Button) findViewById(R.id.btn_bind);
mBtnBind.setOnClickListener(this);
mBtnCreate = (Button) findViewById(R.id.btn_create);
mBtnCreate.setOnClickListener(this);
mBtnUnbind = (Button) findViewById(R.id.btn_unbind);
mBtnUnbind.setOnClickListener(this);
mServiceIntent = new Intent();
mServiceIntent.setAction("com.einsteinford.demo.service");
mServiceIntent.setPackage("com.einsteinford.demo");
}
@Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.btn_bind:
bindService(mServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
break;
case R.id.btn_create:
boolean b = mIMyAidlInterface.createPerson("阿三", 25);
Log.i("new process", "創(chuàng)建結(jié)果: " + b);
break;
case R.id.btn_unbind:
unbindService(mConnection);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
還有布局文件猎荠,放了3個(gè)按鈕,分別用于“綁定服務(wù)”蜀备,“調(diào)用服務(wù)內(nèi)方法”以及“解綁服務(wù)”关摇。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.einsteinford.precessdemo.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bind Service"
android:id="@+id/btn_bind"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="create"
android:id="@+id/btn_create"
android:layout_below="@+id/btn_bind"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unbind"
android:id="@+id/btn_unbind"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
這些代碼就跟普通的沒(méi)什么區(qū)別,只不過(guò)如今使用隱式Intent調(diào)用Service琼掠,必須添加包名Intent.setPackage()拒垃,這下,在新應(yīng)用內(nèi)依次點(diǎn)擊3個(gè)按鈕瓷蛙,便會(huì)顯示出下圖的效果了
Service中創(chuàng)建了Activity傳入的人物悼瓮,Activity也取得了創(chuàng)建成功的返回值。
至此艰猬,成功完成跨App間的AIDL方式通信横堡,下次再寫(xiě)Messenger的方式。
-完-