蓝牙App设计2:使用Android Studio制作一个蓝牙软件(包含:代码实现等)

这篇具有很好参考价值的文章主要介绍了蓝牙App设计2:使用Android Studio制作一个蓝牙软件(包含:代码实现等)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言:蓝牙聊天App设计全部有三篇文章(一、UI界面设计,二、蓝牙搜索配对连接实现,三、蓝牙连接聊天),这篇文章是:二、蓝牙搜索配对连接实现。

课程1:Android Studio小白安装教程,以及第一个Android项目案例“Hello World”的调试运行
课程2:蓝牙聊天App设计1:Android Studio制作蓝牙聊天通讯软件(UI界面设计)
课程3:蓝牙聊天App设计2:Android Studio制作蓝牙聊天通讯软件(蓝牙搜索)
课程4:蓝牙聊天App设计3:Android Studio制作蓝牙聊天通讯软件(完结,蓝牙连接聊天,结合生活情景进行蓝牙通信的通俗讲解,以及代码功能实现,内容详细,讲解通俗易懂)

涉及文件:

在java目录下新建一个包“BluetoothPackage”,并在该包内新建两个新文件:“Constant.java”和“BluetoothController.java”,如图所示:
蓝牙App设计2:使用Android Studio制作一个蓝牙软件(包含:代码实现等)

一、在AndroidManifest.xml中添加依赖:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />

二、新建文件Constant.java,用来预先定义一些下面可能需要用到的常量,完整代码如下:

package com.example.wyb.btw3.connect;
/**
 * Created by WYB on 2023/4/24.
 */
public class Constant {
    public static final String CONNECTTION_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    /**
     * 开始监听
     */
    public static final int MSG_START_LISTENING = 1;

    /**
     * 结束监听
     */
    public static final int MSG_FINISH_LISTENING = 2;
    /**
     * 有客户端连接
     */
    public static final int MSG_GOT_A_CLINET = 3;

    /**
     * 连接到服务器
     */
    public static final int MSG_CONNECTED_TO_SERVER = 4;
    /**
     * 获取到数据
     */
    public static final int MSG_GOT_DATA = 5;
    /**
     * 出错
     */
    public static final int MSG_ERROR = -1;
}

三、新建文件BlueToothController .java,完整代码如下:

package com.example.wyb.btw3;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by WYB on 2023/4/24.
 */
public class BlueToothController {
    private BluetoothAdapter mAdapter;
    public BlueToothController(){
        mAdapter = BluetoothAdapter.getDefaultAdapter();
    }
    /*
        打开蓝牙设备
    */
    public void  turnOnBlueTooth(Activity activity, int requestCode){
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(intent,requestCode);
    }
    /*
        查找未绑定的蓝牙设备
    */
    public void findDevice(){
        assert (mAdapter!=null);
        mAdapter.startDiscovery();
    }
    /*
        查看已绑定的蓝牙设备
    */
    public List<BluetoothDevice> getBondedDeviceList(){
        return new ArrayList<>(mAdapter.getBondedDevices());
    }
}

四、MainActivity .java完整代码如下:

