开发中一般不需要第三方直接编写连接我们服务的代码,我们需要提供一个Service的管理类
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.os.RemoteException;
import android.util.Log;
public class TestServiceManager {
private static final String TAG = "TestServiceManager";
private TestCallBack mTestCallBack;
private Context mContext;
private ITestService testBinder;
private volatile static TestServiceManager instance;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG,"===onServiceConnected==="+(service != null));
if (service!=null){
testBinder = ITestService.Stub.asInterface(service);
if (mTestCallBack!=null){
mTestCallBack.success(testBinder);
}
try {
service.linkToDeath(deathRecipient,0);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG,"===onServiceDisconnected===");
if (mTestCallBack!=null){
mTestCallBack.fail();
}
testBinder = null;
}
};
//死亡代理,断开重连
private IBinder.DeathRecipient deathRecipient=new IBinder.DeathRecipient() {
@Override
public void binderDied() {
Log.i(TAG,"===binderDied===");
if(testBinder!=null){
testBinder.asBinder().unlinkToDeath(deathRecipient,0);
testBinder=null;
bind();
}
}
};
private TestServiceManager() {
}
//实现单例
public static TestServiceManager getInstance() {
if (instance == null) {
synchronized (TestServiceManager.class) {
if (instance == null) {
instance = new TestServiceManager();
}
}
}
return instance;
}
public void init(Context context, TestCallBack testCallBack) {
Log.i(TAG,"===init===");
mTestCallBack = testCallBack;
mContext = context;
bind();
}
//连接服务
private void bind(){
Log.i(TAG,"===bind===");
if (mContext!=null){
Intent intent = new Intent("com.test");
intent.setPackage("com.test");
mContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
}
public void release(){
Log.i(TAG,"===release===");
mContext.unbindService(serviceConnection);
testBinder = null;
instance = null;
}
public ITestService getTestBinder() {
return testBinder;
}
public interface TestCallBack {
void success(ITestService service);
void fail();
}
}