安卓开发--开启蓝牙(支持配对功能)

安卓的不同版本所实现的代码不同,9.0需要动态申请权限,包括获取位置的权限的Location

9.0以下版本的代码:

  • 权限:

	<uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  • 布局:

<?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:layout_height="match_parent"
    tools:context=".buletooth_01"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/start"
        android:text="开启连接"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="搜索链接"
        android:id="@+id/search"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭连接"
        android:id="@+id/close"
        />
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyc"
        >

    </android.support.v7.widget.RecyclerView>
</LinearLayout>
  • RecyclerView的条目布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/item1"
        android:textSize="25sp"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/item2"
        android:textSize="25sp"
        android:layout_below="@id/item1"
        />
</RelativeLayout>
  • java的bean类:

package com.example.bluetouth_1;

import android.bluetooth.BluetoothDevice;

public class BlueToothBean {
     String name;
     String mac;
     BluetoothDevice bluetoothDevice;

    public BlueToothBean(String name, String mac) {
        this.name = name;
        this.mac = mac;
    }

    public BlueToothBean() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }
}

  • RecyclerView适配器类:

package com.example.bluetouth_1;

import android.content.ContentValues;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.VideoView;

import java.util.ArrayList;
import java.util.List;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MyViewHolder> {

    List<BlueToothBean> datas;
    Context context;

    public MainAdapter(List datas, Context context) {
        this.datas = datas;
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item,null));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        myViewHolder.item1.setText(datas.get(i).getName());
        myViewHolder.item2.setText(datas.get(i).getMac());
        //添加点击事件  进行接口回调
        myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 onClick.OnClick(i);
             }
         });
    }

    @Override
    public int getItemCount() {
        if(datas == null){
            return 0;
        }
        return datas.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView item1;
        TextView item2;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            item1 = itemView.findViewById(R.id.item1);
            item2 = itemView.findViewById(R.id.item2);
        }
    }
    //添加点击事件的接口
    interface MyOnClick {
        public void OnClick(int index);
    }
}

  • 主类代码:

package com.example.bluetouth_1;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class buletooth_01 extends AppCompatActivity implements View.OnClickListener {

    private MainAdapter adapter;
    private List<BlueToothBean> beans = new ArrayList<>();
    private RecyclerView recyclerView;

    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothReceiver bluetoothReceiver;
    String permisssions[] = {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.BLUETOOTH,Manifest.permission.BLUETOOTH_ADMIN};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buletooth_01);
        initView();
        initData();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            MyPermission();
        }
    }

    private void MyPermission() {
        boolean flag = true;
        for(int i = 0;i < permisssions.length;i++){
            if(checkSelfPermission(permisssions[i])!= PackageManager.PERMISSION_GRANTED){
                flag = false;
                break;
            }
        }
        if(!flag){
            requestPermissions(permisssions,100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100){
            boolean flag = true;
            for(int i = 0;i < grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    flag = false;
                    break;
                }
            }
            if(flag){
                Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "申请失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initData() {
        bluetoothManager = (BluetoothManager)getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();//蓝牙的适配器
        if(bluetoothAdapter == null){
            finish();
            return;
        }
        bluetoothReceiver = new BluetoothReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//可发现
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定结束
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//绑定结束
        registerReceiver(bluetoothReceiver,intentFilter);
    }

    /**
     * 初始化布局
     */
    private void initView() {
        recyclerView = findViewById(R.id.recyc);
        //点击事件
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.search).setOnClickListener(this);
        findViewById(R.id.close).setOnClickListener(this);
        //设置风格
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        //设置分割线
        DividerItemDecoration decoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        Drawable drawable = getResources().getDrawable(R.drawable.line);
        decoration.setDrawable(drawable);
        recyclerView.addItemDecoration(decoration);

        adapter = new MainAdapter(beans,this);
        recyclerView.setAdapter(adapter);
        //设置条目点击事件的监听
        adapter.setOnClick(new MainAdapter.MyOnClick() {
            @Override
            public void OnClick(int index) {
                try {
                    //反射方法调用配对方法
                    Method method = BluetoothDevice.class.getMethod("createBond");
                    Log.e("###",beans.get(index).getName());
                    method.invoke(beans.get(index).getBluetoothDevice());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.start:
                boolean flag = bluetoothAdapter.enable();
                if(!flag){
                    Intent intent = new Intent();
                    intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//启动蓝牙
                    intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//开启本设备可被发现
                    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//指定搜索设备时间
                    startActivityForResult(intent,100);
                }
                break;
            case R.id.close:
                bluetoothAdapter.disable();//关闭蓝牙
                beans.clear();
                adapter.notifyDataSetChanged();
                break;
            case R.id.search:
                bluetoothAdapter.startDiscovery();//开启搜索
                break;
                default:
                    break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100&&resultCode == RESULT_OK){
            Toast.makeText(this, "蓝牙启动成功", Toast.LENGTH_SHORT).show();
        }
    }

    public class BluetoothReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch(action){
                case BluetoothDevice.ACTION_FOUND:
                    //搜索到一台蓝牙设备,进入一次found
                    //搜索到的设备保存到list中
                    BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    BlueToothBean bean = new BlueToothBean();
                    bean.name = bluetoothDevice.getName();
                    Log.e("name","###"+bean.name);
                    bean.mac = bluetoothDevice.getAddress();
                    bean.bluetoothDevice = bluetoothDevice;
                    beans.add(bean);
                    adapter.notifyDataSetChanged();
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    adapter.notifyDataSetChanged();
                    break;
                    default:
                        break;
            }
        }
    }
}

版本在9.0以下的主类代码:


package com.huluobo.lc.a1702c_bluetoothdemo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView listView;
    private MainAdapter mainAdapter;
    private List<BlueToothBean> list = new ArrayList<>();
    private Button btn_start, btn_stop, btn_search;

    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothReceiver bluetoothReceiver;

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

    private void initView() {
        btn_start = findViewById(R.id.btn_start);
        btn_stop = findViewById(R.id.btn_stop);
        btn_search = findViewById(R.id.btn_search);

        btn_start.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
        btn_search.setOnClickListener(this);

        listView = findViewById(R.id.listView);
        mainAdapter = new MainAdapter();
        listView.setAdapter(mainAdapter);

    }

    private void initDate() {
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();//蓝牙adapter
        if (bluetoothAdapter == null) {
            finish();
            return;
        }
        bluetoothReceiver = new BluetoothReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//可发现
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索结束
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态
        registerReceiver(bluetoothReceiver, intentFilter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                boolean flag = bluetoothAdapter.enable();
                if (!flag) {
                    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, 100);
                }
                break;
            case R.id.btn_stop:
                bluetoothAdapter.disable();//关闭蓝牙
                list.clear();
                mainAdapter.refresh(list);
                break;
            case R.id.btn_search:
                bluetoothAdapter.startDiscovery();//开启搜索
                break;
            default:
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            Toast.makeText(this, "开启蓝牙成功", Toast.LENGTH_SHORT).show();
        }
    }

    private class BluetoothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BluetoothDevice.ACTION_FOUND:
                    //搜索到一台蓝牙设备,进入一次FOUND
                    //搜索到的设备保存到list中
                    BluetoothDevice bluetoothDevice =
                            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    BlueToothBean blueToothBean = new BlueToothBean();
                    blueToothBean.name = bluetoothDevice.getName();
                    blueToothBean.address = bluetoothDevice.getAddress();
                    blueToothBean.bluetoothDevice = bluetoothDevice;
                    list.add(blueToothBean);
                    mainAdapter.refresh(list);
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    mainAdapter.refresh(list);
                    break;
                default:
                    break;
            }
        }
    }
}

Android9.0效果图:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44946212/article/details/92800350