功能分类:工具
支持平台:Android
运行环境:Eclipse
开发语言:Java
开发工具:Eclipse
源码大小:1.37MB
源码下载地址:http://down.51cto.com/data/1984795
源码简介
该Demo主要是兼容了支持BLE的Android4.3终端设备之间的蓝牙通信。
主要功能包含:
1、蓝牙的开启、关闭;
2、周围蓝牙开启设备的搜索、建连
3、成功建连后,通过蓝牙向对方发送消息。
注:要想观察发送/接收消息,必须双方都安装了此APP。
源码运行截图
APP打开蓝牙时,对蓝牙的请求
蓝牙通信
搜索周围安装该APP的蓝牙设备
设置蓝牙的某些属性值
源码片段
- 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();
}
// Adapter for holding devices found through scanning.
- private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<bluetoothdevice> mLeDevices;
- private LayoutInflater mInflator;
- public LeDeviceListAdapter() {
super();
- mLeDevices = new ArrayList<bluetoothdevice>();
mInflator = DeviceScanActivity.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 i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
- // General ListView optimization code.
if (view == null) {
- view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
- viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
- view.setTag(viewHolder);
} else {
- viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
- final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
- viewHolder.deviceName.setText(deviceName);
else
- viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
- }
}
// Device scan callback.
- 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() {
mLeDeviceListAdapter.addDevice(device);
- mLeDeviceListAdapter.notifyDataSetChanged();
}
- });
}
- };
</bluetoothdevice></bluetoothdevice>