蓝牙

蓝牙的创建方法

蓝牙需要动态获取权限,使用getSystemService(BLUETOOTH_SERVICE);创建一个BluetoothManager的对象,然后使用BluetoothManager的对象.getAdapter();获取本地蓝牙对象,对本地的蓝牙进行操作。

蓝牙开启的方法

蓝牙是使用隐式意图跳转的,需要在addAction里添加对应的常量,然后使用广播接收者接收(需要动态注册),用startActivity(intent);方法发送。

代码

private void init(){
        String[] s = new String[]{
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_FINE_LOCATION
        };
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(s,100);
            }
        }
        initBlueTooth();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//注册搜索蓝牙的广播
        intentFilter.addAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//搜索结束
        myReceiver = new MyReceiver(mapList,simpleAdapter,deviceList);
        registerReceiver(myReceiver,intentFilter);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initBlueTooth(){
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        adapter = bluetoothManager.getAdapter();
    }
    public void open(){
        Intent intent = new Intent();
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
        startActivity(intent);
    }

    public void close(){
        adapter.disable();
    }

    public void search(){
        adapter.startDiscovery();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值