解开服务时遇到问题
我创建了一个自定义按钮的类。所以这个类扩展了Button类。
在这个类中,我将我的类与远程服务绑定以更新按钮状态。
public class CustomButton extends Button implements View.OnClickListener {
private Activity mActivity;
public CustomButton(Context context) {
super(context);
init(context, null);
}
private void init(Context context, AttributeSet attrs) {
if (context instanceof Activity) {
this.mActivity = (Activity) context;
Intent intent = new Intent(mActivity, CustomService.class);
final IRemoteCustomServiceCallback callback = new IRemoteCustomServiceCallback.Stub() {
@Override
public void stateChanged(boolean state) throws RemoteException {
Log.i("stateChanged", "New state is " + String.valueOf(state));
setAvailableMode(state);
}
@Override
public IBinder asBinder() {
return this;
}
};
ServiceConnection remoteConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
mService = IRemoteCustomService.Stub.asInterface(service);
try {
int test = mService.getPid();
Log.i("test", String.valueOf(test));
mService.registerCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
try {
mService.unregisterCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
mService = null;
}
};
boolean state = mActivity.bindService(intent, remoteConnection, 0);
}
问题是:当我关闭应用程序时,我收到一个错误:" [...]已泄露最初绑定的ServiceConnection [...]"
我理解这个错误,但因为我没有收到"信号" onStop或onDestroy,我无法取消绑定我的服务。
你知道我怎么解决它吗?
答案 0 :(得分:0)
您必须覆盖方法
protected void onDetachedFromWindow() {
}
使用此方法取消注册/取消绑定远程服务