(Android Studio)Android 手机设备与HC05 蓝牙设备的通信(成功案例+源码)

     代码我忘了在哪找的,只记得是把别人网上的代码稍微整理了一下,之后再加上自己的一些东西就成功了,对,反正就是成功了。很感谢我的一个哥们帮我组建了单片机和蓝牙设备硬件方面的东西,服务器那边也是他写的,灰常感谢...

在上次的博客中写的手机设备向蓝牙设备中发送消息,代码很乱不是很容易整理,这次我会把源码的地址放到文末,大家可以测试一下。

一,Android 手机蓝牙 与 Android 手机蓝牙

    从网上抠下来的那个代码,在一个APP中写了接受和发送,也就是说,两部手机用一个APP就可以通信,     

                                                         

很清楚的看到,两个手机一个APP,在未连接之下点击目标蓝牙会先配对,配对成功之后就可相互发送消息了。

二,Android 手机蓝牙向HC05设备发送数据

在这里之前有一个问题导致APP无法使用,最后看到有博客这样写,我是这样理解的,你的目标设备可以分几类,每一类又有几个专门的UUID,使得匹配,差不多就是这个意思。最后也成功了,也是用这个APK ,那接受的部分就交给我哥们了,啊哈哈哈.

下载地址:https://download.csdn.net/download/h2677lucy/10295861

layout_buletooth_seacher.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/l1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:orientation="vertical">

        <ListView
            android:id="@+id/lvDevices"
            android:layout_width="match_parent"
            android:layout_height="250dp" />

        <TextView
            android:id="@+id/text_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="[CURRENT ORDER]"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/receive_text"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#EEEEEE"
            android:gravity="center"
            android:textSize="20dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_below="@id/l1"
        android:id="@+id/l2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="3">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/red"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="红灯"
                android:textSize="10dp" />

            <Button
                android:id="@+id/green"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="10dp"
                android:layout_weight="1"
                android:text="绿灯"/>
            <Button
                android:id="@+id/blue"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="10dp"
                android:layout_weight="1"
                android:text="蓝灯" />
            <Button
                android:id="@+id/breath"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="10dp"
                android:layout_weight="1"
                android:text="呼吸灯" />
            <Button
                android:id="@+id/close_all_led"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="10dp"
                android:layout_weight="1"
                android:text="关灯" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"

            android:padding="5dp"
            android:layout_height="50dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:background="#31555555"
                android:text="亮度" />

            <SeekBar
                android:id="@+id/seekBar"
                style="@style/AlertDialog.AppCompat.Light"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_gravity="center_vertical"
                android:max="800"
                android:background="#31555555"
                android:progress="50" />
        </LinearLayout>

        <Button
            android:id="@+id/button"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="onClick_Search"
            android:text="搜索" />
    </LinearLayout>
    <LinearLayout
        android:layout_below="@id/l2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <TextView
            android:id="@+id/text_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="[RECEIVE ORDER]"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/msg"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#EEEEEE"
            android:gravity="center"
            android:textSize="20dp" />
    </LinearLayout>

</RelativeLayout>

BuletoothClientActivity

