天天看點

AIDL深入學習1)一種簡單的實作跨程序的方式(Binder,Messenger)

Android多程序總結一:生成多程序(android:process屬性) - lixpjita39的專欄 - CSDN部落格請添加連結描述

以下兩種方式都是基于bindService啟動服務。

1)一種簡單的實作跨程序的方式(Binder,Messenger)

http://www.open-open.com/lib/view/open1469493830770.html

使用Messenger的好處就是如果有多個請求,不會沖突,會将請求放入請求隊列中一個一個執行任務。

首先要明确哪個是用戶端,哪個是服務端。
 Service是聲明在服務端工程裡的,因為要被用戶端工程調用到,是以是隐式聲明的:
 `  <service  android:name=".aidl.MessengerServiceDemo" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="com.lypeer.messenger"></action>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </service>

    <activity android:name=".aidl.ActivityMessenger"/>`           

服務端工程安裝好後,開啟用戶端工程,綁定服務端聲明的服務。(服務端服務不一定要事先開啟了,聲明了即可。)

注意: 用戶端工程隐式調用服務端開啟的那個service,傳給intent的包名是服務端的包名,并非自己的包名。

`public class MainActivity extends AppCompatActivity {

static final int MSG_SAY_HELLO = 1;

Messenger mService = null;
boolean mBound;
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        //接收onBind()傳回來的IBinder,并用它構造Messenger
        mService = new Messenger(service);
        mBound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        mService = null;
        mBound = false;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById(R.id.sample_text).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sayHello(view);
        }
    });
}

//調用此方法時會發送資訊給服務端
public void sayHello(View v) {
    if (!mBound) return;
    //發送一條資訊給服務端
    Message msg = Message.obtain(null, MSG_SAY_HELLO, 1, 2);
    try {
        mService.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

@Override
protected void onStart() {
    super.onStart();
    //綁定服務端的服務,此處的action是service在Manifests檔案裡面聲明的
    Intent intent = new Intent();
    intent.setAction("com.lypeer.messenger");
    //不要忘記了包名,不寫會報錯
    intent.setPackage("com.example.lianxiang.cmakedemo1");
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}           

}`

這樣,在用戶端就可以操作,實作與服務端工程的一個互動。

Messenger實作的程序間的互動,隻是資訊的傳遞,用戶端無法直接調用服務端的方法,是以AIDL就是解決的這個問題。

繼續閱讀