Java 在foregroud Service android中连接蓝牙存在问题
在这段代码中,它在后台工作,但在前台不工作。我想添加一个前台服务,实现蓝牙连接和GATT连接。请帮我输入这个密码 在这段代码中,它在后台工作,但在前台不工作。我想添加一个前台服务,实现蓝牙连接和GATT连接。请帮我输入这个密码 在这段代码中,它在后台工作,但在前台不工作。我想添加一个前台服务,实现蓝牙连接和GATT连接。请帮我输入这个密码Java 在foregroud Service android中连接蓝牙存在问题,java,android,Java,Android,在这段代码中,它在后台工作,但在前台不工作。我想添加一个前台服务,实现蓝牙连接和GATT连接。请帮我输入这个密码 在这段代码中,它在后台工作,但在前台不工作。我想添加一个前台服务,实现蓝牙连接和GATT连接。请帮我输入这个密码 在这段代码中,它在后台工作,但在前台不工作。我想添加一个前台服务,实现蓝牙连接和GATT连接。请帮我输入这个密码 public static BluetoothGattCharacteristic colorCharacteristic; private HashMap&
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,所以不能发送使能数据");
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;
}
公共静态蓝牙特征颜色特征;
私有HashMap gattHash=新HashMap();
私人BluetoothManager BluetoothManager;
私人蓝牙适配器mBluetoothAdapter;
私人蓝牙GATT mGatt;
私有布尔不连通;
@凌驾
公共IBinder onBind(意向){
initAdapter();
返回kBinder;
}
@凌驾
公共布尔onUnbind(意图){
返回super.onUnbind(intent);
}
私有字符串地址;
public void initBluetoothDevice(最终字符串地址、最终上下文){
this.address=地址;
最终BluetoothDevice=mBluetoothAdapter.getRemoteDevice(地址);
if(isConnected())返回;
如果(空!=mGatt){
刷新设备缓存(mGatt);
mGatt=null;
}
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.M){
mGatt=device.connectGatt(上下文,false,blegatcallback,BluetoothDevice.TRANSPORT_LE);
}否则{
mGatt=device.connectGatt(上下文,false,bleGattCallback);
}
如果(mGatt==null){
System.out.println(device.getAddress()+“gatt为空”);
}
//this.mContext=上下文;
//重新连接(true);
}
公共字符串getDeviceAddress(){
返回此地址;
}
private BluetoothAdapter.LeScanCallback mLeScanCallback=新建BluetoothAdapter.LeScanCallback(){
@凌驾
仅限公共无效扫描(最终蓝牙设备、最终int rssi、,
最终字节[]扫描记录){
if(device.getAddress().equals(address)和&Math.abs(rssi)<90){
});
}
}
};
私有void initAdapter(){
如果(bluetoothManager==null){
bluetoothManager=(bluetoothManager)getSystemService(Context.BLUETOOTH\u服务);
如果(bluetoothManager==null){
返回;
}
}
mBluetoothAdapter=bluetoothManager.getAdapter();
}
公共空间断开连接(){
需要重新连接=错误;
如果(mGatt==null)
返回;
mGatt.disconnect();
}
公共无效断开连接(字符串地址){
ArrayList gatts=新的ArrayList();
对于(蓝牙gatt:arrayGatts){
if(gatt!=null&&gatt.getDevice().getAddress().equals(address)){
加上(关贸总协定);
//关贸总协定;
关贸总协定关闭();
//关贸总协定=零;
}
}
总协定;
}
公共类LocalBinder扩展了Binder{
公共服务getService(){
返回BleService.this;
}
}
私人int发现计数;
私有对象ob=新对象();
私有BluetoothGattCallback bleGattCallback=新的BluetoothGattCallback(){
@凌驾
连接状态更改(蓝牙gatt、国际关税及贸易总协定状态、,
int新闻状态){
字符串操作=null;
Log.i(标记“onConnectionStateChange:status”+status+“newstate”+newstate);
if(newState==BluetoothProfile.STATE\u CONNECTED){
如果(状态==133){
mGatt.close();
mGatt=null;
返回;
}
动作=动作与关贸总协定连接;
试一试{
关贸总协定。发现服务();
}捕获(例外e){
//TODO:处理异常
e、 printStackTrace();
}
}else if(newState==BluetoothProfile.STATE\u已断开连接){
断开连接=错误;
Log.i(标记“onConnectionStateChange:”+操作\u GATT\u断开连接);
如果(mGatt!=null){
mGatt.close();
mGatt=null;
}
队列。清除();
如果(!NeedReconnect){
动作=动作与关贸总协定断开;
广播更新(行动);
}
}
}
@凌驾
发现服务上的公共无效(Bluetooth gatt,int状态){
//如果(mGatt==null)
//返回;
如果(状态==蓝牙GATT.GATT\U成功){
字符串地址=gatt.getDevice().getAddress();
字符串名称=mBluetoothAdapter.getRemoteDevice(地址)
.getName();
setCharacteristicNotification(真);
/*if(gatt!=null&&Build.VERSION.SDK\u INT>=Build.VERSION\u code.LOLLIPOP){
关贸总协定请求MTU(512);
}否则{
setCharacteristicNotification(真);
}*/
发现计数=0;
}否则{
//mGatt=null;
Log.w(“服务发现”,“OnServicesDiscovery已收到:”
+地位);
}
}
@凌驾
更改后的公共状态(蓝牙gatt、国际关税及贸易总协定、国际mtu、国际状态){
super.onmtu(关贸总协定、多边贸易联盟、地位);
if(BluetoothGatt.GATT_SUCCESS==状态){
setCharacteristicNotification(真);
}否则{
关贸总协定(153);
}
}
公共性质无效阅读(蓝牙gatt,
android.bluetooth.BluetoothGattCharacteristic特征,
int状态){
如果(状态==蓝牙GATT.GATT\U成功){
广播更新(行动数据可用,特征,gatt
.getDevice().getAddress());
}否则{
}
}
公共空间