android开发BLE蓝牙时蓝牙连接不稳定会自动断开重连

搜索、通讯均正常,只是连接不正常
public void onCreate(){
super.onCreate();
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, "没有蓝牙", Toast.LENGTH_SHORT).show();
stopSelf();
return;
}
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Toast.makeText(this, "不支持BLE", Toast.LENGTH_SHORT).show();
stopSelf();
return;
}
}
@Override
public void onDestroy(){
if(mBluetoothGatt != null){
mBluetoothGatt.close();
}
mBluetoothGatt = null;
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent){
if(mBluetoothGatt != null){
mBluetoothGatt.close();
}
mBluetoothGatt = null;
return super.onUnbind(intent);
}

// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                String str = device.getName() + "|" + device.getAddress();
                LogUtil.d(TAG, "get BluetoothDevice.ACTION_FOUND:" + str);
                sendLocalBroadcast(ACTION_SCAN_FOUND,str);
            }
        };

public void startScan(){
    Handler mHandler = new Handler();
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            stopScan();
        }
    },SCAN_PERIOD );
    LogUtil.d(TAG, "get startScan");
    mScanning = true;
    mBluetoothAdapter.startLeScan(mLeScanCallback);
    sendLocalBroadcast(ACTION_SCAN_STARTED);
}
public void stopScan(){
    if(mScanning){
        LogUtil.d(TAG, "get stopScan");
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        sendLocalBroadcast(ACTION_SCAN_FINISHED);
    }
}

public void findService(List<BluetoothGattService> gattServices)
{
    Log.i(TAG, "Count is:" + gattServices.size());
    for (BluetoothGattService gattService : gattServices)
    {
        Log.i(TAG, gattService.getUuid().toString());
        Log.i(TAG, UUID_SERVICE.toString());
        if(gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString()))
        {
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            Log.i(TAG, "Count is:" + gattCharacteristics.size());
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics)
            {
                if(gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_NOTIFY.toString()))
                {
                    Log.i(TAG, gattCharacteristic.getUuid().toString());
                    Log.i(TAG, UUID_NOTIFY.toString());
                    mNotifyCharacteristic = gattCharacteristic;
                    setCharacteristicNotification(gattCharacteristic, true);
                    //broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                    return;
                }
            }
        }
    }
}

// Implements callback methods for GATT events that the app cares about.  For example,
// connection change and services discovered.
//设备连接
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        Log.i(TAG, "oldStatus=" + status + " NewStates=" + newState);
        if(status == BluetoothGatt.GATT_SUCCESS)
        {

            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_CONNECTED;
                sendLocalBroadcast(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_DISCONNECTED;
                mBluetoothGatt.close();
                mBluetoothGatt = null;
                Log.i(TAG, "Disconnected from GATT server.");
                sendLocalBroadcast(intentAction);
            }
        }
    }

   //发现服务
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.w(TAG, "onServicesDiscovered received: " + status);
            findService(gatt.getServices());
        } else {
            if(mBluetoothGatt.getDevice().getUuids() == null)
                Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            byte[] bufRecv = characteristic.getValue();
            int nRecv = bufRecv.length;
            if(nRecv > 1024 + nReadPtr - nRecvPtr)
                nRecv = 1024 + nReadPtr - nRecvPtr;
            if(nRecv + nRecvPtr <= 1024){
                System.arraycopy(bufRecv, 0, bRecv, nRecvPtr, nRecv);
                nRecvPtr += nRecv;
            }
            else{
                System.arraycopy(bufRecv, 0, bRecv, nRecvPtr, 1024-nRecvPtr);
                System.arraycopy(bufRecv, 1024-nRecvPtr, bRecv, 0, nRecv - (1024-nRecvPtr));
                nRecvPtr = nRecv - (1024 - nRecvPtr);
            }
            sendLocalBroadcast(ACTION_DATA_RECV);
        }
    }
    /**
     *  发送数据后的回调
     * @param gatt
     * @param characteristic
     * @param status
     */
    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                                      int status)
    {
        Log.e(TAG, "OnCharacteristicWrite");
    }

    @Override
    public void onDescriptorRead(BluetoothGatt gatt,
                                 BluetoothGattDescriptor bd,
                                 int status) {
        Log.e(TAG, "onDescriptorRead");
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        byte[] bufRecv = characteristic.getValue();
        int nRecv = bufRecv.length;
        if(nRecv > 1024 + nReadPtr - nRecvPtr)
            nRecv = 1024 + nReadPtr - nRecvPtr;
        if(nRecv + nRecvPtr <= 1024){
            System.arraycopy(bufRecv, 0, bRecv, nRecvPtr, nRecv);
            nRecvPtr += nRecv;
        }
        else{
            System.arraycopy(bufRecv, 0, bRecv, nRecvPtr, 1024-nRecvPtr);
            System.arraycopy(bufRecv, 1024-nRecvPtr, bRecv, 0, nRecv - (1024-nRecvPtr));
            nRecvPtr = nRecv - (1024 - nRecvPtr);
        }
        sendLocalBroadcast(ACTION_DATA_RECV);
        Log.e(TAG, "onCharacteristicChanged");
    }


    @Override
    public void onDescriptorWrite(BluetoothGatt gatt,
                                  BluetoothGattDescriptor bd,
                                  int status) {
        Log.e(TAG, "onDescriptorWrite");
    }

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int a, int b)
    {
        Log.e(TAG, "onReadRemoteRssi");
    }

    @Override
    public void onReliableWriteCompleted(BluetoothGatt gatt, int a)
    {
        Log.e(TAG, "onReliableWriteCompleted");
    }
    @Override
    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
        Log.e(TAG, "onMtuChanged");

    }
};


