安卓——蓝牙listView搜索以及点击事件_安卓listview选择蓝牙设备(1)

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

android:id=“@+id/Address”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:textSize=“10sp”
/>



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);

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

5805305201)]
[外链图片转存中…(img-MGEuEiST-1715805305201)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值