Android 自定义按钮类内的解除绑定服务

Android 自定义按钮类内的解除绑定服务,android,service,Android,Service,我在解除服务绑定时遇到问题 我创建了一个自定义按钮的类。所以这个类扩展了Button类 在这个类上,我用一个远程服务绑定我的类来更新按钮状态 public class CustomButton extends Button implements View.OnClickListener { private Activity mActivity; public CustomButton(Context context) { super(contex

我在解除服务绑定时遇到问题

我创建了一个自定义按钮的类。所以这个类扩展了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[…]”

我理解这个错误,但由于我没有在桌面或onDestroy上收到“信号”,我无法解除服务绑定


你知道我如何修复它吗?

你必须重写这个方法

protected void onDetachedFromWindow() {
}

使用此方法取消注册/解除绑定远程服务

在活动/片段中执行服务绑定/解除绑定如果解除绑定成功,为什么不在暂停时解除绑定服务,然后在恢复时解除绑定服务?因为我正在处理库项目,并将自定义按钮添加到另一个应用程序中:我绑定我的服务直接通过这个自定义按钮类。所以我没有onPause和onResume方法