android 蓝牙基本使用

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

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

然后动态请求权限

//动态获取权限
        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();
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值