蓝牙的使用

蓝牙

JAVA代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int OPEN = 110;
    
    private Button bt_open;
    private Button bt_close;
    private Button bt_discovery;
    private Button bt_bond;
    private RecyclerView rv_discovery;
    private RecyclerView rv_bond;
    private ArrayList<BluetoothDevice> list_bond = new ArrayList<>();//已配对蓝牙集合
    private ArrayList<BluetoothDevice> list_discovery = new ArrayList<>();//附近蓝牙设备集合

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

    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;

    private MyBluetoothAdapter adapter_bond;
    private MyBluetoothAdapter adapter_discovery;
    private MyRecever myRecevier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //TODO:动态授权
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH
            }, 101);
        }

        initView();

        //TODO:初始化蓝牙设备
        initBull();

        //TODO:动态注册广播
        initRecever();
    }

    private void initRecever() {
        MyRecever myRecever = new MyRecever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myRecever, intentFilter);
    }

    //TODO:解除注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myRecevier);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initBull() {
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
    }

    private void initView() {
        bt_open = (Button) findViewById(R.id.bt_open);
        bt_close = (Button) findViewById(R.id.bt_close);
        bt_discovery = (Button) findViewById(R.id.bt_discovery);
        bt_bond = (Button) findViewById(R.id.bt_bond);
        rv_discovery = (RecyclerView) findViewById(R.id.rv_discovery);
        rv_bond = (RecyclerView) findViewById(R.id.rv_bond);

        bt_open.setOnClickListener(this);
        bt_close.setOnClickListener(this);
        bt_discovery.setOnClickListener(this);
        bt_bond.setOnClickListener(this);


        //TODO:显示已配对蓝牙设备
        adapter_bond = new MyBluetoothAdapter(list_bond, this);
        rv_bond.setAdapter(adapter_bond);
        rv_bond.setLayoutManager(new LinearLayoutManager(this));
        rv_bond.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        //点击发送数据
        adapter_bond.setMyItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(int postion) {
                BluetoothDevice device = list_bond.get(postion);
                //TODO:建立连接 发送数据
                try {
                    //创建BluetoothSocket
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    socket.connect();
                    //判断是否连接成功
                    if (socket.isConnected()) {
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        //发送数据
                        socket.getOutputStream().write("http://5b0988e595225.cdn.sohucs.com/images/20180523/93c796f46fd5417a9af7ba0b9ae87627.gif".getBytes());
                        //接收回传的结果
                        InputStream inputStream = socket.getInputStream();
                        byte[] bytes = new byte[1024];
                        int len = inputStream.read(bytes);
                        String s = new String(bytes, 0, len);
                        Toast.makeText(MainActivity.this, "" + s, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        //TODO:显示附近蓝牙设备
        adapter_discovery = new MyBluetoothAdapter(list_discovery, this);
        rv_discovery.setAdapter(adapter_discovery);
        rv_discovery.setLayoutManager(new LinearLayoutManager(this));
        rv_discovery.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        //TODO:点击设备进行配对
        adapter_discovery.setMyItemClickListener(new MyItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(int position) {
                //点击进行配对
                BluetoothDevice device = list_discovery.get(position);
                device.createBond();
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_open:
                open();
                break;
            case R.id.bt_close:
                close();
                break;
            case R.id.bt_discovery:
                discovery();
                break;
            case R.id.bt_bond:
                bond();
                break;
        }
    }

    //TODO:获取已配对蓝牙设备
    private void bond() {
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();//获取配对蓝牙集合
        list_bond.clear();
        list_bond.addAll(bondedDevices);
        adapter_bond.notifyDataSetChanged();
    }

    //TODO:扫描附近设备+广播
    private void discovery() {
        //扫描附近蓝牙设备
        bluetoothAdapter.startDiscovery();
    }

    //TODO:关闭蓝牙
    private void close() {
        bluetoothAdapter.disable();
    }

    //TODO:打开蓝牙
    private void open() {
        if (!bluetoothAdapter.isEnabled()) {
            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, OPEN);
        }
    }

    //TODO: 广播接收者   (扫描到一个蓝牙设备)
    class MyRecever extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {//扫描频道
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获得远程设备
                list_discovery.add(device);//添加附近的设备到集合中
                adapter_discovery.notifyDataSetChanged();
            }
        }
    }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    android:padding="15dp"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/bt_open"
            android:text="打开"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"></Button>
        <Button
            android:id="@+id/bt_close"
            android:text="关闭"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"></Button>
        <Button
            android:id="@+id/bt_discovery"
            android:text="扫描"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"></Button>
        <Button
            android:id="@+id/bt_bond"
            android:text="配对"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"></Button>
    </LinearLayout>

    <TextView
        android:text="已经配对"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></TextView>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_bond"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></androidx.recyclerview.widget.RecyclerView>

    <TextView
        android:layout_marginTop="20dp"
        android:text="附近设备"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></TextView>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_discovery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></androidx.recyclerview.widget.RecyclerView>



</LinearLayout>

适配器

public class MyBluetoothAdapter extends RecyclerView.Adapter<MyBluetoothAdapter.ViewHolder> {
    private ArrayList<BluetoothDevice> list;
    private Context context;

    public MyBluetoothAdapter(ArrayList<BluetoothDevice> list, Context context) {
        this.list = list;
        this.context = context;
    }

    private MyItemClickListener myItemClickListener;

    public void setMyItemClickListener(MyItemClickListener myItemClickListener) {
        this.myItemClickListener = myItemClickListener;
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        holder.textView.setText(list.get(position).getName()+"");
        //接口回调
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myItemClickListener!=null){
                    myItemClickListener.onItemClick(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    //TODO:ViewHolder
    class ViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.item_text);
        }
    }
}

接口回调 item点击监听

public interface MyItemClickListener {
    void onItemClick(int postion);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值