BlueTooth

BlueTooth

  • 添加权限:
    • 打开蓝牙并设置允许被搜索
  • 打开蓝牙
  • 关闭蓝牙
  • 扫描蓝牙
    • 点击进行连接
  • 显示已配对蓝牙
  • 对配对的蓝牙设备发送消息
  • 开启服务器接收已配对设备消息

添加权限:

   <!-- 用于进行网络定位 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 用于访问GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>

打开蓝牙并设置允许被搜索

 //调用系统开关蓝牙弹窗->用户手动允许
	Intent intent = new Intent();
	intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//开启蓝
    intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//允许蓝牙被搜索
   intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//设置允许被搜索时间200s内可以被搜索到
    startActivityForResult(intent,100);

打开蓝牙

Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
                startActivity(intent);

关闭蓝牙

获取蓝牙管理及适配

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
bluetoothAdapter.disable();//强制关闭蓝牙

扫描蓝牙

通过广播获取
广播接收

 class MyRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                ss.add(bluetoothDevice);
                blueToothAdapter1.notifyDataSetChanged();
            }
        }
    }

点击进行连接

lvConnectable.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = ss.get(position);
                device.createBond();
            }
        });

1.注册广播

myRecevier=new MyRecevier();
        IntentFilter intentFilter = new IntentFilter();//设置频道
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myRecevier,intentFilter);
bluetoothAdapter.startDiscovery();

显示已配对蓝牙

Set<BluetoothDevice> bondedDevicess = bluetoothAdapter.getBondedDevices();
                bondedDevices.removeAll(bondedDevices);
                bondedDevices.addAll(bondedDevicess);
                blueToothAdapter.notifyDataSetChanged();

对配对的蓝牙设备发送消息

开启客户端

public class BlueToothSocket extends Thread{
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");

    BluetoothDevice device;
    String message;

    public BlueToothSocket(BluetoothDevice device, String message) {
        this.device = device;
        this.message = message;
    }

    @Override
    public void run() {
        try {
            BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
            socket.connect();
            if(socket.isConnected()){
                socket.getOutputStream().write(message.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
lvConnected.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = bondedDevices.get(position);
                new BlueToothSocket(device,"123").start();
            }
        });

开启服务器接收已配对设备消息

public class BlueToothSeverSocket extends Thread{
    private BluetoothSocket socket;
    private Handler handler;

    public BlueToothSeverSocket(BluetoothSocket socket, Handler handler) {
        this.socket = socket;
        this.handler = handler;
    }

    @Override
    public void run() {
        StringBuffer buffer = new StringBuffer();
        try {
            InputStream is = socket.getInputStream();
            int len = 0;
            byte[] b = new byte[1024];
            int read = is.read(b);
            String s = new String(b, 0, read);
            Log.i("111", "run: ");

            Message message = new Message();
            message.what = 100;
            message.obj = s;
            Log.i("123", "run: "+s);
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在打开蓝牙时开启线程

new Thread(){
                    @Override
                    public void run() {
                        while (true){
                            try {
                                BluetoothServerSocket socket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                                while (true){
                                    BluetoothSocket accept = socket.accept();
                                    new BlueToothSeverSocket(accept,handler).start();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();

你可能感兴趣的:(BlueTooth)