首页 > 解决方案 > 在前台服务android中连接蓝牙存在问题

问题描述

在这段代码中,它在后台工作,但在前台不工作我想添加一个前台服务,它也实现蓝牙连接和 GATT 连接。请在此代码中的此代码中帮助我,它在后台工作,但不在前台工作我想添加一个前台服务,该服务也实现蓝牙连接和 GATT 连接。请在此代码中的此代码中帮助我,它在后台工作,但不在前台工作我想添加一个前台服务,该服务也实现蓝牙连接和 GATT 连接。请在这段代码中帮助我

public static BluetoothGattCharacteristic colorCharacteristic;
private HashMap<String, BluetoothGatt> gattHash = new HashMap<String, BluetoothGatt>();
private BluetoothManager bluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mGatt;
private boolean isConnected;
@Override
public IBinder onBind(Intent intent) {
    initAdapter();
    return kBinder;
}

@Override
public boolean onUnbind(Intent intent) {

    return super.onUnbind(intent);
}


private String address;


public void initBluetoothDevice(final String address, final Context context) {

    
    this.address = address;
    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if(isConnected())return;
    if(null!=mGatt){
        refreshDeviceCache(mGatt);
        mGatt=null;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        mGatt = device.connectGatt(context, false, bleGattCallback,BluetoothDevice.TRANSPORT_LE);
    } else {
        mGatt = device.connectGatt(context, false, bleGattCallback);
    }
    if (mGatt == null) {
        System.out.println(device.getAddress() + "gatt is null");
    }

    // this.mContext=context;
    // reconnect(true);

}



public String getDeviceAddress() {
    return this.address;
}

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, final int rssi,
                         final byte[] scanRecord) {
        if (device.getAddress().equals(address) && Math.abs(rssi) < 90) {
        });

        }
    }
};


private void initAdapter() {
    if (bluetoothManager == null) {
        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) {
            return;
        }
    }
    mBluetoothAdapter = bluetoothManager.getAdapter();
}

    public void disconnect() {
    NeedReconnect = false;
    if (mGatt == null)
        return;
    mGatt.disconnect();
}


public void disconnect(String address) {
    ArrayList<BluetoothGatt> gatts = new ArrayList<BluetoothGatt>();
    for (BluetoothGatt gatt : arrayGatts) {

        if (gatt != null && gatt.getDevice().getAddress().equals(address)) {
            gatts.add(gatt);
            // gatt.disconnect();
            gatt.close();
            // gatt = null;
        }
    }
    arrayGatts.removeAll(gatts);

}

public class LocalBinder extends Binder {
    public BleService getService() {
        return BleService.this;
    }
}

private int discoverCount;

private Object ob = new Object();
private BluetoothGattCallback bleGattCallback = new BluetoothGattCallback() {
    
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
        String action = null;
        Log.i(TAG, "onConnectionStateChange:  status"+ status+" newstate "+newState);
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            if (status == 133) {
                mGatt.close();
                mGatt = null;
                return;
            }
            action = ACTION_GATT_CONNECTED;
            try {
                gatt.discoverServices();
        
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            isConnected=false;
            Log.i(TAG, "onConnectionStateChange: "+ACTION_GATT_DISCONNECTED);
            if (mGatt != null) {
                mGatt.close();
                mGatt = null;
            }
            queues.clear();
            if(!NeedReconnect) {
                action = ACTION_GATT_DISCONNECTED;
                broadcastUpdate(action);
            }

        }
    }

 
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        // if (mGatt == null)
        // return;
        if (status == BluetoothGatt.GATT_SUCCESS) {
            String address = gatt.getDevice().getAddress();
            String name = mBluetoothAdapter.getRemoteDevice(address)
                    .getName();
            setCharacteristicNotification(true);
          /*  if (gatt != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                gatt.requestMtu(512);
            }else{
                setCharacteristicNotification(true);
            }*/
            discoverCount = 0;
        } else {

            // mGatt = null;
            Log.w("servieDiscovered", "onServicesDiscovered received: "
                    + status);
        }
    }
    @Override
    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
        super.onMtuChanged(gatt, mtu, status);
        if (BluetoothGatt.GATT_SUCCESS == status) {
            setCharacteristicNotification(true);
        }else {
            gatt.requestMtu(153);
        }
    }
   
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     android.bluetooth.BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic, gatt
                    .getDevice().getAddress());
        } else {

        }
    }

    public void onDescriptorWrite(BluetoothGatt gatt,
                                  BluetoothGattDescriptor descriptor, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            //MyLog.i("onDescriptorWrite");
          //  NeedReconnect = true;
            isConnected=true;
        //    SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_ADDRESS,gatt.getDevice().getAddress());
            broadcastUpdate(ACTION_GATT_onDescriptorWrite);
        }else{
            Log.i(TAG, "onDescriptorWrite: failed");
        }
    }

    ;

   
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        android.bluetooth.BluetoothGattCharacteristic characteristic) {


        if (mGatt == null)
            return;
       Log.i(TAG, "onCharacteristicChanged: " + ResolveData.byte2Hex(characteristic.getValue()));

        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic, gatt
                .getDevice().getAddress());
        //  SendData.sendBus(ACTION_DATA_AVAILABLE, characteristic.getValue());
    }

    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            nextQueue();
        } else {
            //  MyLog.i("status" + status);
        }

    }

    ;

};