package com.managesoft.nullchen.buletoothdemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class BuletoothClientActivity extends Activity implements OnItemClickListener{
    // 获取到蓝牙适配器
    private BluetoothAdapter mBluetoothAdapter;
    // 用来保存搜索到的设备信息
    private List<String> bluetoothDevices = new ArrayList<String>();
    // ListView组件
    private ListView lvDevices;
    // ListView的字符串数组适配器
    private ArrayAdapter<String> arrayAdapter;
    // UUID,蓝牙建立链接需要的
    private final UUID MY_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");
    // 为其链接创建一个名称
    private final String NAME = "Bluetooth_Socket";
    // 选中发送数据的蓝牙设备,全局变量,否则连接在方法执行完就结束了
    private BluetoothDevice selectDevice;
    // 获取到选中设备的客户端串口,全局变量,否则连接在方法执行完就结束了
    private BluetoothSocket clientSocket;
    // 获取到向设备写的输出流,全局变量,否则连接在方法执行完就结束了
    private OutputStream os;
    // 服务端利用线程不断接受客户端信息
    private AcceptThread thread;
    //定义按钮
    //定义按钮
    private Button close_all_led;
    private Button red1 = null;
    private Button green1 = null;
    private Button blue1 = null;
    private Button breath = null;
    private TextView receive1;
    private SeekBar seekBar;
    private String LED_STATE = "A 红灯亮";
    private TextView re_msg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_buletooth_seacher);
        red1 = (Button)findViewById(R.id.red);
        green1 = (Button)findViewById(R.id.green);
        blue1 = (Button)findViewById(R.id.blue);
        receive1 = (TextView)findViewById(R.id.receive_text);
        close_all_led = (Button)findViewById(R.id.close_all_led);
        breath = (Button)findViewById(R.id.breath);
        seekBar = (SeekBar)findViewById(R.id.seekBar);
        re_msg = (TextView)findViewById(R.id.msg);

        red1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LED_STATE = "R";
                receive1.setText(LED_STATE);
            }
        });
        green1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LED_STATE = "G";
                receive1.setText(LED_STATE);
            }
        });
        blue1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LED_STATE = "B";
                receive1.setText(LED_STATE);
            }
        });
        close_all_led.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LED_STATE = "E";
                receive1.setText(LED_STATE);
            }
        });
        breath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LED_STATE = "H";
                receive1.setText(LED_STATE);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b){
                    LED_STATE ="{0:"+i+"}";
                    receive1.setText(LED_STATE);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        // 获取到蓝牙默认的适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 获取到ListView组件
        lvDevices = (ListView) findViewById(R.id.lvDevices);
        // 为listview设置字符换数组适配器
        arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                bluetoothDevices);
        // 为listView绑定适配器
        lvDevices.setAdapter(arrayAdapter);
        // 为listView设置item点击事件侦听
        lvDevices.setOnItemClickListener(this);

        // 用Set集合保持已绑定的设备   将绑定的设备添加到Set集合。
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        if (devices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : devices) {
                // 保存到arrayList集合中
                bluetoothDevices.add(bluetoothDevice.getName() + ":"
                        + bluetoothDevice.getAddress() + "\n");
            }
        }

        // 因为蓝牙搜索到设备和完成搜索都是通过广播来告诉其他应用的
        // 这里注册找到设备和完成搜索广播
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);

        // 实例接收客户端传过来的数据线程
        thread = new AcceptThread();
        // 线程开始
        thread.start();
    }

    //搜索蓝牙设备
    public void onClick_Search(View view) {
        setTitle("正在扫描...");
        // 点击搜索周边设备,如果正在搜索,则暂停搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        mBluetoothAdapter.startDiscovery();
    }
    // 注册广播接收者
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            // 获取到广播的action
            String action = intent.getAction();
            // 判断广播是搜索到设备还是搜索完成
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                // 找到设备后获取其设备
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 判断这个设备是否是之前已经绑定过了,如果是则不需要添加,在程序初始化的时候已经添加了
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    // 设备没有绑定过,则将其保持到arrayList集合中
                    bluetoothDevices.add(device.getName() + ":"
                            + device.getAddress() + "\n");
                    // 更新字符串数组适配器,将内容显示在listView中
                    arrayAdapter.notifyDataSetChanged();
                }
            } else if (action
                    .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                setTitle("搜索完成");
            }
        }
    };

    // 点击listView中的设备,传送数据
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // 获取到这个设备的信息
        String s = arrayAdapter.getItem(position);
        // 对其进行分割,获取到这个设备的地址
        String address = s.substring(s.indexOf(":") + 1).trim();
        Log.d("TAG",address);
        // 判断当前是否还是正在搜索周边设备,如果是则暂停搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 如果选择设备为空则代表还没有选择设备
        if (selectDevice == null) {
            //通过地址获取到该设备
            selectDevice = mBluetoothAdapter.getRemoteDevice(address);
        }
        // 这里需要try catch一下,以防异常抛出
        try {
            // 判断客户端接口是否为空
            if (clientSocket == null) {
                // 获取到客户端接口
                clientSocket = selectDevice
                        .createRfcommSocketToServiceRecord(MY_UUID);
                // 向服务端发送连接
                clientSocket.connect();
                // 获取到输出流,向外写数据
                os = clientSocket.getOutputStream();

            }
            // 判断是否拿到输出流
            if (os != null) {
                // 需要发送的信息
                //String text = "我传过去了";
                // 以utf-8的格式发送出去
                os.write(LED_STATE.getBytes("UTF-8"));
            }
            // 吐司一下,告诉用户发送成功
            Toast.makeText(this, "发送信息成功,请查收", 0).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // 如果发生异常则告诉用户发送失败
            Toast.makeText(this, "发送信息失败", 0).show();
        }

    }

    // 创建handler,因为我们接收是采用线程来接收的,在线程中无法操作UI,所以需要handler
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            // 通过msg传递过来的信息,吐司一下收到的信息
           // Toast.makeText(BuletoothClientActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
            re_msg.setText((String)msg.obj);
        }
    };

    // 服务端接收信息线程
    private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;// 服务端接口
        private BluetoothSocket socket;// 获取到客户端的接口
        private InputStream is;// 获取到输入流
        private OutputStream os;// 获取到输出流

        public AcceptThread() {
            try {
                // 通过UUID监听请求,然后获取到对应的服务端接口
                serverSocket = mBluetoothAdapter
                        .listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void run() {
            try {
                // 接收其客户端的接口
                socket = serverSocket.accept();
                // 获取到输入流
                is = socket.getInputStream();
                // 获取到输出流
                os = socket.getOutputStream();

                // 无线循环来接收数据
                while (true) {
                    // 创建一个128字节的缓冲
                    byte[] buffer = new byte[128];
                    // 每次读取128字节,并保存其读取的角标
                    int count = is.read(buffer);
                    // 创建Message类,向handler发送数据
                    Message msg = new Message();
                    // 发送一个String的数据,让他向上转型为obj类型
                    msg.obj = new String(buffer, 0, count, "utf-8");
                    // 发送数据
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        }
    }
}
最后感谢我的好哥们和那个网友。
  • 38
    点赞
  • 262
    收藏
    觉得还不错? 一键收藏
  • 156
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
Android Studio中连接HC-05蓝牙模块,需要使用Android蓝牙API和串口通信协议,具体步骤如下: 1. 在AndroidManifest.xml文件中添加蓝牙权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> ``` 2. 在应用程序中使用BluetoothAdapter类来获取本地蓝牙适配器: ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 3. 使用BluetoothAdapter对象来搜索HC-05蓝牙模块: ```java bluetoothAdapter.startDiscovery(); ``` 4. 连接HC-05蓝牙模块。首先需要获取HC-05蓝牙模块的MAC地址,然后使用BluetoothDevice类来连接蓝牙模块: ```java String mac = "00:11:22:33:44:55"; // HC-05蓝牙模块的MAC地址 BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mac); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); ``` 其中,uuid是HC-05蓝牙模块服务的UUID,可以在HC-05模块的说明书中找到。 5. 使用IO流进行数据的传输和通信。可以使用InputStream和OutputStream来进行数据的读写操作: ```java InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); byte[] buffer = new byte[1024]; int bytes; bytes = inputStream.read(buffer); outputStream.write(buffer, 0, bytes); ``` 6. 最后,在应用程序退出时需要关闭蓝牙连接: ```java socket.close(); ``` 以上是Android Studio连接HC-05蓝牙模块的基本步骤,具体的实现过程需要根据应用程序的需求和实际情况进行相应的调整和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 156
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值