android service 远程,android service(远程service) 知识点
遠程service能夠實現多個應用共享一個service,從而實現各個應用之間的通信。
遠程service使用的技術是AIDL。創建遠程服務步驟:
1. 創建包名,在包下創建一個*.aidl文件,在文件里邊定義接口。
package com.example.servicetest.services;
interface MyAIDLService {
int plus(int a, int b);
String toUpperCase(String str);
}
注意,定義接口時,不要使用public等關鍵字。
2. 在服務里邊,創建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類,并實現了MyAIDLService接口。所以,我們只要重寫我們自己接口中的方法即可。
3. 在onBind()方法中,返回IBander子類對象。
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
4. 在AndroidManifest.xml文件中配置服務為遠程服務。
android:name="com.example.servicetest.services.MyService"
android:process=":remote"
>
配置遠程服務時,一定要在名稱前邊添加":",所以配置成:remote。不然會出現“?INSTALL_PARSE_FAILED_MANIFEST_MALFORMED”部署異常。通過以上的配置,就能在遠程服務所在的應用下使用遠程服務了。但,在另一個應用里邊如何使用這個遠程服務呢?
具體步驟如下:
1. 將*.aidl文件和所在的包,一起包括到自己應用src目錄下。
2. 創建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
// 和遠程服務連接成功以后,就會調用次方法
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)就能拿到接口對象。從而就能夠調用服務里邊的方法了。
3. 通過遠程服務提供的action就可以bindService。
總結
以上是生活随笔為你收集整理的android service 远程,android service(远程service) 知识点的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 去掉一键还原 开机按k键
- 下一篇: 收集的 正则表达式
