android service 远程,android service(远程service) 知识点
遠(yuǎn)程service能夠?qū)崿F(xiàn)多個應(yīng)用共享一個service,從而實現(xiàn)各個應(yīng)用之間的通信。
遠(yuǎn)程service使用的技術(shù)是AIDL。創(chuàng)建遠(yuǎn)程服務(wù)步驟:
1. 創(chuàng)建包名,在包下創(chuàng)建一個*.aidl文件,在文件里邊定義接口。
package com.example.servicetest.services;
interface MyAIDLService {
int plus(int a, int b);
String toUpperCase(String str);
}
注意,定義接口時,不要使用public等關(guān)鍵字。
2. 在服務(wù)里邊,創(chuàng)建IBander子類對象。
private MyAIDLService.Stub mBinder = new Stub() {
@Override
public String toUpperCase(String str) throws RemoteException {
// TODO Auto-generated method stub
return str.toUpperCase();
}
@Override
public int plus(int a, int b) throws RemoteException {
// TODO Auto-generated method stub
return a + b;
}
};
Stub繼承Binder類,并實現(xiàn)了MyAIDLService接口。所以,我們只要重寫我們自己接口中的方法即可。
3. 在onBind()方法中,返回IBander子類對象。
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
4. 在AndroidManifest.xml文件中配置服務(wù)為遠(yuǎn)程服務(wù)。
android:name="com.example.servicetest.services.MyService"
android:process=":remote"
>
配置遠(yuǎn)程服務(wù)時,一定要在名稱前邊添加":",所以配置成:remote。不然會出現(xiàn)“?INSTALL_PARSE_FAILED_MANIFEST_MALFORMED”部署異常。通過以上的配置,就能在遠(yuǎn)程服務(wù)所在的應(yīng)用下使用遠(yuǎn)程服務(wù)了。但,在另一個應(yīng)用里邊如何使用這個遠(yuǎn)程服務(wù)呢?
具體步驟如下:
1. 將*.aidl文件和所在的包,一起包括到自己應(yīng)用src目錄下。
2. 創(chuàng)建ServiceConnection子類對象。
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
// 和遠(yuǎn)程服務(wù)連接成功以后,就會調(diào)用次方法
try {
MyAIDLService binder = MyAIDLService.Stub.asInterface(service);
int result = binder.plus(1, 2);
String str = binder.toUpperCase("hello world");
System.out.println("result=" + result);
System.out.println("str=" + str);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};通過方法MyAIDLService.Stub.asInterface(service)就能拿到接口對象。從而就能夠調(diào)用服務(wù)里邊的方法了。
3. 通過遠(yuǎn)程服務(wù)提供的action就可以bindService。
總結(jié)
以上是生活随笔為你收集整理的android service 远程,android service(远程service) 知识点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 去掉一键还原 开机按k键
- 下一篇: 收集的 正则表达式