导航菜单

页面标题

页面副标题

自健身 v3.3.4 - UartService.java 源代码

正在查看: 自健身 v3.3.4 应用的 UartService.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.mu.gymtrain.service;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import com.blankj.utilcode.util.LogUtils;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.mu.gymtrain.R;
import com.mu.gymtrain.Utils.FinalTools;
import com.mu.gymtrain.Utils.PreferenceUtils;
import com.mu.gymtrain.Utils.ToastUtil;
import com.mu.gymtrain.service.BluetoothScanUtil;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class UartService extends Service implements BluetoothScanUtil.BlueCallBack {
    public static final String ACTION_DATA_AVAILABLE = "com.nordicsemi.nrfUART.ACTION_DATA_AVAILABLE";
    public static final String ACTION_GATT_CONNECTED = "com.nordicsemi.nrfUART.ACTION_GATT_CONNECTED";
    public static final String ACTION_GATT_DISCONNECTED = "com.nordicsemi.nrfUART.ACTION_GATT_DISCONNECTED";
    public static final String ACTION_GATT_SERVICES_DISCOVERED = "com.nordicsemi.nrfUART.ACTION_GATT_SERVICES_DISCOVERED";
    public static final String DEVICE_DOES_NOT_SUPPORT_UART = "com.nordicsemi.nrfUART.DEVICE_DOES_NOT_SUPPORT_UART";
    public static final String EXTRA_DATA = "com.nordicsemi.nrfUART.EXTRA_DATA";
    public static final int MSG_STEPS_ING = 1;
    private static final int STATE_CONNECTED = 2;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_DISCONNECTED = 0;
    private static final String TAG = "UartService";
    private BluetoothScanUtil bluetoothScanUtil;
    private Context context;
    private byte[] data;
    private DataCallBack dataCallBack;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private BluetoothGattCallback mGattCallback;
    private TimerTask scantask;
    public float walk;
    public float weight;
    public static final UUID SERVICE_UUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
    public static final UUID READ_CHAR_UUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
    public static final UUID RX_CHAR_UUID = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    public static final UUID S_SERVICE_UUID = UUID.fromString("0000181B-0000-1000-8000-00805f9b34fb");
    public static final UUID S_READ_CHAR_UUID = UUID.fromString("00002A9C-0000-1000-8000-00805f9b34fb");
    public static final UUID CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    private static final Timer scantimer = new Timer();
    private int mConnectionState = 0;
    private boolean isconn = true;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int i = msg.what;
            if (i == 0) {
                int i2 = msg.arg1;
                if (i2 == 0) {
                    Boolean bool = (Boolean) msg.obj;
                    if (bool == null || !bool.booleanValue()) {
                        UartService.this.dataCallBack.getState(3);
                        return;
                    }
                    return;
                }
                if (i2 == 1) {
                    UartService uartService = UartService.this;
                    ToastUtil.showShort(uartService, uartService.getResources().getString(R.string.manage_device_cant_conn_blue));
                    return;
                } else {
                    if (i2 != 2) {
                        return;
                    }
                    UartService uartService2 = UartService.this;
                    ToastUtil.showShort(uartService2, uartService2.getResources().getString(R.string.msg_no_open_bluetooth));
                    return;
                }
            }
            if (i == 3) {
                UartService.this.dataCallBack.getState(0);
                return;
            }
            if (i == 4) {
                UartService.this.dataCallBack.getState(1);
                UartService.this.timedOff();
                return;
            }
            if (i != 5) {
                switch (i) {
                    case 8:
                        UartService.this.scanBleDevice();
                        return;
                    case 9:
                        if (UartService.this.n == 2) {
                            UartService.this.eEnableTXNotification();
                            break;
                        }
                        break;
                    case 10:
                        break;
                    default:
                        return;
                }
                UartService.this.eEnableTXNotification();
                return;
            }
            UartService.this.dataCallBack.getState(2);
        }
    };
    private boolean isSuoding = false;
    private int n = 1;
    private String old_str = "";
    private final IBinder mBinder = new LocalBinder();
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (FinalTools.BROADCAST_ACTION_USER_CONNECTION.equals(action)) {
                UartService.this.isconn = true;
                UartService.this.mHandler.sendEmptyMessage(8);
                LogUtils.i(new Object[]{"请求连接"});
            } else if (FinalTools.BROADCAST_ACTION_USER_DISCONNECTION.equals(action)) {
                UartService.this.isconn = false;
                UartService.this.mHandler.removeMessages(8);
                UartService.this.close("mBroadcastReceiver");
            }
        }
    };

    public interface DataCallBack {
        void dataCallBack(byte[] data, boolean isLast);

        void getState(final int state);
    }

    public void timedOff() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.context = getApplicationContext();
        blueCallBack();
        this.bluetoothScanUtil = new BluetoothScanUtil(this, this, this.mHandler);
        registerBoradcastReceiver();
        System.out.println("后台服务开启");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        close("UartService onDestroy");
        unregisterReceiver(this.mBroadcastReceiver);
        PreferenceUtils.getInstance().saveBoolean(FinalTools.CONNECTION_STATE, false);
        sendBroadcast(new Intent(FinalTools.BROADCAST_ACTION_DISCONNECTION_DEVICE));
        System.out.println("后台服务停止");
    }

    private void blueCallBack() {
        try {
            this.mGattCallback = new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                    if (newState == 2) {
                        UartService.this.mConnectionState = 2;
                        UartService.this.mBluetoothGatt.discoverServices();
                        Log.i(UartService.TAG, "------连接成功");
                        PreferenceUtils.getInstance().saveBoolean(FinalTools.CONNECTION_STATE, true);
                        LogUtils.i(new Object[]{"蓝牙连接成功,但是还没发现服务"});
                        UartService.this.mHandler.removeMessages(9);
                        UartService.this.mHandler.sendEmptyMessageDelayed(9, AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS);
                        return;
                    }
                    if (newState == 0) {
                        if (UartService.this.isconn) {
                            UartService.this.mHandler.sendEmptyMessage(5);
                        }
                        Log.i(UartService.TAG, "断线重连了");
                        UartService.this.close("blueCallBack");
                        UartService.this.mConnectionState = 0;
                        PreferenceUtils.getInstance().saveBoolean(FinalTools.CONNECTION_STATE, false);
                    }
                }

                @Override
                public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                    LogUtils.i(new Object[]{"status   = " + status});
                    if (status == 0) {
                        Log.w(UartService.TAG, "mBluetoothGatt = " + UartService.this.mBluetoothGatt);
                        UartService.this.enableTXNotification();
                        UartService.this.mHandler.sendEmptyMessage(4);
                        LogUtils.i(new Object[]{"连接成功,发现服务"});
                        UartService.this.mHandler.removeMessages(9);
                        UartService.this.mHandler.sendEmptyMessageDelayed(9, AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS);
                        PreferenceUtils.getInstance().saveBoolean(FinalTools.CONNECTION_STATE, true);
                        return;
                    }
                    Log.w(UartService.TAG, "onServicesDiscovered received: " + status);
                }

                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                    if (status == 0) {
                        UartService.this.broadcastUpdate(UartService.ACTION_DATA_AVAILABLE, characteristic);
                    }
                }

                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    UartService.this.broadcastUpdate(UartService.ACTION_DATA_AVAILABLE, characteristic);
                }
            };
        } catch (NoClassDefFoundError unused) {
            ToastUtil.showShort(this, this.context.getString(R.string.manage_device_cant_conn_blue));
        }
    }

    public void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
        byte[] bArr;
        byte[] value = characteristic.getValue();
        this.data = value;
        StringBuilder sb = new StringBuilder(value.length);
        for (byte b : this.data) {
            sb.append(String.format("%02X", Byte.valueOf(b)));
        }
        if (sb.toString() != null && sb.toString().equals(this.old_str)) {
            this.n++;
        } else {
            this.n = 1;
        }
        this.old_str = sb.toString();
        System.out.println(sb.toString() + "--" + this.isSuoding);
        if (this.isSuoding) {
            if (this.n == 3) {
                this.dataCallBack.dataCallBack(this.data, true);
                close("broadcastUpdate");
                return;
            }
            return;
        }
        DataCallBack dataCallBack = this.dataCallBack;
        if (dataCallBack != null && (bArr = this.data) != null) {
            if (this.n == 3) {
                this.mHandler.sendEmptyMessage(10);
                this.n = 1;
            } else {
                dataCallBack.dataCallBack(bArr, false);
            }
        }
        this.mHandler.removeMessages(9);
        this.mHandler.sendEmptyMessageDelayed(9, AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS);
    }

    public void writeRXCharacteristic(final byte[] data) {
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt == null) {
            return;
        }
        BluetoothGattService service = bluetoothGatt.getService(SERVICE_UUID);
        StringBuilder sb = new StringBuilder(data.length);
        for (byte b : data) {
            Log.i(TAG, "" + ((int) b));
            sb.append(String.format("%02X", Byte.valueOf(b)));
        }
        System.out.println("下发:" + sb.toString());
        if (this.mBluetoothGatt == null) {
            close("writeRXCharacteristic");
            return;
        }
        if (service == null) {
            close("writeRXCharacteristic");
            return;
        }
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(RX_CHAR_UUID);
        if (characteristic == null) {
            close("writeRXCharacteristic");
            return;
        }
        characteristic.setValue(data);
        Log.d(TAG, "write TXchar - status=" + this.mBluetoothGatt.writeCharacteristic(characteristic));
    }

    public class LocalBinder extends Binder {
        public LocalBinder() {
        }

        public UartService getService() {
            return UartService.this;
        }

        public void setCallBack(DataCallBack dataCallBack) {
            UartService.this.dataCallBack = dataCallBack;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "Service  unbind");
        return this.mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "Service  onUnbind");
        close("onUnbind");
        return super.onUnbind(intent);
    }

    public boolean connect(BluetoothDevice device) {
        BluetoothAdapter bluetoothAdapter = this.bluetoothScanUtil.getBluetoothAdapter();
        this.mBluetoothAdapter = bluetoothAdapter;
        if (bluetoothAdapter == null || device == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }
        if (this.mBluetoothDeviceAddress != null && device.getAddress().equals(this.mBluetoothDeviceAddress) && this.mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.重复");
            this.mBluetoothGatt.disconnect();
            if (!this.mBluetoothGatt.connect()) {
                return false;
            }
            this.mConnectionState = 2;
            PreferenceUtils.getInstance().saveBoolean(FinalTools.CONNECTION_STATE, true);
            this.mHandler.sendEmptyMessage(4);
            LogUtils.i(new Object[]{"连接成功  connect"});
            this.mHandler.removeMessages(9);
            this.mHandler.sendEmptyMessageDelayed(9, AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS);
            return true;
        }
        this.mBluetoothGatt = device.connectGatt(this, false, this.mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        this.mBluetoothDeviceAddress = device.getAddress();
        this.mConnectionState = 1;
        return true;
    }

    public void disconnect() {
        BluetoothGatt bluetoothGatt;
        if (this.mBluetoothAdapter == null || (bluetoothGatt = this.mBluetoothGatt) == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
        } else {
            bluetoothGatt.disconnect();
            this.mBluetoothGatt.close();
        }
    }

    public void close(String from) {
        LogUtils.i(new Object[]{"关闭蓝牙 = " + from});
        if (this.mBluetoothGatt == null) {
            return;
        }
        Log.w(TAG, "  mBluetoothGatt closed");
        this.mBluetoothDeviceAddress = null;
        this.mBluetoothGatt.disconnect();
        this.mBluetoothGatt.close();
        this.mBluetoothGatt = null;
        this.mConnectionState = 0;
        BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
        if (bluetoothAdapter != null) {
            bluetoothAdapter.cancelDiscovery();
            this.mBluetoothAdapter = null;
        }
        System.gc();
    }

    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        BluetoothGatt bluetoothGatt;
        if (this.mBluetoothAdapter == null || (bluetoothGatt = this.mBluetoothGatt) == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
        } else {
            bluetoothGatt.readCharacteristic(characteristic);
        }
    }

    public void enableTXNotification() {
        BluetoothGattService service;
        BluetoothGattCharacteristic characteristic;
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt == null || (service = bluetoothGatt.getService(SERVICE_UUID)) == null || (characteristic = service.getCharacteristic(READ_CHAR_UUID)) == null) {
            return;
        }
        this.mBluetoothGatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCCD);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        this.mBluetoothGatt.writeDescriptor(descriptor);
    }

    public void eEnableTXNotification() {
        BluetoothGattService service;
        BluetoothGattCharacteristic characteristic;
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt == null || (service = bluetoothGatt.getService(S_SERVICE_UUID)) == null || (characteristic = service.getCharacteristic(S_READ_CHAR_UUID)) == null) {
            return;
        }
        this.mBluetoothGatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCCD);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        this.mBluetoothGatt.writeDescriptor(descriptor);
        this.isSuoding = true;
    }

    public List<BluetoothGattService> getSupportedGattServices() {
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt == null) {
            return null;
        }
        return bluetoothGatt.getServices();
    }

    public void scanBleDevice() {
        this.isSuoding = false;
        String string = PreferenceUtils.getInstance().getString(FinalTools.DEVICEADDRESS, (String) null);
        if (this.isconn) {
            if (this.mConnectionState == 2) {
                ToastUtil.showShort(this, getResources().getString(R.string.msg_connected));
                return;
            }
            if (string != null) {
                BluetoothAdapter bluetoothAdapter = this.bluetoothScanUtil.getBluetoothAdapter();
                this.mBluetoothAdapter = bluetoothAdapter;
                BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(string);
                if (remoteDevice != null) {
                    System.out.println("chong-------device_adress--" + remoteDevice.getAddress());
                    this.mHandler.sendEmptyMessage(3);
                    connect(remoteDevice);
                    return;
                }
            }
            this.bluetoothScanUtil.scanLeDevice(true, string);
        }
    }

    public void registerBoradcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(FinalTools.BROADCAST_ACTION_USER_CONNECTION);
        intentFilter.addAction(FinalTools.BROADCAST_ACTION_USER_DISCONNECTION);
        registerReceiver(this.mBroadcastReceiver, intentFilter);
    }

    @Override
    public void blueCallBack(ScanBleDevice scanBleDevice) {
        final BluetoothDevice device = scanBleDevice.getDevice();
        LogUtils.i(new Object[]{"扫描到的蓝牙名地址:" + device.getName() + "--" + device.getAddress() + "  " + scanBleDevice.getRssi()});
        this.mHandler.sendEmptyMessage(3);
        this.mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (UartService.this.mConnectionState == 2 || !UartService.this.isconn) {
                    return;
                }
                UartService.this.connect(device);
            }
        });
    }

    private void refreshDeviceCache(final BluetoothGatt gatt) {
        try {
            Method method = gatt.getClass().getMethod("refresh", new Class[0]);
            if (method != null) {
                ((Boolean) method.invoke(gatt, new Object[0])).booleanValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}