步骤#1。要求实施界面ServiceConnection
:
public class ServiceBinding<T extends ParentService<T>> implements ServiceConnection {
public T bindedService;
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// Warning: Type safety: Unchecked cast from IBinder to ChatService<T>.LocalBinder
bindedService = ((T.LocalBinder) service).getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
}
}
第2步。然后家长服务将如下所示:
public abstract class ParentService<T extends ParentService<T>> extends Service {
public class LocalBinder extends Binder {
public T getService() {
return (T) T.this; // Warning: Unchecked cast from ChatService<T> to T
}
};
}
问题:这样的解决方案是否可以接受?
如何正确实施ServiceConnection
?
答案 0 :(得分:0)
你可以这样实现 -
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
service = binder.getService();
boundVal = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
boundVal = false;
}
};
boundVal是&#39; unbindservice&#39;的触发器。传递带有连接的boundval作为参数。
一旦建立或断开客户端 - 服务器连接,就会调用 onServiceConnected()
和onServiceDisconnected()
。对于onServiceConnected()
方法,将传递一个IBinder
对象,其中包含客户端与服务交互所需的信息。
干杯!