package com.example.wyb.bluetoothchatui;
import android.Manifest;
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.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import BluetoothPackage.BluetoothController;
import MyClass.DeviceAdapter;
import MyClass.DeviceClass;
public class MainActivity extends AppCompatActivity {
    private DeviceAdapter mAdapter1,mAdapter2;
    private List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表
    private List<DeviceClass> mfindDeviceList = new ArrayList<>();//搜索到的所有未绑定设备保存为列表
    private BluetoothController mbluetoothController = new BluetoothController();
    private Toast mToast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init_Bluetooth();//开启蓝牙相关权限
        init_Filter();//初始化广播并打开
        Init_listView();//初始化设备列表
        show_bondDeviceList();//搜索展示已经绑定的蓝牙设备
    }
    //初始化蓝牙权限
    private void Init_Bluetooth(){
        //开启蓝牙位置共享
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
        mbluetoothController.enableVisibily(this);//让其他蓝牙看得到我
        mbluetoothController.turnOnBlueTooth(this,0);//打开蓝牙
    }
    //初始化列表,适配器的加载
    public void Init_listView(){
        mAdapter1 = new DeviceAdapter(MainActivity.this, R.layout.device_item, mbondDeviceList);
        ListView listView1 = (ListView)findViewById(R.id.listview1);
        listView1.setAdapter(mAdapter1);
        mAdapter1.notifyDataSetChanged();
        //listView1.setOnItemClickListener(toMainActivity2);//设备点击事件,点击设备名称后执行toMainActivity2
        mAdapter2 = new DeviceAdapter(MainActivity.this, R.layout.device_item, mfindDeviceList);
        ListView listView2 = (ListView)findViewById(R.id.listview2);
        listView2.setAdapter(mAdapter2);
        mAdapter2.notifyDataSetChanged();
    }
    //开启广播
    private void init_Filter(){
        IntentFilter filter = new IntentFilter();
        //开始查找
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //结束查找
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //查找设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //设备扫描模式改变
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        //绑定状态
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(receiver, filter);
    }
    //广播内容
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                setSupportProgressBarIndeterminateVisibility(true);
                change_Button_Text("搜索中...","DISABLE");
                mfindDeviceList.clear();
                mAdapter2.notifyDataSetChanged();
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                setProgressBarIndeterminateVisibility(false);
                change_Button_Text("搜索设备","ENABLE");
            }
            //查找设备
            else if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                change_Button_Text("搜索中...","DISABLE");
                //查找到一个设备就添加到列表类中
                mfindDeviceList.add(new DeviceClass(device.getName(),device.getAddress()));
                mAdapter2.notifyDataSetChanged();//刷新列表适配器,将内容显示出来
            }
            else if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)){
                int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,0);
                if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
                    setProgressBarIndeterminateVisibility(true);
                }
                else {
                    setProgressBarIndeterminateVisibility(false);
                }
            }
            else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice remoteDecive = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(remoteDecive == null){
                    return;
                }
                int status = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, 0);
                if(status == BluetoothDevice.BOND_BONDED) {
                    showToast("已绑定" + remoteDecive.getName());
                } else if(status == BluetoothDevice.BOND_BONDING) {
                    showToast("正在绑定" + remoteDecive.getName());
                } else if(status == BluetoothDevice.BOND_NONE) {
                    showToast("未绑定" + remoteDecive.getName());
                }
            }
        }
    };
    //点击开始查找蓝牙设备
    public View findDevice(View view){
        mbluetoothController.findDevice();
        return view;
    }
    //查找已绑定的蓝牙设备
    private void show_bondDeviceList(){
        mbondDeviceList.clear();
        List<BluetoothDevice> bondDevices = mbluetoothController.getBondedDeviceList();//查找已绑定设备
        for(int i=0;i<bondDevices.size();i++){
            mbondDeviceList.add(new DeviceClass(bondDevices.get(i).getName(),bondDevices.get(i).getAddress()));
        }
        mAdapter1.notifyDataSetChanged();
    }
    //点击按键搜索后按键的变化
    private void change_Button_Text(String text,String state){
        Button button = (Button)findViewById(R.id.button1);
        if("ENABLE".equals(state)){
            button.setEnabled(true);
            button.getBackground().setAlpha(255); //0~255 之间任意调整
            button.setTextColor(ContextCompat.getColor(this, R.color.black));
        }
        else {
            button.setEnabled(false);
            button.getBackground().setAlpha(150); //0~255 之间任意调整
            button.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
        }
        button.setText(text);
    }
    //点击设备后执行的函数
    private AdapterView.OnItemClickListener toMainActivity2 =new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
            Intent intent = new Intent(MainActivity.this,Main2Activity.class);
            startActivity(intent);
        }
    };
    //设置toast的标准格式
    private void showToast(String text){
        if(mToast == null){
            mToast = Toast.makeText(this, text,Toast.LENGTH_SHORT);
            mToast.show();
        }
        else {
            mToast.setText(text);
            mToast.show();
        }
    }
}

五、效果图
蓝牙App设计2:使用Android Studio制作一个蓝牙软件(包含:代码实现等)

六、完整项目分享
项目链接:https://pan.baidu.com/s/1z8tW3aA7a5knKxiwlE3BFw 提取码:3d53

七、蓝牙聊天功能实现
可以看课程蓝牙聊天App设计3:Android Studio制作蓝牙聊天通讯软件(完结,蓝牙连接聊天,结合生活情景进行蓝牙通信的通俗讲解,以及代码功能实现,内容详细,讲解通俗易懂)文章来源地址https://www.toymoban.com/news/detail-514170.html

