Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中为BLE设备设置蜂鸣器_Android_Bluetooth Lowenergy - Fatal编程技术网

如何在Android中为BLE设备设置蜂鸣器

如何在Android中为BLE设备设置蜂鸣器,android,bluetooth-lowenergy,Android,Bluetooth Lowenergy,我开发了一款Android应用程序,可以使用BLE设备进行操作,如图所示 该应用程序可以扫描和连接设备,但我不能写正确的特征蜂鸣器标签。我编写此代码就是为了做到这一点: private static final int ALERT_HIGH = 2; private static final UUID IMMEDIATE_ALERT_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); private static fi

我开发了一款Android应用程序,可以使用BLE设备进行操作,如图所示

该应用程序可以扫描和连接设备,但我不能写正确的特征蜂鸣器标签。我编写此代码就是为了做到这一点:

private static final int ALERT_HIGH = 2;
private static final UUID IMMEDIATE_ALERT_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
private static final UUID ALERT_LEVEL_UUID = UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb");
public void ClickButton(View view)
{
    BluetoothGattService alertService = mGatt.getService(IMMEDIATE_ALERT_UUID);
    if (alertService == null)
    {
        Toast.makeText(this, "Immediate Alert service not found!", 1)
                .show();
        return;
    }
    BluetoothGattCharacteristic alertLevel = alertService.getCharacteristic(ALERT_LEVEL_UUID);
    if (alertLevel == null)
    {
        Toast.makeText(this, "Alert Level charateristic not found!", 1)
                .show();
        return;
    }
    alertLevel.setValue(ALERT_HIGH, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
    mGatt.writeCharacteristic(alertLevel);
}
但是没有任何行动发生

我在play store上发现了这个应用程序,它运行良好,可以对ble设备进行蜂鸣器操作

我不知道我的代码在哪里丢失了;我不知道我以前使用的函数或与此设备连接的初始化中存在的问题

最后,这是我使用的完整代码

public class MainActivity extends Activity {
    private BluetoothAdapter mBluetoothAdapter;
    private int REQUEST_ENABLE_BT = 1;
    private Handler mHandler;
    private static final long SCAN_PERIOD = 1000*60;
    private BluetoothLeScanner mLEScanner;
    private ScanSettings settings;
    private List<ScanFilter> filters;
    private BluetoothGatt mGatt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mHandler = new Handler();
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "BLE Not Supported",
                Toast.LENGTH_SHORT).show();
        finish();
    }
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

}

@Override
protected void onResume() {
    super.onResume();
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
            settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            filters = new ArrayList<ScanFilter>();
        }
        scanLeDevice(true);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
        scanLeDevice(false);
    }
}

@Override
protected void onDestroy() {
    if (mGatt == null) {
        return;
    }
    mGatt.close();
    mGatt = null;
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_ENABLE_BT) {
        if (resultCode == Activity.RESULT_CANCELED) {
            //Bluetooth not enabled.
            finish();
            return;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void scanLeDevice(final boolean enable) {
    if (enable) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT < 21) {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } else {
                    mLEScanner.stopScan(mScanCallback);

                }
            }
        }, SCAN_PERIOD);
        if (Build.VERSION.SDK_INT < 21) {
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mLEScanner.startScan(filters, settings, mScanCallback);
        }
    } else {
        if (Build.VERSION.SDK_INT < 21) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        } else {
            mLEScanner.stopScan(mScanCallback);
        }
    }
}


private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        Log.i("callbackType", String.valueOf(callbackType));
        Log.i("result", result.toString());
        BluetoothDevice btDevice = result.getDevice();
        String DeviceAddress = btDevice.getAddress().trim();            
        if(DeviceAddress.equals("FF:FF:00:01:05:07"))
            connectToDevice(btDevice);
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        for (ScanResult sr : results) {
            Log.i("ScanResult - Results", sr.toString());
        }
    }

    @Override
    public void onScanFailed(int errorCode) {
        Log.e("Scan Failed", "Error Code: " + errorCode);
    }
};

private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi,
                                 byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("onLeScan", device.toString());
                        connectToDevice(device);
                    }
                });
            }
        };

String address;
public void connectToDevice(BluetoothDevice device) {
    if (mGatt == null) {
        address = device.getAddress();
        mGatt = device.connectGatt(this, false, gattCallback);
    }
}

private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        Log.i("onConnectionStateChange", "Status: " + status);
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                Log.i("gattCallback", "STATE_CONNECTED");
                mGatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                Log.e("gattCallback", "STATE_DISCONNECTED");
                break;
            default:
                Log.e("gattCallback", "STATE_OTHER");
        }

    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        List<BluetoothGattService> services = gatt.getServices();
        Log.i("onServicesDiscovered", services.toString());
        gatt.readCharacteristic(services.get(1).getCharacteristics().get
                (0));
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic
                                             characteristic, int status) {
        Log.i("onCharacteristicRead", characteristic.toString());
        gatt.disconnect();
    }
};

