功能:扫描周围蓝牙设备,获取设备名称、地址等,并添加到ListView上面,并能够获取选中项,显示设备地址
搜索蓝牙
if (!mBluetoothAdapter.isDiscovering())//扫描蓝牙
{
mBluetoothAdapter.startDiscovery();//扫描蓝牙设备,没有返回false
}
取消搜索
if (mBluetoothAdapter.isDiscovering())//是否处于扫描过程中
{
mBluetoothAdapter.cancelDiscovery();//取消蓝牙扫描,没有开启返回false
}
PS:如果只有搜索蓝牙,搜索的设备会显示的系统的蓝牙搜索栏中。
XML中添加控件ListView,ID:ListView1
获取搜索到的设备,需要自己添加广播来获取发现的设备
protected void onCreate(Bundle savedInstanceState) 中添加
IntentFilter discoveryFilter = new IntentFilter();
discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);//搜索到设备
discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始搜索
discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索结束
registerReceiver(mReceiver, discoveryFilter);
//添加搜索响应广播
//发现设备广播
private BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) // 发现设备
{
// 从Intent中获取设备对象
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
add = device.getName() + "," + add; //搜索设备名称
add1 = device.getAddress() + "," + add1; //搜索设备地址
//解决重复扫描的问题
String[] a = add.split(",");
String[] b = add1.split(",");
String sss = a[0];
String sss1 = b[0];
int j = 0;
for(int i = 1; i < a.length; i++)
{
j = i - 1;
while(!a[i].equals(a[j]))
{
if(j > 0)
{
j--;
}
else if(j == 0)
{
sss = a[i] + "," + sss;
break;
}
}
}
j = 0;
for(int i = 1; i < b.length; i++)
{
j = i - 1;
while(!b[i].equals(b[j]))
{
if(j > 0)
{
j--;
}
else if(j == 0)
{
sss1 = b[i] + "," + sss1;
break;
}
}
}
add = sss;
add1 = sss1;
String[] all = add.split(",");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,all);
ListView listView5 = (ListView)findViewById(R.id.ListView1);
listView5.setAdapter(adapter);//重复扫描
}
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))//搜索开始
{
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("搜索蓝牙设备中......");
progressDialog.setCancelable(false);
progressDialog.setButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
progressDialog.dismiss();
if (mBluetoothAdapter.isDiscovering())//是否处于扫描过程中
{
mBluetoothAdapter.cancelDiscovery();//取消蓝牙扫描,没有开启返回false
}
}
});
progressDialog.show();
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(13000);
progressDialog.dismiss();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))//搜索结束
{
toast("搜索结束!");
}
}
};
添加一个按钮响应搜索设备,搜索开始后会在ListView控件中显示搜索到的设备名称,一直到搜索结束。
添加ListView单击的监听器
//设置选项点击的监听器
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
String[] al = add1.split(",");
toast(al[arg2]);//显示地址
}
});