以下兩種方式都是基於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就是解決的這個問題。
2)AIDL
http://www.open-open.com/lib/view/open1469493649028.html (上)
按照博主所說的,結果能實現。
2-1)新建aidl文件,注意新建的規則。
2-2)注意aidl及java類的目錄的問題,並且保證服務端與客戶端都存在aidl與java文件。
2-3)服務端聲明service,service裏調用aidl自動生成的java類。
2-4)客戶端綁定服務端的service,調用aidl轉化的類。