美文网首页
安卓蓝牙 HC-06蓝牙模块 最简单例程

安卓蓝牙 HC-06蓝牙模块 最简单例程

作者: 招风小妖怪 | 来源:发表于2019-10-15 21:13 被阅读0次

功能代码看不懂看这篇文章
https://www.jianshu.com/p/25e413d433d7
布局代码看不懂看这篇文章https://www.jianshu.com/p/008c0d9752ab

项目说明:手机和HC-06蓝牙模块通信,其他模块行不行你测试一下,我也不知道,上图

Screenshot_2019-10-15-20-59-56-287_com.example.le(1).jpg

app长这样,功能描述

1,先手动开启蓝牙,并配对设备
2、点击查看已经配对设备按钮,在屏幕上打印出已经配对的设备名称和mac地址
3、长按复制你要连接的设备mac地址到连接按钮签名的框框,注意前后不要有空格
4、点击连接,不管成功和失败都会弹出提示
5、连接成功后可以点击发送按钮发送消息,蓝牙模块会串口输出数据。(没有连接就点击会闪退,为了代码简单,没有做处理)

蓝牙模块长这样 IMG_20191015_210042.jpg

蓝牙串口输出

image.png

布局代码

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout 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=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="12dp"
        android:layout_y="476dp"
        android:text="消息接收框下(边框不会加)"
        tools:layout_editor_absoluteX="21dp"
        tools:layout_editor_absoluteY="30dp" />

    <Button
        android:id="@+id/connectBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/name"
        android:layout_marginStart="-83dp"
        android:layout_marginTop="-101dp"
        android:layout_toEndOf="@+id/name"
        android:layout_x="306dp"
        android:layout_y="10dp"
        android:onClick="conncet"
        android:text="连接"
        tools:layout_editor_absoluteX="281dp"
        tools:layout_editor_absoluteY="434dp" />

    <TextView
        android:id="@+id/txv"
        android:layout_width="388dp"
        android:layout_height="294dp"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="207dp"
        android:layout_marginRight="207dp"
        android:layout_marginBottom="265dp"
        android:layout_x="10dp"
        android:layout_y="175dp"
        android:lineSpacingExtra="14sp"
        android:textColor="@color/colorPrimary"
        android:textIsSelectable="true"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        tools:layout_editor_absoluteY="242dp" />

    <EditText
        android:id="@+id/sendEDTX"
        android:layout_width="259dp"
        android:layout_height="wrap_content"
        android:layout_x="11dp"
        android:layout_y="524dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="hello"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="413dp" />

    <Button
        android:id="@+id/sendBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="298dp"
        android:layout_y="519dp"
        android:onClick="send"
        android:text="发送"
        tools:layout_editor_absoluteX="274dp"
        tools:layout_editor_absoluteY="421dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="155dp"
        android:layout_y="157dp"
        android:text="消息接收框上(边框不会加)"
        tools:layout_editor_absoluteX="21dp"
        tools:layout_editor_absoluteY="30dp" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="23dp"
        android:layout_y="15dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="20:19:05:14:22:94"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="8dp" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="248dp"
        android:layout_y="82dp"
        android:text="查看已经配对的设备"
        tools:layout_editor_absoluteX="249dp"
        tools:layout_editor_absoluteY="89dp"
        android:onClick="seePeiDui"/>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="18dp"
        android:layout_y="111dp"
        android:text="复制mac地址到连接的框框里"
        tools:layout_editor_absoluteX="39dp"
        tools:layout_editor_absoluteY="121dp" />

</AbsoluteLayout>

功能代码

package com.example.leaf.myapplication;



import android.bluetooth.BluetoothAdapter;


import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Set;
import java.util.UUID;

import static java.lang.Thread.*;


public class MainActivity extends AppCompatActivity {


    private BluetoothAdapter mBluetoothAdapter;//你自己的手机蓝牙
    private BluetoothDevice device;//你准备连接哪个蓝牙
    private BluetoothSocket socket;//连接成功后返回的socket服务,类似TCP的socket
    private String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号,
    private InputStream is;
    //这个自行百度,不同的UUID可以提供不同的服务,
    //我这里这个UUID说明使用的是串口服务


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


