野火电子论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9066|回复: 1

android蓝牙通信

[复制链接]
发表于 2019-1-21 20:02:50 | 显示全部楼层 |阅读模式
终于圆了蓝牙app的开发了,以前整过好几次,不过都没成功,虽然实现的功能很简单,也来分享一下吧。
实现的功能并没有搜索蓝牙,打开蓝牙和配对。所以在使用前要打开蓝牙并且配对好。
接受数据好像有点问题。。。。
需要添加的权限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>主要代码
//定义蓝牙适配器和socket
private BluetoothAdapter mBluetoothAdapter=null;
private BluetoothSocket btSock=null;//UUID固定 相当于端口号
private UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//蓝牙mac地址 通过其他蓝牙软件获取的
private String bt_addess="983:32:30:C9:A7";


//获取蓝牙适配器
    mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    final BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(bt_addess);
    //获取socket
    try {
        btSock=device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //取消当前设备发现查找进程
    mBluetoothAdapter.cancelDiscovery();
    try {
        btSock.connect();//连接
    } catch (IOException e) {
    e.printStackTrace();
}接下来就可以通过输入输出流进行通信了

布局文件
<?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"
    androidrientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:layout_marginTop="100dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/msg"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送"
        android:id="@+id/send"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            androidrientation="vertical"
            android:id="@+id/showmsg">

        </LinearLayout>
    </ScrollView>
</LinearLayout>

主要代码

package com.example.user.buletooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    //定义蓝牙适配器和socket
    private BluetoothAdapter mBluetoothAdapter=null;
    private BluetoothSocket btSock=null;

    private OutputStream bt_out=null;//输入输出流
    private InputStream bt_in=null;
    private byte[] buff=new byte[2048];//保存接受的数据
    private String rxStr;
    private int bytes=0;

    //UUID固定 相当于端口号
    private UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    //蓝牙mac地址 通过其他蓝牙软件获取的
    private String bt_addess="983:32:30:C9:A7";
    //UI组件
    private EditText txdMsg;//发送数据的输入框
    private Button send;//发送按键
    private LinearLayout rxMsg;//接受数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化UI组件
        txdMsg=findViewById(R.id.msg);
        send=findViewById(R.id.send);
        rxMsg=findViewById(R.id.showmsg);
        //获取蓝牙适配器
        mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        final BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(bt_addess);
        //获取socket
        try {
            btSock=device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //取消当前设备发现查找进程
        mBluetoothAdapter.cancelDiscovery();
        try {
            btSock.connect();//连接
        } catch (IOException e) {
        e.printStackTrace();
    }

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String str= "\r\n"+txdMsg.getText().toString();
                            bt_out=btSock.getOutputStream();
                            bt_out.write("hello world".getBytes());
                            bt_out.write(str.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.i("--4","fail");
                        }
                    }
                }).start();
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    bt_in=btSock.getInputStream();
                    while(true)
                    {
                        bytes=bt_in.read(buff);
                        rxStr=new String(buff,0,bytes);
                        handler.sendEmptyMessage(0x11);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.i("--5","fail");
                }
            }
        }).start();

    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            TextView tx=new TextView(MainActivity.this);
            tx.setText(rxStr);
            rxMsg.addView(tx);
        }
    };
}






Screenshot_20190121-195741.png

主要代码.zip

1.98 KB, 下载次数: 74

回复

使用道具 举报

发表于 2019-1-22 08:39:39 | 显示全部楼层
谢谢分享
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

联系站长|手机版|野火电子官网|野火淘宝店铺|野火电子论坛 ( 粤ICP备14069197号 ) 大学生ARM嵌入式2群

GMT+8, 2024-4-25 05:32 , Processed in 0.056929 second(s), 26 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表