Android ble peripheral 连接后自动断开

发布于 2021-11-29 15:46:46 字数 11788 浏览 649 评论 2

使用android手机作为蓝牙4.0的外围设备,用iOS上的lightblue进行测试;
能正常扫描到android的蓝牙,但一连接马上就断开了,根据log确实是连接成功后再断开的,但我没有进行断开连接的操作啊;
测试的手机是nexus6p,6.0系统;


不知道有哪位有android的蓝牙外围开发经验,还请赐教;


贴一下代码

public class MainActivity extends AppCompatActivity {

    public static final String TAG="bleperipheral";
    private  static boolean D = true;

    public static String serviceUUID = "039AFFF0-2C94-11E3-9E06-0002A5D5C51B";
    public static String characteristicUUID = "039AFFA1-2C94-11E3-9E06-0002A5D5C51B";

    private BluetoothManager mBluetoothManager;

    private BluetoothGattServer server;
    private BluetoothGattCharacteristic character;
    private BluetoothGattService service;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeAdvertiser mBluetoothLeAdvertiser;
    private  static Context mContext;
    private Button mStartButton, mStopButton, mSendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        mStartButton = (Button) findViewById(R.id.start);
        mStartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mBluetoothLeAdvertiser.startAdvertising(createAdvSettings(true, 0), createAdvertiseData(), mAdvertiseCallback);
                if (D) {
                    Toast.makeText(mContext, "Start Advertising", Toast.LENGTH_LONG).show();
                    Log.e(TAG,"Start Advertising");
                }
            }
        });

        mStopButton = (Button) findViewById(R.id.stop);
        mStopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                stopAdvertise();
                if (D) {
                    Toast.makeText(mContext, "Stop Advertising", Toast.LENGTH_LONG).show();
                    Log.e(TAG, "Stop Advertising");
                }
            }
        });

        mSendButton = (Button) findViewById(R.id.send);
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                character.setValue("send test".getBytes());
            }
        });

        init();

        setServer();
    }

    private void init(){
        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
            finish();
        }

        mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();

        if(mBluetoothAdapter ==  null){
            Toast.makeText(this, R.string.bluetooth_not_supported, Toast.LENGTH_LONG).show();
            finish();
        }

        mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
        if(mBluetoothLeAdvertiser == null){
            Toast.makeText(this, "the device not support peripheral", Toast.LENGTH_SHORT	).show();
            Log.e(TAG, "the device not support peripheral");
            finish();
        }
    }

    private void setServer() {
        character = new BluetoothGattCharacteristic(
                UUID.fromString(characteristicUUID),
                BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE,
                BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE);

        service = new BluetoothGattService(UUID.fromString(serviceUUID),
                BluetoothGattService.SERVICE_TYPE_PRIMARY);

        service.addCharacteristic(character);

        server = mBluetoothManager.openGattServer(this,
                new BluetoothGattServerCallback() {

                    @Override
                    public void onConnectionStateChange(BluetoothDevice device,
                                                        int status, int newState) {
                        super.onConnectionStateChange(device, status, newState);
                        Log.d("Chris", "onConnectionStateChange:"+device+"-=-=-=-="+status+"-=-=-=-"+newState);
                    }

                    @Override
                    public void onServiceAdded(int status,
                                               BluetoothGattService service) {
                        super.onServiceAdded(status, service);
                        Log.d("Chris", "service added");
                    }

                    @Override
                    public void onCharacteristicReadRequest(
                            BluetoothDevice device, int requestId, int offset,
                            BluetoothGattCharacteristic characteristic) {
                        super.onCharacteristicReadRequest(device, requestId,
                                offset, characteristic);
                        Log.d("Chris", "onCharacteristicReadRequest");
                    }

                    @Override
                    public void onCharacteristicWriteRequest(
                            BluetoothDevice device, int requestId,
                            BluetoothGattCharacteristic characteristic,
                            boolean preparedWrite, boolean responseNeeded,
                            int offset, byte[] value) {
                        super.onCharacteristicWriteRequest(device, requestId,
                                characteristic, preparedWrite, responseNeeded,
                                offset, value);
                        Log.d("Chris", "onCharacteristicWriteRequest");
                    }

                    @Override
                    public void onDescriptorReadRequest(BluetoothDevice device,
                                                        int requestId, int offset,
                                                        BluetoothGattDescriptor descriptor) {
                        super.onDescriptorReadRequest(device, requestId,
                                offset, descriptor);
                        Log.d("Chris", "onDescriptorReadRequest");
                    }

                    @Override
                    public void onDescriptorWriteRequest(
                            BluetoothDevice device, int requestId,
                            BluetoothGattDescriptor descriptor,
                            boolean preparedWrite, boolean responseNeeded,
                            int offset, byte[] value) {
                        super.onDescriptorWriteRequest(device, requestId,
                                descriptor, preparedWrite, responseNeeded,
                                offset, value);
                        Log.d("Chris", "onDescriptorWriteRequest");
                    }

                    @Override
                    public void onExecuteWrite(BluetoothDevice device,
                                               int requestId, boolean execute) {
                        super.onExecuteWrite(device, requestId, execute);
                        Log.d("Chris", "onExecuteWrite");
                    }

                });

        server.addService(service);
    }

    private AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            if (settingsInEffect != null) {
                Log.d(TAG, "onStartSuccess TxPowerLv=" + settingsInEffect.getTxPowerLevel() + " mode=" + settingsInEffect.getMode()
                        + " timeout=" + settingsInEffect.getTimeout());
            } else {
                Log.e(TAG, "onStartSuccess, settingInEffect is null");
            }
            Log.e(TAG,"onStartSuccess settingsInEffect" + settingsInEffect);

        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            if(D) 	Log.e(TAG,"onStartFailure errorCode" + errorCode);

            if(errorCode == ADVERTISE_FAILED_DATA_TOO_LARGE){
                if(D){
                    Toast.makeText(mContext, R.string.advertise_failed_data_too_large, Toast.LENGTH_LONG).show();
                    Log.e(TAG,"Failed to start advertising as the advertise data to be broadcasted is larger than 31 bytes.");
                }
            }else if(errorCode == ADVERTISE_FAILED_TOO_MANY_ADVERTISERS){
                if(D){
                    Toast.makeText(mContext, R.string.advertise_failed_too_many_advertises, Toast.LENGTH_LONG).show();
                    Log.e(TAG,"Failed to start advertising because no advertising instance is available.");
                }
            }else if(errorCode == ADVERTISE_FAILED_ALREADY_STARTED){
                if(D){
                    Toast.makeText(mContext, R.string.advertise_failed_already_started, Toast.LENGTH_LONG).show();
                    Log.e(TAG,"Failed to start advertising as the advertising is already started");
                }
            }else if(errorCode == ADVERTISE_FAILED_INTERNAL_ERROR){
                if(D){
                    Toast.makeText(mContext, R.string.advertise_failed_internal_error, Toast.LENGTH_LONG).show();
                    Log.e(TAG,"Operation failed due to an internal error");
                }
            }else if(errorCode == ADVERTISE_FAILED_FEATURE_UNSUPPORTED){
                if(D){
                    Toast.makeText(mContext, R.string.advertise_failed_feature_unsupported, Toast.LENGTH_LONG).show();
                    Log.e(TAG,"This feature is not supported on this platform");
                }
            }
        }
    };

    /** create AdvertiseSettings */
    public static AdvertiseSettings createAdvSettings(boolean connectable, int timeoutMillis) {
        AdvertiseSettings.Builder mSettingsbuilder = new AdvertiseSettings.Builder();
        mSettingsbuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
        mSettingsbuilder.setConnectable(connectable);
        mSettingsbuilder.setTimeout(timeoutMillis);
        mSettingsbuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
        AdvertiseSettings mAdvertiseSettings = mSettingsbuilder.build();
        if(mAdvertiseSettings == null){
            if(D){
                Toast.makeText(mContext, "mAdvertiseSettings == null", Toast.LENGTH_LONG).show();
                Log.e(TAG,"mAdvertiseSettings == null");
            }
        }
        return mAdvertiseSettings;
    }
    public static AdvertiseData createAdvertiseData(){
        AdvertiseData.Builder    mDataBuilder = new AdvertiseData.Builder();
        mDataBuilder.addServiceUuid(ParcelUuid.fromString(serviceUUID));
        mDataBuilder.setIncludeDeviceName(true);
        AdvertiseData mAdvertiseData = mDataBuilder.build();
        if(mAdvertiseData==null){
            if(D){
                Toast.makeText(mContext, "mAdvertiseSettings == null", Toast.LENGTH_LONG).show();
                Log.e(TAG,"mAdvertiseSettings == null");
            }
        }

        return mAdvertiseData;
    }

    private void stopAdvertise() {
        if (mBluetoothLeAdvertiser != null) {
            mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
//            mBluetoothLeAdvertiser = null;
        }
    }

}




如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清晨说ぺ晚安 2021-11-30 13:28:35

但连其他蓝牙,比如ti的蓝牙模块就没问题

风透绣罗衣 2021-11-30 00:46:34

iOS 使用节能版蓝牙模块的问题吧

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文