android 蓝牙基本使用

蓝牙。。基本方法

  • 第一步必须导入权限(蓝牙权限)
  • 然后动态请求权限
  • 第一个。打开蓝牙(使用隐视意图)
  • 第二个。关闭蓝牙(需要实例化)
    • 调用关闭方法:
  • 第三个。使用方法来获取已配对的蓝牙(将数据源放入listview)
  • 第四个。扫描附近蓝牙(使用广播接收器)
    • 扫描蓝牙的广播接收器:(内部类)
      • 绑定接收器:
      • 解除接收器:(实现ondestory方法)
  • 点击配对蓝牙:(.createBond方法)
  • 客户端。。使用蓝牙发送数据(例如一个string字符串)
  • 设置服务端接收消息(创建服务器以及使用handler实现toast)

第一步必须导入权限(蓝牙权限)





然后动态请求权限

//动态获取权限
        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH}, 100);

第一个。打开蓝牙(使用隐视意图)

 //使用隐视意图开启蓝牙
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(intent,1);

第二个。关闭蓝牙(需要实例化)

//实例化manager
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

调用关闭方法:

//使用方法关闭蓝牙
                bluetoothAdapter.disable();

第三个。使用方法来获取已配对的蓝牙(将数据源放入listview)

bondedDevices = bluetoothAdapter.getBondedDevices();
                for (BluetoothDevice bondedDevice : bondedDevices) {
                    Log.i("123",""+bondedDevice.getName());
                }
                //设置listview的适配器
                list.addAll(bondedDevices);
                basadap.notifyDataSetChanged();

第四个。扫描附近蓝牙(使用广播接收器)

list1.clear();
                //开启接收
                bluetoothAdapter.startDiscovery();

扫描蓝牙的广播接收器:(内部类)

 class  MyRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //判断是否扫描到一个
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                //获取到值
                BluetoothDevice parcelableExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //放入集合
                list1.add(parcelableExtra);
                //刷新适配器
                basadap.notifyDataSetChanged();
            }
        }
    }

绑定接收器:

//绑定
        myRecevier = new MyRecevier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myRecevier,intentFilter);

解除接收器:(实现ondestory方法)

protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myRecevier);
    }

点击配对蓝牙:(.createBond方法)

//使用list点击事件
        list_fj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                BluetoothDevice bluetoothDevice = list1.get(i);
                //设置点击配对
                bluetoothDevice.createBond();
            }
        });

客户端。。使用蓝牙发送数据(例如一个string字符串)

 private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//蓝牙通讯规范

严格规范

list_ybd.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) {
                BluetoothDevice bluetoothDevice = list.get(i);
                try {
                    BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
                    //这里是子线程
                    new Mythread(socket,"Shaw").start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

发送消息需要一个子线程,所以使用子线程

public class Mythread extends Thread {

    private BluetoothSocket bluetoothSocket;
    private String pass;

    public Mythread(BluetoothSocket bluetoothSocket, String pass) {
        this.bluetoothSocket = bluetoothSocket;
        this.pass = pass;
    }

    @Override
    public void run() {
        super.run();
        try {
            bluetoothSocket.connect();
            if (bluetoothSocket.isConnected()){
                Log.i("123","配对成功");
                OutputStream outputStream = bluetoothSocket.getOutputStream();
                outputStream.write(pass.getBytes());
            }else {
                Log.i("123","配对失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

设置服务端接收消息(创建服务器以及使用handler实现toast)

因为需要耗时操作所以使用子线程

public class Mythread_fwd extends Thread {

    private BluetoothAdapter bluetoothAdapter;
    private Handler handler;
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    private String s;

    public Mythread_fwd(BluetoothAdapter bluetoothAdapter, Handler handler) {
        this.bluetoothAdapter = bluetoothAdapter;
        this.handler = handler;
    }

    @Override
    public void run() {
        super.run();
        try {
            BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
            BluetoothSocket accept = serverSocket.accept();
            Log.i("123","蓝牙连接成功");
            InputStream inputStream = accept.getInputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes))!= -1){
                s = new String(bytes, 0, len);
            }
            Message message = handler.obtainMessage();
            message.what = 101;
            message.obj = s;
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(android 蓝牙基本使用)