public boolean refreshDeviceCache(BluetoothGatt gatt) {
    try {
        BluetoothGatt localBluetoothGatt = gatt;
        Method localMethod = localBluetoothGatt.getClass().getMethod(
                "refresh", new Class[0]);
        if (localMethod != null) {
            boolean bool = ((Boolean) localMethod.invoke(
                    localBluetoothGatt, new Object[0])).booleanValue();
            return bool;
        }
    } catch (Exception localException) {
        Log.e("s", "An exception occured while refreshing device");
    }
    return false;
}


private void broadcastUpdate(String action) {
    BleData bleData = new BleData();
    bleData.setAction(action);
    RxBus.getInstance().post(bleData);
    //Intent intent = new Intent(action);
    //sendBroadcast(intent);
}




private void broadcast update(String action,
                             BluetoothGattCharacteristic characteristic, String mac) {

 //   Intent intent = new Intent(action);
    byte[] data = characteristic.getValue();
    BleData bleData = new BleData();
    bleData.setAction(action);
    bleData.setValue(data);
    RxBus.getInstance().post(bleData);

}

public void readValue(BluetoothGattCharacteristic characteristic) {

    if (mGatt == null) return;
    mGatt.readCharacteristic(characteristic);

}




public void writeValue(byte[] value) {
    if (mGatt == null||value==null) return;
    BluetoothGattService service = mGatt.getService(SERVICE_DATA);
    if (service == null) return;
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(DATA_Characteristic);
    if (characteristic == null) return;
    if (value[0] ==(byte) 0x47) {
        NeedReconnect = false;
    }
    characteristic.setValue(value);
    Log.i(TAG, "writeValue: "+ ResolveData.byte2Hex(value));
    mGatt.writeCharacteristic(characteristic);

}





public void setCharacteristicNotification(boolean enable) {
    // TODO Auto-generated method stub
    if (mGatt == null) return;
    BluetoothGattService service = mGatt.getService(SERVICE_DATA);
    if (service == null) return;
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(NOTIY_Characteristic);
    if (characteristic == null) return;
    mGatt.setCharacteristicNotification(characteristic, enable);
    try {
        Thread.sleep(20);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    BluetoothGattDescriptor descriptor = characteristic
            .getDescriptor(NOTIY);
    if (descriptor == null) {
        //MyLog.e("setCharacteristicNotification  descriptor=null,所以不能发送使能数据&quot;);
        return;
    }
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    if (mGatt == null)
        return;
    mGatt.writeDescriptor(descriptor);
}





@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    //MyLog.i("servicer destory");
}


Queue<byte[]> queues=new LinkedList<>();

public void offerValue(byte[]value) {
    queues.offer(value);
}
public void nextQueue(){
    final Queue<byte[]> requests=queues;
    byte[]data=requests!=null?requests.poll():null;
    writeValue(data);
}
public boolean isConnected(){
    return this.isConnected;
}

}

标签: javaandroid

解决方案


推荐阅读