到了这里,关于蓝牙App设计2:使用Android Studio制作一个蓝牙软件(包含:代码实现等)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Android Studio制作手机App:通过手机蓝牙(Bluetooth)与STM32上的低功耗蓝牙(HC-42)连接通信,实现手机端对单片机的控制。

    背景: 本文的内容是针对单片机蓝牙模块(HC-42)开发的手机App。在这之前,我想先声明一点,手机与手机间的蓝牙连接方式”与“手机与HC间的蓝牙连接方式”是不一样的。原因就是手机搭配的是“经典蓝牙”模块,HC等蓝牙属于“低功耗蓝牙”模块。(二者的区别想了解的

    2024年02月04日
    浏览(43)
  • 使用Android studio完成简易智能家居APP的制作(含源码工程包)

     (填下坑,把我之前答应大家的完整软件代码翻出来,供大家一起学习) 可以看看实现效果先:   智能家居APP展示视频(含源码)_哔哩哔哩_bilibili 目录 项目说明 功能介绍 系统功能需求 具体实现的软件功能  1、地图定位 2、蓝牙按钮 3、远端控制  核心代码展示说明 蓝牙

    2024年02月06日
    浏览(35)
  • 使用Android Studio 利用极光推送SDK 制作手机 APP 实现远程测试技术 (第一部)

    总参考文章:https://blog.csdn.net/qq_38436214/article/details/105073213 Android Studio 安装配置教程 - Windows(详细版) 1.JDK 安装与环境变量配置(Win10详细版) 《jdk-8u371-windows-i586.exe》 https://blog.csdn.net/qq_38436214/article/details/105071088 此时会让登录账号密码: https://login.oracle.com/mysso/signon.jsp 账号:

    2024年02月03日
    浏览(37)
  • 基于Android平台的记事本软件(Android Studio项目+报告+app文件)

    移动应用开发技术 期末考核报告 题    目:         基于 Android 平台的记事本软件              学生姓名                               学生学号                               专      业                            班     级

    2024年02月08日
    浏览(40)
  • Android studio 简单登录APP设计

    一、登录界面: 二、xml布局设计:

    2024年01月17日
    浏览(42)
  • Android Studio:一个简单的计算器app的实现过程<初级>

    📌Android Studio 专栏正在持续更新中,案例的原理图解析、各种模块分析💖这里都有哦,同时也欢迎大家订阅专栏,获取更多详细信息哦✊✊✊ ✨个人主页:零小唬的博客主页 🥂欢迎大家 👍点赞 📨评论 🔔收藏 ✨作者简介:20级计算机专业学生一枚,来自宁夏,可能会去

    2024年02月01日
    浏览(96)
  • Android Studio:一个简单的米英尺单位转化app的实现过程

    📌Android Studio 专栏正在持续更新中,案例的原理图解析、各种模块分析💖这里都有哦,同时也欢迎大家订阅专栏,获取更多详细信息哦✊✊✊ ✨个人主页:零小唬的博客主页 🥂欢迎大家 👍点赞 📨评论 🔔收藏 ✨作者简介:20级计算机专业学生一枚,来自宁夏,想从事前

    2023年04月09日
    浏览(31)
  • 基于Android Studio的日记App课程设计

    目录 一、课程设计介绍 二、系统模块介绍及展示 1.系统目录结构图 2.数据库设计 3.系统模块测试 (1)用户认证模块测试 (2)日记管理模块测试 (3)清单管理模块测试 (4)个人信息模块测试 三、代码展示         在这样的背景下,开发一个基于Android的生活记事本A

    2024年02月03日
    浏览(41)
  • 基于Android的学生信息管理App设计(Android studio开发)

    目 录 一、 题目选择(题目、选题意义) 3 二、 设计目的 3 1、 初衷 3 2、 结合实际 3 3、 使用工具 3 三、 最终页面效果展示 4 1、 登陆界面 4 2、 主界面 5 3、 各个功能模块 6 四、 各部分设计 11 1、活动页面Activity布局文件 11 2、Activity的编程 13 五、 总结 17 题目:基于Android的

    2024年02月08日
    浏览(89)
  • 基于Android studio的校园小助手app设计

    基于Android的校园小助手系统设计,包含如下主要功能: 校园资讯 校园天气(和风天气api) 外出申请 我的记账本 课程表 考试安排 基于Android studio的校园小助手系统设计

    2024年02月11日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包