传统蓝牙学习记录(一):蓝牙基础

一:传统蓝牙基础知识

传统蓝牙:所谓传统蓝牙,其实是蓝牙4.0以前的蓝牙技术的统称,在蓝牙4.0之后的的蓝牙称为BLE(Bluetooth Low Energy),关于Ble的知识可以放在以后再说。

                                   

二:蓝牙常用的几个API:

  1.蓝牙适配器BluetoothAdapter

         无论是使用传统蓝牙还是BLE都要调用这个API,可以把它看做蓝牙的管理器。这个api里面有好多方法都是我们在使用蓝牙时需要用到的:                

        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();  //静态方法,获取默认的蓝牙适配器对象;
        bluetoothAdapter.enable();   //打开蓝牙
        bluetoothAdapter.disable();   //关闭蓝牙
        bluetoothAdapter.isEnabled();   //判断蓝牙功能是否打开
        bluetoothAdapter.startDiscovery();  //开始搜索周围设备
        bluetoothAdapter.isDiscovering();    //判断当前设备是否正在搜索周围设备
        bluetoothAdapter.cancelDiscovery();   //停止搜索周围设备
        bluetoothAdapter.getBondedDevices();  //获得已经配对的设备列表
        bluetoothAdapter.getAddress();  //获得本设备的address
        bluetoothAdapter.getName();     //获取本设备的蓝牙名字

  2.蓝牙设备BluetoothDevice

      顾名思义,这个API是用来获取蓝牙设备的一些信息。要注意,这个device代表的是对方的设备,而不是本机的设备,这个一定不要混淆了。BluetoothDevice常用的一些方法如下:

  

        bluetoothDevice.getName();  // 获取设备的蓝牙名字
        bluetoothDevice.getAddress();   //获取设备的address
        bluetoothDevice.getBondState();   //获取设备的绑定状态
        bluetoothDevice.createBond();    //与该设备创建绑定
        bluetoothDevice.createRfcommSocketToServiceRecord(UUID.randomUUID());  //创建一个BluetoothSocket;

3.蓝牙套接字BluetoothSocket和蓝牙服务器套接字BluetoothServiceSocket

   两个蓝牙设备创建连接并互相发送消息,必须有一个是客户端,另一个是服务端。当两台设备配对成功之后,客户端向服务端发送socket连接请求,服务端接收到socket连接请求之后,建立连接,双方开始收发数据。

BluetoothSocket常用的方法如下:

        bluetoothSocket.close();   //关闭连接传输并释放资源
        bluetoothSocket.connect();  //尝试连接到远程设备
        bluetoothSocket.getConnectionType();   //获取底层连接的类型
        bluetoothSocket.getInputStream();    //获取与这个套接字相关联的输入流
        bluetoothSocket.getOutputStream();    //获得与这个套接字相关联的输出流
        bluetoothSocket.getMaxReceivePacketSize();  //获取底层传输的最大支持接收数据包大小。
        bluetoothSocket.getRemoteDevice();    //获取这个套接字连接的远程设备
        bluetoothSocket.isConnected();   //判断是否与远程设备建立了活动连接

BluetoothServiceSocket常用的方法如下:

        bluetoothServerSocket.accept();  //一直阻塞直到连接建立。
        bluetoothServerSocket.accept(int timeout);   //一直组摄直到连接建立或者超过timeout
        bluetoothServerSocket.close();   //关闭这个socket并且释放资源

    三:开启和使用蓝牙服务所需要的权限     

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

在android6.0之后,必须加上第location权限,否则在搜索周围设备时返回的设备列表为空!!!!!!  

四:蓝牙的开启与搜索

      1.蓝牙的开启:

      蓝牙的开启方式可以分为两种:隐式开启和弹出对话框开启。

//隐式开启
  if(!bluetoothAdapter.isEnabled()){
        bluetoothAdapter.enable();
    }
//弹出对话框开启
   if(bluetoothAdapter!=null && !bluetoothAdapter.isEnabled()){
         Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivity(intent);
     }

    2.搜索周围蓝牙设备并且显示出来:这里直接上代码:

activity_main.xml:(蓝牙设备列表通过recyclerview显示出来)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜索设备"
        />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/device_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

dev_item.xml:(列表中每一个item的布局)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

     DeviceAdapter.java:

package com.example.liucongcong.bluetoothtest1;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

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

    private List<BluetoothDevice> bluetoothDevices=new ArrayList<>();
    Context context;

    public DeviceAdapter(Context context,List<BluetoothDevice> bluetoothDevices){
       this.context=context;
        this.bluetoothDevices=bluetoothDevices;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v= View.inflate(context,R.layout.dev_item,null);
       return new MyViewHolder(v);
    }
    @Override
    public int getItemCount(){
        return bluetoothDevices.size();
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.name.setText(bluetoothDevices.get(position).getName());
        holder.address.setText(bluetoothDevices.get(position).getAddress());
    }

    public void addDev(BluetoothDevice device){
        if (bluetoothDevices.contains(device))
            return;
        bluetoothDevices.add(device);
        notifyDataSetChanged();
    }

class MyViewHolder extends RecyclerView.ViewHolder{
        TextView name;
        TextView address;
        public MyViewHolder(View v){
            super(v);
            name=v.findViewById(R.id.name);
            address=v.findViewById(R.id.address);
        }
}
}

MainActivity.java:

package com.example.liucongcong.bluetoothtest1;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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.view.View;
import android.widget.Button;

import android.widget.Toast;

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


public class MainActivity extends AppCompatActivity {
   BluetoothAdapter bluetoothAdapter;
   private Button mSearch;
   private RecyclerView recyclerView;
   private List<BluetoothDevice> bluetoothDevices=new ArrayList<>();
    DeviceAdapter mydaapter;
   int i=0;

   //接收其他蓝牙设备发送的广播
   private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
           String action=intent.getAction();
          if(BluetoothDevice.ACTION_FOUND.equals(action)){
              BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
              //在列表里面加上该项
              mydaapter.addDev(device);
          }
       }
       };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSearch=(Button)findViewById(R.id.btn1);
        recyclerView=findViewById(R.id.device_list);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);

        registerReceiver(broadcastReceiver, intentFilter);
        //开启蓝牙begin
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        //弹出对话框提示用户开启蓝牙
        if(bluetoothAdapter==null){
            Toast.makeText(MainActivity.this,"此设备不支持蓝牙",Toast.LENGTH_LONG);
            finish();
        }
        if(bluetoothAdapter!=null && !bluetoothAdapter.isEnabled()){
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(intent);
        }
        //开启蓝牙end
       mydaapter=new DeviceAdapter(this,bluetoothDevices);
       recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
       recyclerView.setAdapter(mydaapter);
       recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bluetoothAdapter.isDiscovering()){
                    bluetoothAdapter.cancelDiscovery();
                }
                   bluetoothAdapter.startDiscovery();
            }
        });

    }
}

  总结:  到这里传统蓝牙的开启和搜索小伙伴们应该都已经熟悉了,在下一篇中将记录传统蓝牙的配对与连接。

        还有,android6.0之后必须申请location权限,否则会搜索不到周围的蓝牙,切记~~~~

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值