bindService执行成功后,低概率出现onServiceConnected没有被调用

本文探讨了在Android中使用bindService方法时遇到的问题:即首次bindService与unbindService操作后,再次bindService虽未报错但onServiceConnected未被调用。文中提供了解决方案,包括检查绑定状态及采用重试机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

============问题描述============


如题。
即第一次bindService->unbindService后,接着再执行bindService
执行完后,从bindService返回结果来看,正常。但是onServiceConnected没有被调用

采用重试的方法,重试5到10次后,绑定成功,具体是
bindService后,判断onServiceConnected是否执行,如果没有执行,先执行unBindService,然后重新执行bindService
直到onServiceConnected被成功执行
关键代码如下
Client


    //getBluetoothAvrcpCtl由一activity调用

    public static synchronized BluetoothAvrcpCtl getBluetoothAvrcpCtl(Context mContext) {

        if(sAvrcpCtl == null)

        {

            sAvrcpCtl = new BluetoothAvrcpCtl(mContext);

            Log.e(TAG,"getBluetoothAvrcpCtl sAvrcpCtl:"+ sAvrcpCtl);

        }

        return sAvrcpCtl;

    }



    public BluetoothAvrcpCtl(Context mContext) {

        context = mContext;

        if(mService == null)

        {

            if (!context.bindService(new Intent(IBluetoothAvrcpCtl.class.getName()), mConnection, 0)) {

               Log.e(TAG, "Could not bind to Bluetooth AVRCP CT Service");

            }

        }

    }

	

    private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {

            Log.d(TAG, "Proxy object connected");

            mService = IBluetoothAvrcpCtl.Stub.asInterface(service);

            notifyServiceBind(true);

        }

        public void onServiceDisconnected(ComponentName className) {

            Log.d(TAG, "Proxy object disconnected");

            notifyServiceBind(false);

            mService = null;

        }

    };

	



    public void closeProxy() {

        if((mCallbacks.isEmpty()) && (mConnection != null)){

           context.unbindService(mConnection);

           sAvrcpCtl = null;

        } else {

           Log.d(TAG, "Either Callback not present or not connected to service");

        }

    }



AIDL文件省略

Service端


   BluetoothAvrcpCtBinder mBinder;

	

    @Override

    public void onCreate() {

        mBinder = new BluetoothAvrcpCtBinder(this);

        ......

    }

    public IBinder onBind(Intent intent) {

        Log.d(TAG,"onBind");

        return mBinder;

    }



XML文件


- <service android:name=".avrcpct.BluetoothAvrcpCtlService">

- <intent-filter>

  <action android:name="android.bluetooth.IBluetoothAvrcpCtl" /> 

  </intent-filter>

  </service>

============解决方案1============


建议debug看看,是不是没有绑定成功,即实际没有bindservice

转载于:https://www.cnblogs.com/meizhenfen42/p/4030391.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值