蓝牙配对

蓝牙配对

蓝牙基本操作

一、加权限

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.INTERNET"/>

二、常用功能
1、打开蓝牙
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE); 请求启动
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 暴露蓝牙搜索
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200); 设置多久可能搜到蓝牙
startActivityForResult(intent,100); 请求码

2、关闭蓝牙
适配器.disable()
3、配对蓝牙
设备.createBond()
4、搜索
适配器.startDiscovery()

三、常用类
BluetoothManager 管理蓝牙类
管理bluetoothAdapter管理蓝牙连接
BluetoothAdapter 蓝牙适配器,代表本蓝牙(自己的)
BluetoothDevice 蓝牙设备,是连接的那个设备(对方的)
BluetoothServiceSocket 服务器
BluetoothSocket 客户端

蓝牙的传输功能的UUID是:00001101-0000-1000-8000-00805F9B34FB
uuid.fromString(“00001101-0000-1000-8000-00805F9B34FB”)类型转换
四 action
ACTION_BOND_STATE_CHANGED createBond配对方法
ACTION_DISCOVERY_FINISHED 搜索蓝牙
ACTION_FOUND 搜索蓝牙结束

布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
<Button
    android:id="@+id/seach"
    android:text="搜索"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/b1"
    android:text="开启"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/b2"
    android:text="关闭"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<ListView
    android:id="@+id/lv1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>
</LinearLayout>

自定义布局

<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
    android:textSize="20dp"
    android:id="@+id/t1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:textSize="20dp"
    android:id="@+id/t2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

适配器

public class MyAdapter extends BaseAdapter {
    Context context; List<BluetoothDevice> list;
    public MyAdapter(Context context, List<BluetoothDevice> list) {
        this.context=context;
        this.list=list;
    }

public void refresh(List<BluetoothDevice> list){
    this.list.addAll(list);
    notifyDataSetChanged();
}
@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView==null){
        viewHolder = new ViewHolder();
        convertView = View.inflate(context,R.layout.name1,null);
        viewHolder.name=convertView.findViewById(R.id.t1);
        viewHolder.address=convertView.findViewById(R.id.t2);
        convertView.setTag(viewHolder);
    }else{
        viewHolder = (ViewHolder)convertView.getTag();
    }


    BluetoothDevice device = list.get(position);
    viewHolder.name.setText(device.getName());
    viewHolder.address.setText(device.getAddress());
    return convertView;
}

public class ViewHolder{
    TextView name;
    TextView address;
}
}

Activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button button;
Button button2;
Button button3;
ListView listView;
MyAdapter myAdapter;
List<Bean> list = new ArrayList<>();
BluetoothManager bluetoothManager;
BluetoothAdapter bluetoothAdapter;
BlueReceiver blueReceiver;
ConnectionManager manager;
BluetoothDevice device;
List<BluetoothDevice> devices = new ArrayList<>();
static final  String Tag="###";
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    init();
    start();

}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void init(){
    bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    if (bluetoothAdapter == null){
        finish();
        return;
    }

    button = findViewById(R.id.seach);
    button2 = findViewById(R.id.b1);
    button3 = findViewById(R.id.b2);
    button.setOnClickListener(this);
    button2.setOnClickListener(this);
    button3.setOnClickListener(this);
    listView = findViewById(R.id.lv1);
    myAdapter = new MyAdapter(this,devices);
    listView.setAdapter(myAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            BluetoothDevice device = devices.get(position);
            try {
                Method method = BluetoothDevice.class.getMethod("createBond");
                method.invoke(device);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

}

public void start(){
    blueReceiver = new BlueReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//是否发现有设备
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//是否扫描结束
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//监听绑定状态的改变
    registerReceiver(blueReceiver,intentFilter);//注册
}


@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.b1:
            boolean flag=bluetoothAdapter.enable();
            if (!flag){
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
                startActivityForResult(intent,100);
            }
            break;
        case R.id.b2:
            devices.clear();
            myAdapter.notifyDataSetChanged();
            bluetoothAdapter.disable();
            break;
        case R.id.seach:

            bluetoothAdapter.startDiscovery();
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==100 && requestCode==RESULT_OK){
        Toast.makeText(this, "蓝牙开启成功", Toast.LENGTH_SHORT).show();
        Log.e(Tag,bluetoothAdapter.getAddress()+"  "+bluetoothAdapter.getName());
    }
}

class BlueReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch (action){
            case BluetoothDevice.ACTION_FOUND://发现设备触发
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Bean bean = new Bean(bluetoothDevice.getName(), bluetoothDevice.getAddress(), bluetoothDevice);
                devices.add(bluetoothDevice);
                myAdapter.refresh(devices);
                break;
            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:

                break;
            case BluetoothDevice.ACTION_BOND_STATE_CHANGED://状态发生改变是(监听连接状态)
               device  = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//拿到设备
                int state = device.getBondState();
                if (state == BOND_NONE){
                    Log.e(Tag,"没有设备");
                }else if (state ==BOND_BONDING ){
                    Log.e(Tag,"正在匹配中,有可能正在弹框");
                }else if (state ==BOND_BONDED){
                    Log.e(Tag,"连接成功");
                     manager = new ConnectionManager(device);

                }
                break;
                default:

                    break;
        }
    }
}
}

效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值