蓝牙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”,如图所示:
在这里插入图片描述

一、在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();
        }
    }
}

五、效果图
在这里插入图片描述

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

七、蓝牙聊天功能实现
可以看课程蓝牙聊天App设计3:Android Studio制作蓝牙聊天通讯软件(完结,蓝牙连接聊天,结合生活情景进行蓝牙通信的通俗讲解,以及代码功能实现,内容详细,讲解通俗易懂)

猜你喜欢

转载自blog.csdn.net/weiybin/article/details/130352162
今日推荐