     //=================================================================
    //因为这个函数在软件启动时自动运行,所以在这里新建一个线程用来接收数据
        new Thread(){
            public void run(){
                int num = 0;
                byte[] buffer = new byte[1024];
                byte[] buffer_new = new byte[1024];
                int i = 0;
                int n = 0;
                while(true)
                {
                    try {
                        if(socket!=null && socket.isConnected()) {
                            num = is.read(buffer);//获取本次读取长度
                            for(i=0;i<num;i++){
                                if((buffer[i] == 0x0d)&&(buffer[i+1]==0x0a)){
                                    //收到0x0d 0x0a才算结束,你也可以自定义结束符号
                                    //到这里说明接收结束,你可以做自己的操作
                                    String str = new String(buffer_new, 0, n);
                                    System.out.println("=================:"+str+"---"+n);
                                    TextView text2= (TextView) findViewById(R.id.txv);
                                    text2.setText(text2.getText()+"\n"+str);
                                    //==========================
                                    i++;//一定要加上,因为本次读取0x0d,下一次不用读取0x0a,让他跳过
                                    n=0;
                                }else{
                                    buffer_new[n] = buffer[i];
                                    n++;
                                }

                            }
                        }

                    }catch(IOException e){
                        System.out.println("=========================接收出错===============================");

                    }
                }
            }
        }.start();
    }

    public void conncet(View v){     // 连接按钮响应
        try{
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            //获取本机蓝牙设备
            EditText macAddr= (EditText) findViewById(R.id.editText3);
            String remoteDevMac = macAddr.getText().toString();
            device = mBluetoothAdapter.getRemoteDevice(remoteDevMac);
            //通过地址获取已配对的蓝牙设备
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
            //设置准备连接的设备的UUID,我指令设置的是串口服务UUID
            socket.connect();
            //连接远端蓝牙设备
            is = socket.getInputStream();
            //获取输入流
            Toast.makeText(getApplicationContext(), "连接成功!", Toast.LENGTH_LONG).show();

        }catch(IOException e){
            Toast.makeText(getApplicationContext(), "连接失败!", Toast.LENGTH_LONG).show();
        }
    }

    public void send(View v){     // 发送按钮响应
        try{
            OutputStream os = socket.getOutputStream();
            //获取连接设备的输出流
            EditText sendDat= (EditText) findViewById(R.id.sendEDTX);
            String sendDatStr = sendDat.getText().toString();
            os.write(sendDatStr.getBytes());
            //发送消息
            Toast.makeText(getApplicationContext(), "发送成功!", Toast.LENGTH_LONG).show();
        }catch(IOException e){
            Toast.makeText(getApplicationContext(), "发送失败!", Toast.LENGTH_LONG).show();
        }
    }
    public void seePeiDui(View v){     // 查看已经配对的设备
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0){
            for(BluetoothDevice device:pairedDevices){
                // 把名字和地址取出来添加到适配器中
                System.out.println("\n===="+device.getName()+" : "+ device.getAddress());
                TextView text2= (TextView) findViewById(R.id.txv);
                text2.setText(text2.getText()+"\n"+device.getName()+" : "+ device.getAddress());
            }
        }
    }
}

相关文章

  • 安卓蓝牙 HC-06蓝牙模块 最简单例程

    功能代码看不懂看这篇文章https://www.jianshu.com/p/25e413d433d7布局代码看不懂...

  • android蓝牙编程牛刀小试

    简述 在项目中也曾用到安卓蓝牙,主要是与蓝牙模块进行通信,所以简单的进行总结,做下笔记,以备不时之需。 开启与设置...

  • iOS -- 低功耗蓝牙

    蓝牙介绍:使用的是网上购买的一个简单的蓝牙模块蓝牙模块地址:蓝牙模块地址USB转TTL:转接模块地址 AT-09蓝...

  • android蓝牙专题

    深入了解Android蓝牙Bluetooth ——《总结篇》 安卓蓝牙应用程序编写步骤 蓝牙 bluetooth-...

  • android L(5.0)可以作为外设通讯了

    关于: 安卓能否与iphone通过蓝牙4.0(BLE)通讯? 安卓手机与iphone能通过蓝牙4.0进行连接吗? ...

  • 安卓获取手机本身的蓝牙MAC地址

    一、安卓6.0之前的版本 获取蓝牙适配器BluetoothAdpater 或者 二、安卓6.0之后的版本 打开蓝牙...

  • HC-06蓝牙模块配置

    HC-06蓝牙模块进行配置 串口软件:O-ComTool V1.1.1 修改波特率 发送:AT+BAUD8 返回:...

  • 安卓学习笔记1

    安卓蓝牙2.0 程序可以兼容 蓝牙4.0蓝牙 1.首先连接蓝牙 通过以下的代码: 这里面是找到蓝牙设备的代码 找到...

  • Android 蓝牙模块的封装

    引入 蓝牙4.0为低功耗蓝牙,从安卓4.4版本开始支持。安卓中蓝牙的基本使用在官方的指南中有详细的说明,地址如下:...

  • 安卓手机如何通过蓝牙跟Mac互传文件?

    安卓到 Mac 前提需要 Mac 上打开「系统偏好设置-共享-蓝牙共享」,打开蓝牙共享。 然后从安卓手机里选择文件...

网友评论

      本文标题:安卓蓝牙 HC-06蓝牙模块 最简单例程

      本文链接:https://www.haomeiwen.com/subject/lblemctx.html