关于Android Service 防止多次unbind导致crash

发现ServiceConnection的onServiceDisconnectedConnected方法总是不会调用,不管你调用unbind 或者 stop的方法,都不能回调到onServiceDisconnectedConnected,心想service断开连接时候应该调用的啊。。。而且,我想用一个布朗值去代表服务是否断开,只能在这里赋值更改,导致unbind时候不能判断服务是否已经unbind,程序就崩溃了。。。。。
直接查官方文档:

public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
            mBoundService = null;
            Toast.makeText(Binding.this, R.string.local_service_disconnected,
                    Toast.LENGTH_SHORT).show();
 }

 总之就是,这个方法是在服务异常断开连接时候才会被调用,通常是进程crash时候,所以不管你是否调用stop/unbind 都不会回调这个接口。
而且当进程被kill掉,在locat中也难以看到回调这个方法,因为service也是和我们的app通常在一个进程。

注意官方给的源码实例中选择用mShouldUnbind 在bind时候赋值的方式来防止多次unbind

void doBindService() {
        // Attempts to establish a connection with the service.  We use an
        // explicit class name because we want a specific service
        // implementation that we know will be running in our own process
        // (and thus won't be supporting component replacement by other
        // applications).
        if (bindService(new Intent(Binding.this, LocalService.class),
                mConnection, Context.BIND_AUTO_CREATE)) {
            mShouldUnbind = true;
        } else {
            Log.e("MY_APP_TAG", "Error: The requested service doesn't " +
                    "exist, or this client isn't allowed access to it.");
        }
    }

    void doUnbindService() {
        if (mShouldUnbind) {
            // Release information about the service's state.
            unbindService(mConnection);
            mShouldUnbind = false;
        }
    }

 所以遇到问题还是乖乖看官方文档吧,自己写半天还是在坑里给自己挖坑。。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值