接下来 要做的 就是扫描 BLE设备了
// 扫描BLE设备
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressLint("NewApi")
private void scanLeDevice(final boolean enable) {
if (enable) {
// 停止扫描后一个预定义的扫描周期。
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
setProgressBarIndeterminateVisibility(false); // 标题栏进度条
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
setProgressBarIndeterminateVisibility(true);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
setProgressBarIndeterminateVisibility(false);
}
invalidateOptionsMenu();
}
// Device scan callback. 设备扫描回调
@SuppressLint("NewApi")
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() {
myAdapter.addDevice(device);
myAdapter.notifyDataSetChanged();
}
});
}
};
按demo 来说 要把扫描到的列表,呈现在listview上 ,我把我自己写的ListView的适配器的代码也奉上
private class MyAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public MyAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = MainActivity.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() {
// TODO Auto-generated method stub
return mLeDevices.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mLeDevices.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
* convertView的好处就是不用为所有数据项均生成view对象 比如数据项100个
* 屏幕只能显示10个,那么只需要返回10个view对象(可能更多),然后修改view对象显示内容(如文字或图片等), reuse
* view对象,优化
*/
ViewHolder holder;
if (convertView == null) {
Log.i("null", " " + position);
holder = new ViewHolder();
convertView = mInflator.inflate(R.layout.lv_item, null);
holder.deviceName = (TextView) convertView
.findViewById(R.id.lv_item_tv_1);
holder.deviceAddress = (TextView) convertView
.findViewById(R.id.lv_item_tv_2);
convertView.setTag(holder);
} else {
Log.i("not-null", " " + position);
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mLeDevices.get(position);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
holder.deviceName.setText(deviceName);
else
holder.deviceName.setText("未知设备");
holder.deviceAddress.setText(device.getAddress());
return convertView;
}
}