private static final int ALERT_HIGH = 2;
private static final UUID IMMEDIATE_ALERT_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
private static final UUID ALERT_LEVEL_UUID = UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb");
public void ClickButton(View view)
{
    BluetoothGattService alertService = mGatt.getService(IMMEDIATE_ALERT_UUID);
    if (alertService == null)
    {
        Toast.makeText(this, "Immediate Alert service not found!", 1)
                .show();
        return;
    }
    BluetoothGattCharacteristic alertLevel = alertService.getCharacteristic(ALERT_LEVEL_UUID);
    if (alertLevel == null)
    {
        Toast.makeText(this, "Alert Level charateristic not found!", 1)
                .show();
        return;
    }
    alertLevel.setValue(ALERT_HIGH, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
    mGatt.writeCharacteristic(alertLevel);
}
}
公共类MainActivity扩展活动{
私人蓝牙适配器mBluetoothAdapter;
私有整数请求\启用\ BT=1;
私人经理人;
专用静态最终长扫描周期=1000*60;
私人蓝牙扫描仪;
私人扫描设置;
私有列表过滤器;
私人蓝牙GATT mGatt;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler=新处理程序();
如果(!getPackageManager().hasSystemFeature(PackageManager.FEATURE\u BLUETOOTH\u LE)){
Toast.makeText(不支持此选项),
吐司。长度(短)。show();
完成();
}
最终BluetoothManager BluetoothManager=
(BluetoothManager)getSystemService(Context.BLUETOOTH\u服务);
mBluetoothAdapter=bluetoothManager.getAdapter();
}
@凌驾
受保护的void onResume(){
super.onResume();
if(mBluetoothAdapter==null | |!mBluetoothAdapter.isEnabled()){
Intent enablebintent=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(启用BTIntent、请求\启用\ BT);
}否则{
如果(Build.VERSION.SDK_INT>=21){
mLEScanner=mBluetoothAdapter.getBluetoothLeScanner();
设置=新的ScanSettings.Builder()
.setScanMode(扫描设置.SCAN\u模式\u低延迟)
.build();
过滤器=新的ArrayList();
}
扫描设备(真实);
}
}
@凌驾
受保护的void onPause(){
super.onPause();
if(mBluetoothAdapter!=null&&mBluetoothAdapter.isEnabled()){
扫描设备(假);
}
}
@凌驾
受保护的空onDestroy(){
如果(mGatt==null){
返回;
}
mGatt.close();
mGatt=null;
super.ondestory();
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
if(requestCode==请求启用){
if(resultCode==Activity.RESULT\u已取消){
//蓝牙未启用。
完成();
返回;
}
}
super.onActivityResult(请求代码、结果代码、数据);
}
专用void扫描设备(最终布尔启用){
如果(启用){
mHandler.postDelayed(新的Runnable(){
@凌驾
公开募捐{
if(Build.VERSION.SDK_INT<21){
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}否则{
mLEScanner.stopScan(mScanCallback);
}
}
},扫描周期);
if(Build.VERSION.SDK_INT<21){
mBluetoothAdapter.startedscan(mLeScanCallback);
}否则{
mLEScanner.startScan(过滤器、设置、mScanCallback);
}
}否则{
if(Build.VERSION.SDK_INT<21){
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}否则{
mLEScanner.stopScan(mScanCallback);
}
}
}
private ScanCallback mScanCallback=新建ScanCallback(){
@凌驾
公共void onScanResult(int callbackType、ScanResult){
Log.i(“callbackType”,String.valueOf(callbackType));
Log.i(“result”,result.toString());
BluetoothDevice btDevice=result.getDevice();
字符串DeviceAddress=btDevice.getAddress().trim();
如果(设备地址等于(“FF:FF:00:01:05:07”))
连接到设备(BTD设备);
}
@凌驾
public void onBatchScanResults(列出结果){
用于(扫描结果sr:结果){
Log.i(“ScanResult-Results”,sr.toString());
}
}
@凌驾
公共无效OnScan失败(内部错误代码){
Log.e(“扫描失败”,“错误代码:”+错误代码);
}
};
私有BluetoothAdapter.LeScanCallback mLeScanCallback=
新的BluetoothAdapter.LeScanCallback(){
@凌驾
public void onLeScan(最终蓝牙设备,int rssi,
字节[]扫描记录){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Log.i(“onLeScan”,device.toString());
连接到设备(设备);
}
});
}
};
字符串地址;
public void connectToDevice(蓝牙设备){
如果(mGatt==null){
address=device.getAddress();
mGatt=device.connectGatt(this,false,gattCallback);
}
}
私有最终BluetoothGattCallback gattCallback=新BluetoothGattCallback(){
@凌驾
连接状态更改的公共无效(蓝牙gatt gatt、int状态、int新闻状态){
Log.i(“onConnectionStateChange”,“Status:+Status”);
交换机(新闻状态){
案例BluetoothProfile.STATE\u已连接:
Log.i(“gattCallback”、“STATE_CONNECTED”);
mGatt.discoverServices();
打破
案例BluetoothProfile.STATE\u已断开连接:
Log.e(“gattCallback”、“STATE_DISCONNECTED”);
打破
违约:
Log.e(“gattCallback”、“STATE_OTHER”);
}
}
@凌驾
发现服务上的公共无效(Bluetooth gatt,int状态){
List services=gatt.getServices();
Log.i(“OnServicesDiscovery”
    byte[] valToWrite = parseHexStringToBytes("0x0" + alertLevel);
    immediateAlertChar.setValue(valToWrite);
    boolean val = gatt.writeCharacteristic(immediateAlertChar);