一;点击事件。
1;打开关闭蓝牙;
2;扫描附近蓝牙的点击事件。
二;关于蓝牙设备listView展示
1;listView适配器
2;通过layout找到实例化ListView对象
3;ListView对象加载适配器
4;即可进行点击事件
三;关于ListView适配器(在这个案例中我们使用的是BaseAdapter)
关于适配器的处理核心代码都在getView这个方法中,对于ListView中的Item操作。
四;关于搜索蓝牙设备的广播事件
1;注册广播事件
2;发现广播后的回调方法
3;广播的注销
五;关于传限;特别注意的是第三条,高于4.0的安卓系统则需要加上这条传限
完成代码;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zw.findbluetest.MainActivity" >
<Button
android:id="@+id/openBlue"
android:onClick="openBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="打开蓝牙" />
<Button
android:id="@+id/closeBlue"
android:onClick="closeBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="关闭蓝牙" />
<Button
android:id="@+id/findBlue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="findBlue"
android:layout_below="@+id/openBlue"
android:text="搜索蓝牙设备" />
<TextView
android:id="@+id/tv_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/findBlue"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:text="已配对设备"
/>
<ListView
android:id="@+id/listView_bound"
android:layout_below="@+id/tv_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></ListView>
<TextView
android:id="@+id/tv_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/listView_bound"
android:layout_marginTop="25dp"
android:layout_marginBottom="5dp"
android:text="可用设备"
/>
<ListView
android:id="@+id/listView_isConnect"
android:layout_below="@+id/tv_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></ListView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
/>
<TextView
android:id="@+id/Address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp"
/>
</LinearLayout>
package com.zw.findbluetest;
import android.support.v7.app.ActionBarActivity;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket btSocket;
private ConnectThread connectThread;
// 蓝牙BLE列表适配器
private LeDeviceListAdapter mLeDeviceListAdapter_dound;
private LeDeviceListAdapter mLeDeviceListAdapter_isConnect;
private ListView bleDev_lvBound;
private ListView bleDev_lvConnect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//搜索时显示圈圈
setContentView(R.layout.activity_main);
//初始化;
mLeDeviceListAdapter_dound = new LeDeviceListAdapter(this);
mLeDeviceListAdapter_isConnect = new LeDeviceListAdapter(this);
bleDev_lvBound = (ListView) findViewById(R.id.listView_bound);
bleDev_lvBound.setAdapter(mLeDeviceListAdapter_dound);//加载listView适配器
bleDev_lvConnect = (ListView) findViewById(R.id.listView_isConnect);
bleDev_lvConnect.setAdapter(mLeDeviceListAdapter_isConnect);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 获取所有已经绑定的蓝牙设备
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
if (devices.size() > 0) {
for (BluetoothDevice bluetoothDevice : devices) {
// 扫描到设备则添加到适配器
mLeDeviceListAdapter_dound.addDevice(bluetoothDevice);
// 数据改变并更新列表
mLeDeviceListAdapter_dound.notifyDataSetChanged();
}
}
/**
* 已配对listView的点击事件
*/
bleDev_lvBound.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
BluetoothDevice device = mLeDeviceListAdapter_dound.getDevice(position);
connectThread = new ConnectThread(device);
System.out.println("连接中....");
connectThread.start();
Toast.makeText(MainActivity.this, "点击设备是"+ device.getName() + " " + device.getAddress(), Toast.LENGTH_LONG).show() ;
}
}) ;
// 注册用以接收到已搜索到的蓝牙设备的receiver
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
/**
* 可用listView的点击事件
*/
bleDev_lvConnect.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
try {
BluetoothDevice device = mLeDeviceListAdapter_isConnect.getDevice(position);
Boolean returnValue = false;
Method createBondMethod;
if(device.getBondState() == BluetoothDevice.BOND_NONE) {
// 反射方法调用;
createBondMethod = BluetoothDevice.class .getMethod("createBond");
System.out.println("开始配对");
returnValue = (Boolean) createBondMethod.invoke(device);
//mLeDeviceListAdapter_isConnect.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "点击设备是"+ device.getName() + " " + device.getAddress(), Toast.LENGTH_LONG).show() ;
}else if(device.getBondState() == BluetoothDevice.BOND_BONDED){
connectThread = new ConnectThread(device);
connectThread.start();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println(action);
// 获得已经搜索到的蓝牙设备
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 搜索到的不是已经绑定的蓝牙设备
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
// 扫描到设备则添加到适配器
mLeDeviceListAdapter_isConnect.addDevice(device);
// 数据改变并更新列表
mLeDeviceListAdapter_isConnect.notifyDataSetChanged();
}
// 搜索完成
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
setProgressBarIndeterminateVisibility(false);
setTitle("搜索蓝牙设备");
}
}
};
//完成打开蓝牙按钮点击事件;
public void openBlue(View v){
//判断该设备是否是蓝牙设备
if(mBluetoothAdapter == null){
Toast.makeText(this,"本地蓝牙不可用",Toast.LENGTH_SHORT).show();
finish(); //退出应用
}
// 若蓝牙没打开
if(!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable(); //打开蓝牙,需要BLUETOOTH_ADMIN权限
Toast.makeText(this, "正在打开..", 0).show();
}
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600为蓝牙设备可见时间
startActivity(enable);
Intent searchIntent = new Intent(this, MainActivity.class);
startActivity(searchIntent);
}
//完成关闭蓝牙点击事件
public void closeBlue(View v){
if(mBluetoothAdapter.isEnabled()){//判断蓝牙是否打开
mBluetoothAdapter.disable();//关闭蓝牙
Toast.makeText(this, "正在关闭..", 0).show();
}else{
Toast.makeText(getApplicationContext(), "蓝牙未打开,先打开蓝牙", 0).show();
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//解除注册
unregisterReceiver(mReceiver);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//扫描按钮的点计事件
public void findBlue(View v) {
setProgressBarIndeterminateVisibility(true);
setTitle("正在扫描....");
// 如果正在搜索,就先取消搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
mBluetoothAdapter.startDiscovery();
}
}
package com.zw.findbluetest;
import java.util.ArrayList;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
/**
* 用于listView的配置;
* @author wen
*
*/
public class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
//LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化
//它的作用类似于findViewById()
private LayoutInflater mInflator;
private Activity mContext;//获得 LayoutInflater 实例的一种方法就是使用Activity;
public LeDeviceListAdapter(Activity c) {
super();
mContext = c;
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = mContext.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
System.out.println(device.getName() + " " + device.getAddress());
}
}
// 获取子项中对应的设备
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 position) {
return mLeDevices.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.item, null);//实例化这个控件
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.Address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.Name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
//the Object stored in this view as a tag
}
// 对应的设备进行处理
BluetoothDevice device = mLeDevices.get(position);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0) {
viewHolder.deviceName.setText(deviceName);
} else {
viewHolder.deviceName.setText("未知设备");
}
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
//将要显示的信息封装成一个类
final class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}