public boolean connect(final String address){
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    // We want to directly connect to the device, so we are setting the autoConnect
    // parameter to false.
    if(mBluetoothGatt != null)
    {
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

    Log.d(TAG, "Trying to create a new connection.");
    return true;
}

public void disconnect(){
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.disconnect();
}

@Override
public int read(byte[] data) {
    int readLen = data.length;
    int bufLen;
    int retLen;
    if(nRecvPtr >= nReadPtr)
        bufLen = nRecvPtr - nReadPtr;
    else
        bufLen = nRecvPtr + 1024 - nReadPtr;
    if(readLen <= bufLen)
        retLen = readLen;
    else
        retLen = bufLen;
    if(nReadPtr + retLen < 1024){
        System.arraycopy(bRecv, nReadPtr, data,0,retLen);
        nReadPtr += retLen;
    }
    else{
        System.arraycopy(bRecv, nReadPtr, data, 0, 1024-nReadPtr);
        System.arraycopy(bRecv, 0, data, 1024-nReadPtr, retLen - (1024-nReadPtr));
        nReadPtr = retLen-(1024-nReadPtr);
    }
    return retLen;
}

public byte[] write(byte[] data){
    mNotifyCharacteristic.setValue(data/*strValue.getBytes()*/);
    mBluetoothGatt.writeCharacteristic(mNotifyCharacteristic);
    LogUtil.i(TAG, "12154123164512332465451218451231654561233545612");
    //return data.length;
    return data;
}
public final void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    byte[] value = characteristic.getValue();
    Log.d(TAG, "onCharacteristicChanged: " + value);
    String s0 = Integer.toHexString(value[0] & 0xFF);
    String s = Integer.toHexString(value[1] & 0xFF);
    Log.d(TAG, "onCharacteristicChanged: " + s0 + "、" + s);
    for (byte b : value) {
        Log.d(TAG, "onCharacteristicChanged: " + b);
    }

}

/**
 * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
 * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
 * callback.
 *
 * @param characteristic The characteristic to read from.
 */
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.readCharacteristic(characteristic);
}

/**
 * Enables or disables notification on a give characteristic.
 *
 * @param characteristic Characteristic to act on.
 * @param enabled If true, enable notification.  False otherwise.
 */
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

/*
// This is specific to Heart Rate Measurement.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
*/
}

/**
 * Retrieves a list of supported GATT services on the connected device. This should be
 * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
 *
 * @return A {@code List} of supported services.
 */
public List<BluetoothGattService> getSupportedGattServices() {
    if (mBluetoothGatt == null) return null;

    return mBluetoothGatt.getServices();
}

}