BLE服务静态问题

时间:2018-10-05 17:32:25

标签: android service bluetooth-lowenergy

我正在尝试实现一项服务来控制通过BLE传入的数据。我有一个名为BluetoothDiscovery的活动,我在其中尝试显示附近的设备并选择连接到该设备。以我的理解,该服务应控制所有涉及BLE的非UI行为,例如绑定到活动时的接收和分发数据。然后,我将第二个Activity绑定到服务,以便能够访问实时数据以供使用。

我当前的问题是在BluetoothDiscovery与服务有关静态方法的争论之间。谁能帮助我了解如何实施这项服务?

BluetoothDiscover

import android.annotation.SuppressLint;
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.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;
import no.nordicsemi.android.support.v18.scanner.ScanFilter;
import no.nordicsemi.android.support.v18.scanner.ScanResult;
import no.nordicsemi.android.support.v18.scanner.ScanSettings;

public class BluetoothDiscovery extends AppCompatActivity {

    private String DEVICE = "Bluetooth Device";
    private String COMMS = "Bluetooth Communication";
    private int REQUEST_ENABLE_BT = 5;

    //private BluetoothAdapter mBluetoothAdapter;
//    private BluetoothLeScannerCompat scanner;
//    private ScanSettings settings;
//    private UUID baseUUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // service UUID
//    private UUID txUUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // TX UUID characteristic
//    private UUID rxUUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // RX UUID characteristic
//    private ScanFilter scanFilter;
//    private BluetoothDevice device, mdevice;
//    private BluetoothGatt mGatt;
    private boolean mScanning = false;
    private ArrayList<deviceShowFormat> foundDevices = new ArrayList<>();
    formattingAdapter BTadapter;

    private ArrayList<String> xData = new ArrayList<>();
    private ArrayList<String> yData = new ArrayList<>();
    private ArrayList<String> zData = new ArrayList<>();

    Button scanButton;
    TextView fancyWords;
    ListView deviceList;

    Intent ServeBruh = new Intent(BluetoothDiscovery.this, BLEControl.class);

    public BluetoothLeScannerCompat scanner;


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

        startService(ServeBruh);

//        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
//        mBluetoothAdapter = manager.getAdapter();


//
        scanner = BluetoothLeScannerCompat.getScanner();


//        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
//        mBluetoothAdapter = manager.getAdapter();

        //mBluetoothAdapter.getBluetoothLeScanner();
        //mBluetoothAdapter.getDefaultAdapter();//.getBluetoothLeScanner();

        scanButton = findViewById(R.id.scanButt);
        scanButton.setText(getString(R.string.notScanning));

        fancyWords = findViewById(R.id.discoverText);
        fancyWords.setText(getString(R.string.nonScanTitle));

        deviceList = findViewById(R.id.deviceList);
//        BTadapter = new formattingAdapter(BluetoothDiscovery.this, foundDevices);
//        deviceList.setAdapter(BTadapter);


//        scanner = BluetoothLeScannerCompat.getScanner();
//
//        settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).setReportDelay(500).build();
//
//        scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(baseUUID)).build();

        //scanner.startScan(Arrays.asList(scanFilter), settings, mScanCallback);

        deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                BLEControl.scanner.stopScan(BLEControl.mScanCallback);
                scanButton.setText(getString(R.string.notScanning));

                deviceShowFormat mBTDevice = foundDevices.get(i);

                BluetoothDevice Device = mBTDevice.get_device();
                String deviceName = mBTDevice.get_device_name();
                String deviceAddress = mBTDevice.get_device_address();

                Log.i(DEVICE, "Selected device: " + Device.toString());
                Log.i(DEVICE, "Selected device name: " + deviceName);
                Log.i(DEVICE, "Selected device address: " + deviceAddress);

                BLEControl.connect(deviceAddress);

            }
        });
    }

    public void toggleScan(View view){
        mScanning = !mScanning;

        if(mScanning){
            scanner.startScan(BLEControl.mScanCallback); //Arrays.asList(scanFilter) null, settings,
            scanButton.setText(getString(R.string.scanInProgress));
            fancyWords.setText(getString(R.string.ScanTitle));

        } else {
            scanner.stopScan(BLEControl.mScanCallback);
            scanButton.setText(getString(R.string.notScanning));
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();

        stopService(ServeBruh);
    }
}

服务

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.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;
import no.nordicsemi.android.support.v18.scanner.ScanCallback;
import no.nordicsemi.android.support.v18.scanner.ScanFilter;
import no.nordicsemi.android.support.v18.scanner.ScanResult;
import no.nordicsemi.android.support.v18.scanner.ScanSettings;

public class BLEControl extends Service {

