Android Service解绑后再次绑定以及绑定服务出现空指针问题

版权声明:本文为博主原创文章,转载请注明原帖地址,谢谢 https://blog.csdn.net/AooMiao/article/details/59526561

1——今天在做一个应用的前台功能的关闭时出现了这么一个问题,获取了ibinder实例后,调用在Service编写的方法出现了空指针问题。代码如下

private UpdateService.mBinder mBinder;

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBinder = (UpdateService.mBinder) iBinder;
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
         
        }
    };
    
intent_service_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {//Switch按钮
                if(b){
                    Intent intent = new Intent(WeatherAcitivity.this,UpdateService.class);
                    bindService(intent,connection,BIND_AUTO_CREATE);
                    mBinder.stopIntentService();
                }else {
                    unbindService(connection);
                }
            }
        });

后来百度了才知道绑定服务是异步的,所以会出现还没绑定完服务就开始调用方法,当然会报空指针,解决方法是把调用方法的代码放到onServiceConnected()里面去,等到绑定结束才开始调用服务里的方法

2——然后又在做前台服务的重新开启时遇到了问题,就是调用unbind()方法时候,在onServiceDisconnected()没调用里面的逻辑。不得其解,只能把关闭开启前台功能逻辑全部写在Service的生命周期方法里去,以下是代码

public boolean onUnbind(Intent intent) {
        Log.d("me", "解绑");//要看到前台
        startForeground(1,notification);
        return true;
    }

    @Override
    public void onRebind(Intent intent) {
        //Log.d("me", "重新绑定");
        stopForeground(true);
        super.onRebind(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        //初次绑定
        stopForeground(true);
        return mBinder;
    }


值得注意的是刚开始,我只重写了onBind()和unBind()方法,其实如果解绑了一次重新绑定是不会调用onBind()方法的,重新绑定会调用onRebind()方法,并且前提条件是unBind()方法返回ture。这时候重新绑定onRebind()才会被调用,这是要注意的。

猜你喜欢

转载自blog.csdn.net/AooMiao/article/details/59526561
今日推荐