Bluetooth App Design 2: Use Android Studio to make a Bluetooth software (including: code implementation, etc.)

Foreword: There are three articles in the design of Bluetooth chat App (1. UI interface design, 2. Realization of Bluetooth search pairing connection, 3. Bluetooth connection chat). This article is: 2. Realization of Bluetooth search pairing connection.

Course 1: Android Studio Xiaobai installation tutorial, and the debugging and running of the first Android project case "Hello World"
Course 2: Bluetooth Chat App Design 1: Android Studio to make Bluetooth chat communication software (UI interface design)
Course 3: Bluetooth Chat App design 2: Android Studio making Bluetooth chat communication software (Bluetooth search)
Course 4: Bluetooth chat App design 3: Android Studio making Bluetooth chat communication software (end, Bluetooth connection chat, popular explanation of Bluetooth communication combined with life situations, and code Function realization, detailed content, easy to understand explanation)

Involved files:

Create a new package "BluetoothPackage" in the java directory, and create two new files in the package: "Constant.java" and "BluetoothController.java", as shown in the figure:
insert image description here

1. Add dependencies in 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" />

2. Create a new file Constant.java to pre-define some constants that may be used below. The complete code is as follows:

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;
}

3. Create a new file BlueToothController.java, the complete code is as follows:

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

4. The complete code of MainActivity.java is as follows:

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

Five, renderings
insert image description here

6. Complete project sharing
Project link: https://pan.baidu.com/s/1z8tW3aA7a5knKxiwlE3BFw Extraction code: 3d53

7. Realization of Bluetooth chat function
You can see the course Bluetooth chat App Design 3: Android Studio to make Bluetooth chat communication software (end, Bluetooth connection chat, popular explanation of Bluetooth communication combined with life situations, and code function realization, detailed content, easy to explain Understand)

Guess you like

Origin blog.csdn.net/weiybin/article/details/130352162