    private static String TAG = "BLE SERVICE";
    public static BluetoothAdapter mBluetoothAdapter;
    public static BluetoothLeScannerCompat scanner;
    private ScanSettings settings;
    private UUID baseUUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // service UUID
    //    private UUID txUUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // TX UUID characteristic
//    private UUID rxUUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // RX UUID characteristic
    private ScanFilter scanFilter;
    private static BluetoothDevice device, mdevice;
    public static BluetoothGatt mGatt;
    private boolean mScanning = false;

    private static ArrayList<deviceShowFormat> foundDevices = new ArrayList<>();
    formattingAdapter BTadapter = new formattingAdapter(this, foundDevices);
    // needs to be static???


    private static String DEVICE = "Bluetooth Device";

    public static ArrayList<String> xData = new ArrayList<>();
    public static ArrayList<String> yData = new ArrayList<>();
    public static ArrayList<String> zData = new ArrayList<>();


    public BLEControl() {
        String HELLO = "Hello";
    }


    @Override
    public void onCreate() {
        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = manager.getAdapter();

        scanner = BluetoothLeScannerCompat.getScanner();

        settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).setReportDelay(500).build();

        scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(baseUUID)).build();


        //scanner.startScan(mScanCallback);

        //scanner.startScan(Arrays.asList(scanFilter), settings, mScanCallback);
    }

    @Override
    public void onDestroy() {
        mGatt.disconnect();
        mGatt.close();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startID) {

        Log.i("LocalService", "Received start id " + startID + ": " + intent);

        return super.onStartCommand(intent, flags, startID);
    }


    public static final ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            Log.i("onScanResult", "device detected");

            device = result.getDevice();
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();

            Log.i(DEVICE, "Scanned device: " + device.toString());
            Log.i(DEVICE, "Scanned device name: " + deviceName);
            Log.i(DEVICE, "Scanned device address: " + deviceAddress);

            foundDevices.add(new deviceShowFormat(device, deviceName, deviceAddress));
            BTadapter.notifyDataSetChanged(); // Y U SO DIFFICULT
        }
    };


    public static BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);

            Log.i("onConnectionStateChange", "State Changed from: " + status + " to " + newState);
            gatt.discoverServices();
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);

            Log.i("onServicesDiscovered", "Hey, we found a service");

            List<BluetoothGattService> services = gatt.getServices();
            Log.i("SERVICE", "Services: " + services.toString());

            BluetoothGattCharacteristic characteristic = services.get(4).getCharacteristics().get(0);
            //gatt.getService(baseUUID).getCharacteristic(rxUUID);

            gatt.setCharacteristicNotification(characteristic, true);


            List<BluetoothGattDescriptor> describeMe = characteristic.getDescriptors();
            Log.i("DESCRIPTORS", "Descriptors: " + describeMe.toString());


            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(describeMe.get(0).getUuid());
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);

            Log.i("ByeSERVICESDISCOVERED", "that");
        }


        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Log.i("onCharacteristicChanged", "Entered");

            final byte[] dataInput = characteristic.getValue();

            String butt = new String(dataInput);

            Log.i("Message", "" + butt);

            int whereX, whereY, whereZ;

            if (butt.contains("X")) {
                whereX = butt.indexOf("X");
                try {
                    xData.add(butt.substring(whereX, whereX + 8));
                } catch (Exception e) {
                    Log.d("X at end", "" + whereX);
                }

            } // Array ring counter looper

            if (butt.contains("Y")) {
                whereY = butt.indexOf("Y");
                try {
                    yData.add(butt.substring(whereY, whereY + 8));
                } catch (Exception e) {
                    Log.d("Y at end", "" + whereY);
                }

            }

            if (butt.contains("Z")) {
                whereZ = butt.indexOf("Z");
                try {
                    zData.add(butt.substring(whereZ, whereZ + 8));
                } catch (Exception e) {
                    Log.d("Z at end", "" + whereZ);
                }

            }

            Log.i("X data", "" + xData);
            Log.i("Y data", "" + yData);
            Log.i("Z data", "" + zData);

//            Intent intent = new Intent(BluetoothDiscovery.this, ShowData.class);
//            startActivity(intent);


            Log.i("onCharacteristicChanged", "Bye");
        }

    };

    public boolean connect(final String address) {
        final boolean returnVal;

        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            returnVal = false;
        } else {
            Log.d(TAG, "Trying to create a new connection.");
            mBluetoothAdapter.getRemoteDevice(address);
            mGatt = device.connectGatt(this, false, mGattCallback);
            //mBluetoothAddress = address;
            //setConnectionState(State.CONNECTING, true);
            returnVal = true;
        }

        return returnVal;
    }
}

0 个答案:

没有答案