自定义类 继承Service
内部类继承Binder,内写需要的方法(注意一般Service在UI线程,别左耗时操作)
例子如下:
public class localService extends Service {
private finalI Binder mBinder=new localBinder();
public class localBinder extends Binder {
public intCompare(inta,intb){
returna>b?a:b;
}
localServicegetService(){
return localService.this;
}
}
@Nullable
@Override
publicIBinderonBind(Intent intent) {
returnmBinder;
}
}
要在使用的Activity中实例化Connection(匿名内部类)
获取到Binder之后就可以调用方法了。
private Service Connection connection=new ServiceConnection() {
@Override
public void onService Disconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name,IBinder service) {
myBinder= (localService.localBinder) service;
myBinder.Compare(a,b);
}
};
绑定,绑定之后就能用Binder
Intentbind Intent =new Intent(this,localService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
记得在AndroidManifest 里添加
AIDL 跨进程服务
service
public classMyServiceextendsService {
private final staticStringTAG="ALIPaySeivice";
public classlocalBinderextendsBinder {
MyServicegetService(){
returnMyService.this;
}
}
private finalMAIDL.StubmBinder=newMAIDL.Stub(){
@Override
public intCompare(inta, intb)throwsRemoteException {
returna>b?a+1:b+1;
}
@Override
public voidPAY()throwsRemoteException {
Log.v(TAG,"购买");
}
};
AndroidManifest:
service (格式原因没加"<")
android:name=".MyService"
android:process=":remote">
/service>
uses-permission android:name="com.neo1946.remoteservice.MAIDL"/>
调用:用TAG调用
private ServiceConnection connection2=new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name,IBinder service) {
myAIDLService= MAIDL.Stub.asInterface(service);
try{
username.setText("Other service");
inta =Integer.parseInt(et1.getText().toString());
intb = Integer.parseInt(et2.getText().toString());
password.setText(myAIDLService.Compare(a,b)+"");
}catch(RemoteException e) {
e.printStackTrace();
}
}
};
Intent intent2 = new Intent();intent2.setAction("com.neo1946.remoteservice.MAIDL");intent2.setPackage("com.neo1946.remoteservice");bindService(intent2, connection2, BIND_AUTO_CREATE);
参考文章:http://blog.csdn.net/guolin_blog/article/details/9797169?from=singlemessage