AndRoid 蓝牙

开启蓝牙、关闭蓝牙、匹配蓝牙

一、加权限
二、常用功能
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);请求启动
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);暴露蓝牙,被别人搜索到
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,100);设置多久可能搜到蓝牙
startActivityForResult(intent,100);

关闭蓝牙
适配器.disable();
配对适配器
设备.createBond();
搜索蓝牙
适配器.startDiscovery();

反射:
Class c = User.class();

常用类
BluetoothManager;蓝牙管理类,管理bluetoothAdapter,蓝牙连接
BluetoothAdapter;蓝牙适配器,代表本蓝牙
BluetoothDevicer;蓝牙设备,是连接的那个设备
BluetoothServiceSocket;服务端
BluetoothSocket;客户端

蓝牙的传输功能
UUID
UUID.fromString(uuid)类型转换

Activity代码

// An highlighted block
package com.example.work10_1;

import android.Manifest;
import android.annotation.TargetApi;
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.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
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.Button;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import static android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_FINISHED;
import static android.bluetooth.BluetoothDevice.ACTION_BOND_STATE_CHANGED;
import static android.bluetooth.BluetoothDevice.ACTION_FOUND;
import static android.bluetooth.BluetoothDevice.BOND_BONDED;
import static android.bluetooth.BluetoothDevice.BOND_BONDING;
import static android.bluetooth.BluetoothDevice.BOND_NONE;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private BluetoothManager manager;
    private BluetoothAdapter adapter;
    private Button serch;
    private Button start;
    private Button stop;
    private BluetoothReceice bluetoothReceice;
    private RecyclerView recyclerView;
    private ArrayList<Bean> list = new ArrayList<>();
    private MyAdapter myAdapter;
    private String[] permission = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION};
    private boolean isok;

    @TargetApi(Build.VERSION_CODES.M)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initpermission();
        intitview();
        initBluetooth();

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initpermission() {
        boolean flag = false;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

            for (String p:permission) {
                if(checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED){
                    flag = true;
                }
            }

        }
        if(flag){
                  requestPermissions(permission,500);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 500){

            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    isok = true;
                }
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void intitview(){
        recyclerView = findViewById(R.id.main_recy);
        serch = findViewById(R.id.main_serch);
        start = findViewById(R.id.main_start);
        stop = findViewById(R.id.main_stop);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        DividerItemDecoration decoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        decoration.setDrawable(getDrawable(R.drawable.divider));
        recyclerView.addItemDecoration(decoration);

        myAdapter = new MyAdapter(list,MainActivity.this);
        recyclerView.setAdapter(myAdapter);
        serch.setOnClickListener(this);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);

        myAdapter.setlistener(new MyListenner() {
            @Override
            public void click(int i) {
                try {
                    Method createBond = BluetoothDevice.class.getMethod("createBond");
                    createBond.invoke(list.get(i).getDevice());
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public  void initBluetooth(){
        manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        adapter = manager.getAdapter();
        if(adapter == null){
            finish();
            return;
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//是否发现设备
        intentFilter.addAction(ACTION_DISCOVERY_FINISHED);//时候扫描结束
        intentFilter.addAction(ACTION_BOND_STATE_CHANGED);

        bluetoothReceice = new BluetoothReceice();
        registerReceiver(bluetoothReceice,intentFilter);

    }


    @Override
    public void onClick(View v) {
           switch (v.getId()){
               case R.id.main_start:
                   boolean flag = adapter.enable();

                   if(flag == false){
                       Intent intent = new Intent();
                       intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                       intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                       intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,100);
                       startActivityForResult(intent,100);
                   }
                   break;
               case R.id.main_stop:
                   adapter.disable();
                   list.clear();
                   myAdapter.notifyDataSetChanged();
                   break;
               case R.id.main_serch:
                   adapter.startDiscovery();
                   break;
           }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 &&resultCode == RESULT_OK){
            Log.e("########start","开启成功");
        }else{
            Log.e("########start","开启失败");
        }
    }

    public class BluetoothReceice extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case ACTION_BOND_STATE_CHANGED:
                    //监听设备的连接状态
                    BluetoothDevice mydevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//拿到设备
                    int state = mydevice.getBondState();
                    if(state == BOND_NONE){
                        Log.e("#####stata","没有设备");
                    }else if(state == BOND_BONDING){
                        Log.e("#####stata","正在匹配");
                    }else if(state == BOND_BONDED){
                        Log.e("#####stata","匹配成功");
                        new ConnectionManager(mydevice);
                    }


                    break;
                case ACTION_FOUND:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//拿到设备
                    String name = device.getName();
                    String address = device.getAddress();
                    Bean bean = new Bean(name,address,device);
                    list.add(bean);
                    break;
                case ACTION_DISCOVERY_FINISHED:
                    myAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }
}

适配器代码

// An highlighted block
package com.example.work10_1;

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 java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>{
    ArrayList<Bean> list ;
    Context context;
    MyListenner listenner;

    public MyAdapter(ArrayList<Bean> list, Context context) {
        this.list = list;
        this.context = context;
    }
    public void setlistener(MyListenner listenner){
        this.listenner = listenner;
    }


    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycview,viewGroup,false);
        MyHolder myHolder = new MyHolder(view);
        return myHolder;
    }



    @Override
    public void onBindViewHolder(@NonNull MyHolder myHolder, final int i) {
               myHolder.textView1.setText(list.get(i).getName());
               myHolder.textView2.setText(list.get(i).getAddress());
               myHolder.itemView.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       listenner.click(i);
                   }
               });

    }

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

    public class MyHolder extends RecyclerView.ViewHolder{
        private TextView textView1;
        private TextView textView2;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            textView1 = itemView.findViewById(R.id.recyc_text1);
            textView2 = itemView.findViewById(R.id.recyc_text2);
        }
    }
}

实体类代码

// An highlighted block
package com.example.work10_1;

import android.bluetooth.BluetoothDevice;

public class Bean {
    String name;
    String address;
    BluetoothDevice device;

    public Bean(String name, String address, BluetoothDevice device) {
        this.name = name;
        this.address = address;
        this.device = device;
    }

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public BluetoothDevice getDevice() {
        return device;
    }

    public void setDevice(BluetoothDevice device) {
        this.device = device;
    }
}

布局代码

// An highlighted block
<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/main_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启"
        />
    <Button
        android:id="@+id/main_stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭"
        />
   <Button
       android:id="@+id/main_serch"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="搜索"
       />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/main_recy"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>


</LinearLayout>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值