蓝牙搜索显示结果到ListView(十分精简)

来源:互联网 发布:淘宝宝贝怎么修改类目 编辑:程序博客网 时间:2024/05/29 14:31

小Demo是搜索蓝牙设备显示到ListView中的,布局和代码都简单清楚明了。

1.首先创建XML

main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.yipai.scanandcontrol.MainActivity">    <TextView        android:id="@+id/blueName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="已连接的设备名称" />    <Button        android:id="@+id/scan"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="搜索蓝牙设备" />    <ListView        android:id="@+id/result"        android:layout_width="match_parent"        android:layout_height="match_parent">    </ListView></LinearLayout>

2.创建ListView中的Item布局
list_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="wrap_content">    <TextView android:id="@+id/device_name"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:textSize="24dp"/>    <TextView android:id="@+id/device_address"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:textSize="12dp"/></LinearLayout>

3.Main_Activity.java

public class MainActivity extends AppCompatActivity {    //蓝牙适配器    private BluetoothAdapter mBluetoothAdapter;    //搜索BUTTON    private Button scan;    //搜索结果List    private ListView resultList;    //搜索状态的标示    private boolean mScanning;    //扫描时长    private static final long SCAN_PERIOD = 5000;    //请求启用蓝牙请求码    private static final int REQUEST_ENABLE_BT = 1;    //蓝牙适配器    private BlueToothDeviceAdapter mBlueToothDeviceAdapter;    //蓝牙适配器List    private List<BluetoothDevice> mBlueList = new ArrayList<>();    private Context context;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        context = this;        //初始化蓝牙适配器        final BluetoothManager bluetoothManager =                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);        mBluetoothAdapter = bluetoothManager.getAdapter();        //初始化适配器        mBlueToothDeviceAdapter = new BlueToothDeviceAdapter(mBlueList,context);        inint();       }    }    private void inint() {        scan = (Button) findViewById(R.id.scan);        resultList = (ListView) findViewById(R.id.result);        scan.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                //如果点击了搜索,清空适配器,开始搜索蓝牙设备//                mBluetoothAdapter.startLeScan(mLeScanCallback);                scanLeDevice(true);            }        });    }    /**     * 设备搜索     *     * @param enable 是否正在搜索的标示     */    private void scanLeDevice(final boolean enable) {        if (enable) {            mHandler.postDelayed(new Runnable() {                @Override                public void run() {                    if (mScanning) {                        mScanning = false;                        mBluetoothAdapter.stopLeScan(mLeScanCallback);                    }                }            }, SCAN_PERIOD);            mScanning = true;            mHandler.sendEmptyMessage(1);            mBluetoothAdapter.startLeScan(mLeScanCallback);        }    }    // Hander    public final Handler mHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            switch (msg.what) {                case 1: // Notify change                    mBlueToothDeviceAdapter.notifyDataSetChanged();                    break;            }        }    };    // Device scan callback.    private BluetoothAdapter.LeScanCallback mLeScanCallback =            new BluetoothAdapter.LeScanCallback() {                @Override                public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            //获取到蓝牙设备                            if (!mBlueList.contains(device)){                                mBlueList.add(device);                                Log.e("tag", "mLeScanCallback 搜索结果   " + device.getAddress());                            }                            //List加载适配器                            if (mBlueToothDeviceAdapter.isEmpty()) {                                Log.e("tag", "mLeDeviceListAdapter为空");                            } else {                                resultList.setAdapter(mBlueToothDeviceAdapter);                            }                            mHandler.sendEmptyMessage(1);                        }                    });                }            };}

4.ListViewBaseAdapter.java 这个基本是通用的

 private List<BluetoothDevice> mBluelist;    private LayoutInflater layoutInflater;    public BlueToothDeviceAdapter(List<BluetoothDevice> list, Context context) {        mBluelist = list;        layoutInflater = LayoutInflater.from(context);//context :要使用当前的Adapter的界面对象 layoutInflater: 布局装载器对象    }    @Override    public int getCount() {        return mBluelist.size();    }    @Override    public Object getItem(int i) {        return mBluelist.get(i);    }    @Override    public long getItemId(int i) {        return i;    }    @Override    public View getView(int i, View view, ViewGroup viewGroup) {        /**         * 文艺式,避免两个耗时操作,第一个就是创建concerView对象,和findviewbyid         */        //2.创建ViewHlder        ViewHolder viewHolder;        //3.判断concerView是否为空        if (view == null) {            //实例化ViewHolder            viewHolder = new ViewHolder();            //View对象还没有被实例化过,缓存池中没有缓存,那么就创建一个convertView对象            view = layoutInflater.inflate(R.layout.listitem_device, null);            //把findviewbyid找的的保存到 viewHolder 中            viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);            viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);            //通过setTag将 viewHolder 和 convertview 进行绑定            view.setTag(viewHolder);        } else {            //可以直接通过 viewHolder 来找到对象所对应的控件            viewHolder = (ViewHolder) view.getTag();        }        BluetoothDevice blueDevice = mBluelist.get(i);        final String deviceName = blueDevice.getName();        if (deviceName != null && deviceName.length() > 0) {            viewHolder.deviceName.setText(blueDevice.getName());        } else {            viewHolder.deviceName.setText("未知设备");        }        viewHolder.deviceAddress.setText(blueDevice.getAddress());        return view;    }    //创建内部类ViewHlder    class ViewHolder {        /**         * 避免重复的findviewbyId         */        TextView deviceName;        TextView deviceAddress;    }

全部代码都在这里了,没什么技术含量,看一看就能够明白。

1 0
原创粉丝点击