Android的后台服务service有两种,一种是本地服务,通过startservice()来启动; 另一种是远程服务,通过bindservice来启动,必须配合RPC机制,RPC机制有多种方式,其中比较好用的一种叫AIDL;
1、AIDL用于向另一个APK提供服务:
要构键远程服务,需要以下步骤:
a/编写一个AIDL文件来向客户端定义接口,使用的包名称与android项目所使用的包相同。把它放在SRC目录下,android插件会从它生成一个*.java的接口。
package com.aidlServer;
import com.aidlServer.Book;
interface IAIDLServerService {
String sayHello();
}
生成一个IAIDLServerService.java文件在gen下
b/实现一个服务service并从Onbind()方法返回所生成的接口。
package com.aidlServer;
import com.aidlServer.IAIDLServerService.Stub;
import com.aidlServer.IAIDLServerService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AidlServerService extends Service {
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* 在AIDL文件中定义的接口实现。
*/
private IAIDLServerService.Stub mBinder = new Stub() {
public String sayHello() throws RemoteException {
//WRITE THE CODE YOU NEED
return "Hello";
}
};
}
c/将服务配置添加到androidmanifest.xml文件中。
<service android:name="AidlServerService"
android:process=":remote">
<intent-filter>
<action android:name="com.aidlServer.IAIDLServerService"></action>
</intent-filter>
</service>
这样向其他应用提供数据的服务server就写好了!接着来看如何写client
当客户端和服务通信时,他们之间必须有个协议。使用SERVER提供的服务,需要先把服务的AIDL文件复制到客户端中,然后它也会自动生成一个gen/
2、AIDL用于向服务向同个APK的其他类提供服务实例,让其他类能像使用自己的方法、变量一样使用这个类的方法、变量。
a/在要向其他类提供实例的类中实现onbind()方法return一个内部类,这个类中有个方法返回this指针.
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
public class LocalBinder extends Binder {
getRunningAppName getService(){
return getRunningAppName.this;
}
}
private final IBinder mBinder = new LocalBinder();
b/在要获得服务实例的类中获得这个实例
Intent appIntent = new Intent(getApplicationContext(), getRunningAppName.class);
// startService(appIntent);启动服务
bindService(appIntent,mRunningAppNameConn, Context.BIND_AUTO_CREATE);
private ServiceConnection mRunningAppNameConn = new ServiceConnection() {
//@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(LogTAG,"onServiceConnected ");
mRunningAppName = ((getRunningAppName.LocalBinder)service).getService();//获得实例
//@Override
public void onServiceDisconnected(ComponentName name) {
Log.w(LogTAG,"onServiceDisconnected ");
mRunningAppName = null;
}
};
private getRunningAppName mRunningAppName = null;
C、声明服务:
<service android:name="sensorService"/>
这样,就可以在这个类中像使用实例mRunningAppName;