使用 Android 蓝牙 4.0

Working with Android Bluetooth 4.0

我正在开发一个连接到心率传感器并检索值的应用程序。我正在使用 BLE 4.0.

在 google 开发人员门户的帮助下,我能够构建一些代码,但应用程序崩溃了。

请帮帮我。而且我还需要同步我无法正确同步的数据。

代码:

public class PollingTest extends Activity{

public Button btn2;

public static String UUID = "00001101-0000-1000-8000-00805F9B34FB";

public boolean mScanning;
public Handler mHandler;

public LeDeviceListAdapter mLeDeviceListAdapter;
public BluetoothAdapter mBluetoothAdapter;

static final int REQUEST_ENABLE_BT = 1;
public static final long SCAN_PERIOD = 10000;  // Stops scanning after 10 seconds.

@Override
protected void onCreate(Bundle savedInstanceStat){
    super.onCreate(savedInstanceStat);
    setContentView(R.layout.pollingactivity);
    btn2 = (Button)findViewById(R.id.pollB);
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);


    //mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mHandler = new Handler();
            // Use this check to determine whether BLE is supported on the device.  Then you can
            // selectively disable BLE-related features.
            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
                Toast.makeText(getApplicationContext(), "Bluetooth Low Energy is not supported on this Device ", Toast.LENGTH_SHORT).show();
                finish();
            }

            // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
            // BluetoothAdapter through BluetoothManager.
            mBluetoothAdapter = bluetoothManager.getAdapter();

            // Checks if Bluetooth is supported on the device.
            if (mBluetoothAdapter == null) {
                Toast.makeText(getApplicationContext(), "Bluetooth not Supported", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            else {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, 1);
                } else {
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, 1);
                    scanLeDevice(true);
                }
            }
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
        finish();
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

@Override
protected void onPause() {
    super.onPause();
    scanLeDevice(false);
    //mLeDeviceListAdapter.clear();
}

private void scanLeDevice(final boolean enable) {
    if (enable) {
        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                invalidateOptionsMenu();
            }
        }, SCAN_PERIOD);

        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    invalidateOptionsMenu();
}

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() {
                //String macAddress;
                //macAddress = device.getAddress();
                Toast.makeText(getApplicationContext(),device.getAddress(),Toast.LENGTH_LONG).show();
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
                /*switch (device.getAddress().toUpperCase()){
                    case "8C:DE:52:64:8E:D1":
                        Toast.makeText(getApplicationContext(), "First",Toast.LENGTH_LONG).show();
                }*/
            }
        });
    }
};

static class ViewHolder {
    TextView deviceName;
    TextView deviceAddress;
}

private class LeDeviceListAdapter extends BaseAdapter {
    private ArrayList<BluetoothDevice> mLeDevices;
    private LayoutInflater mInflator;

    public LeDeviceListAdapter() {
        super();
        mLeDevices = new ArrayList<>();
        mInflator = PollingTest.this.getLayoutInflater();
    }

    public void addDevice(BluetoothDevice device) {
        if(!mLeDevices.contains(device)) {
            mLeDevices.add(device);
        }
    }

    public BluetoothDevice getDevice(int position) {
        return mLeDevices.get(position);
    }

    public void clear() {
        mLeDevices.clear();
    }

    @Override
    public int getCount() {
        return mLeDevices.size();
    }

    @Override
    public Object getItem(int i) {
        return mLeDevices.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return null;
    }

}

}

我在这里评论了 Resume 和 onPause 方法,因为如果不这样做,应用程序就会崩溃。

日志

我认为 LeScan 中的设备如果由于某些奇怪的原因或其他原因无法 access/receive 蓝牙对象。请帮帮我

谢谢

这是因为DeviceScanActivity.this returns 'null'(那个模式可能没有正确设置),所以当你调用DeviceScanActivity.this.getLayoutInflater()时,你会得到一个NullPointerException,因为您试图在不存在的对象上调用 getLayoutInflater()。