Android strudio 蓝牙打印开发代码示例()
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /><!--this的检查项--> <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/> <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-permission android:name="android.permission.BLUETOOTH_ADVERTISE"/> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.BtPrint" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:background="#E8E8E8"> <TextView android:id="@+id/tv_blt" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="蓝牙功能测试:"/> <Button android:id="@+id/bt_blt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="打开蓝牙1"/> <Button android:id="@+id/bt_print" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="打印测试"/> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <Button android:id="@+id/button3" android:layout_width="0dp" android:layout_height="wrap_content" android:text="是否支持蓝牙" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button4" android:layout_width="0dp" android:layout_height="wrap_content" android:text="当前蓝牙状态" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/guideline2" app:layout_constraintTop_toTopOf="parent" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_begin="205dp" /> <Button android:id="@+id/button7" android:layout_width="0dp" android:layout_height="wrap_content" android:text="打开蓝牙" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button3" /> <Button android:id="@+id/button8" android:layout_width="0dp" android:layout_height="wrap_content" android:text="关闭蓝牙" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/guideline2" app:layout_constraintTop_toBottomOf="@+id/button4" /> <Button android:id="@+id/button9" android:layout_width="0dp" android:layout_height="wrap_content" android:text="使蓝牙可见" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button7" /> <Button android:id="@+id/button10" android:layout_width="0dp" android:layout_height="wrap_content" android:text="搜索可见蓝牙" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button9" /> <Button android:id="@+id/button11" android:layout_width="0dp" android:layout_height="wrap_content" android:text="查看已绑定蓝牙" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/guideline2" app:layout_constraintTop_toBottomOf="@+id/button9" /> <ListView android:id="@+id/listview1" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="wrap_content" android:background="#00BCD4" android:gravity="center" android:text="蓝牙列表" android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button10" /> </androidx.constraintlayout.widget.ConstraintLayout> </LinearLayout>
MainActivity.java

package com.lingrui.btprint; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; 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.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // 弹窗 private Toast mToast; // 常量 private static final int REQ_PERMISSION_CODE = 1; // 蓝牙权限列表 public ArrayList<String> requestList = new ArrayList<>(); // 搜索蓝牙广播 private IntentFilter foundFilter; // public ArrayAdapter adapter1; //定义一个列表,存蓝牙设备的地址。 public ArrayList<String> arrayList = new ArrayList<>(); //定义一个列表,存蓝牙设备地址,用于显示。 public ArrayList<String> deviceName = new ArrayList<>(); private BluetoothSocket btSocket; private String TAG = ""; public static final int RECV_VIEW = 0; public static final int NOTICE_VIEW = 1; private static OutputStream outputStream = null; public static String MY_UUID = "DC:0D:30:D6:0F:50"; /** * 代表本地蓝牙适配器(蓝牙无线电)。BluetoothAdapter是所有蓝牙交互的入口。 * 使用这个你可以发现其他蓝牙设备,查询已配对的设备列表, * 使用一个已知的MAC地址来实例化一个BluetoothDevice, * 以及创建一个BluetoothServerSocket来为监听与其他设备的通信。 */ private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); /** * 代表一个远程蓝牙设备,使用这个来请求一个与远程设备的BluetoothSocket连接, * 或者查询关于设备名称、地址、类和连接状态等设备信息。 */ private BluetoothDevice mBluetoothDevice = null; /** * 代表一个蓝牙socket的接口(和TCP Socket类似)。这是一个连接点, * 它允许一个应用与其他蓝牙设备通过InputStream和OutputStream交换数据。 */ private BluetoothSocket mBluetoothSocket = null; //替换旧版本中的startactivityresult public ActivityResultLauncher<Intent> register; ActivityResultLauncher<Intent> startBlueTooth = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if (result == null) { Log.e("error:", "打开失败"); } else { if (result.getResultCode() == RESULT_CANCELED) { Log.d("debug", "用户取消"); } } } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); //点击蓝牙按钮 Button btBlt = findViewById(R.id.bt_blt); btBlt.setOnClickListener(this); // 通过id获取“是否支持蓝牙”按钮 Button button_3 = (Button) findViewById(R.id.button3); // 是否支持蓝牙按钮点击事件处理函数 button_3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 获取蓝牙权限 getPermision(); // 判断是否支持蓝牙 boolean ret = isSupportBlueTooth(); // 弹窗显示结果 showToast("是否支持蓝牙" + ret); } }); //当前蓝牙状态 Button button_4 = findViewById(R.id.button4); button_4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取蓝牙权限 getPermision(); //显示蓝牙状态; boolean ret = getBlueToothStatus(); showToast("当前蓝牙状态:" + ret); } }); //打开蓝牙按钮点击事件 Button bt_open = findViewById(R.id.button7); bt_open.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean ret = turnOnBlueTooth(MainActivity.this, 1); showToast("蓝牙开启状态:" + ret); } }); //关闭蓝牙点击事件 Button bt_close = findViewById(R.id.button8); bt_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { turnOffBlueTooth(); } }); //打印 Button bt_print = findViewById(R.id.bt_print); bt_print.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Log.d("debug", "蓝牙打印按钮0"); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //getBondedDevices 方法返回已经配对的蓝牙设备的集合。通过遍历集合,可以获取设备的名称和地址等信息 //或者,根据已绑定的名称和网卡信息,强制指定; for (BluetoothDevice device : pairedDevices) { String deviceName = device.getName(); String deviceAddress = device.getAddress(); // 处理找到的设备信息,这是最后一个绑定的设备,如果有多个绑定的打印机,应该做一个选择的界面,让人手工点击,或选择默认的 mBluetoothDevice = device; } BluetoothSocket socket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID)); Log.d("debug", MY_UUID); socket.connect(); //连接成功后,我们可以通过蓝牙连接发送打印指令给蓝牙标签打印机。 OutputStream outputStream = socket.getOutputStream(); String ptString="壮骨麝香止痛膏\n"; outputStream.write(ptString.getBytes("GBK")); } catch (Exception ex) { showToast("打印出错:"); } } }); //使蓝牙可见点击事件 Button bt_visable = findViewById(R.id.button9); bt_visable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { enableVisibly(MainActivity.this); } }); // 通过id获取”搜索可见蓝牙“按钮 Button button_6 = (Button) findViewById(R.id.button10); // 绑定按钮点击事件处理函数 button_6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 获取蓝牙权限 getPermision(); // 注册广播 registerReceiver(bluetoothReceiver, foundFilter); // 初始化各列表 arrayList.clear(); deviceName.clear(); adapter1.notifyDataSetChanged(); // 开始搜索 findDevice(); } }); //搜索蓝牙的广播 foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); // 获取ListView组件 ListView listView = (ListView) findViewById(R.id.listview1); // 实例化ArrayAdapter对象 adapter1 = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, deviceName); // 添加到ListView组件中 listView.setAdapter(adapter1); // 通过id获取”查看已绑定蓝牙“按钮 Button button_7 = (Button) findViewById(R.id.button11); // 绑定按钮点击事件处理函数 button_7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 获取蓝牙权限 getPermision(); // 初始化各列表 deviceName.clear(); arrayList.clear(); adapter1.notifyDataSetChanged(); // 获取已绑定蓝牙 ArrayList<BluetoothDevice> bluetoothDevices = getBondedDeviceList(); // 更新列表 for (int i = 0; i < bluetoothDevices.size(); i++) { BluetoothDevice device = bluetoothDevices.get(i); arrayList.add(device.getAddress()); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } if (device.getBondState() == 12) { deviceName.add("设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"); } else if (device.getBondState() == 10) { deviceName.add("设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"); } else { deviceName.add("设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未知" + "\n"); } adapter1.notifyDataSetChanged(); } } }); //列表框监听事件 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { CharSequence content = ((TextView) view).getText(); String con = content.toString(); String[] conArray = con.split("\n"); String rightStr = conArray[1].substring(5, conArray[1].length()); BluetoothDevice device = find_device(rightStr); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } if (device.getBondState() == 10) { mBluetoothAdapter.cancelDiscovery(); ; String s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"; deviceName.remove(s); device.createBond(); s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"; deviceName.add(s); adapter1.notifyDataSetChanged(); showToast("配对:" + device.getName()); } else { mBluetoothAdapter.cancelDiscovery(); ; String s2 = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"; if (deviceName.contains(s2)) { unpairDevice(device); deviceName.remove(s2); s2 = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"; deviceName.add(s2); adapter1.notifyDataSetChanged(); showToast("取消配对:" + device.getName()); } } } }); } /** * 是否支持蓝牙 * @return true支持,false不支持 */ public boolean isSupportBlueTooth() { // 若支持蓝牙,则本地适配器不为null if (mBluetoothAdapter != null) { return true; } // 否则不支持 else { return false; } } /** * 判断当前蓝牙状态 * @return true为打开,false为关闭 */ public boolean getBlueToothStatus() { // 断言?为了避免mAdapter为null导致return出错 assert (mBluetoothAdapter != null); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return false; } boolean disable = mBluetoothAdapter.disable(); showToast("tttt:" + disable); boolean ret = mBluetoothAdapter.isEnabled(); showToast("tttt:" + ret); return ret; } /** * 打开蓝牙 */ public boolean turnOnBlueTooth(Activity activity, int requestCode) { //检查蓝牙权限 getPermision(); if (!mBluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); register.launch(intent); Log.d("debug", "启动蓝牙"); //activity.startActivityForResult(intent, requestCode); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return false; } boolean enable = mBluetoothAdapter.enable(); Log.d("debug", "蓝牙开启状态:" + String.valueOf(enable)); return true; } else { return true; } } /** * 关闭蓝牙 * @return */ public void turnOffBlueTooth() { if (mBluetoothAdapter.isEnabled()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { checkConnectPermission(); } boolean ret = mBluetoothAdapter.disable(); showToast("蓝牙关闭:" + ret); } } @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { checkConnectPermission(); } Toast.makeText(getApplicationContext(), "蓝牙TEST", Toast.LENGTH_SHORT).show(); try { Log.d("debug", "点击打开蓝牙按钮"); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 如果设备不支持蓝牙 if (mBluetoothAdapter == null) { Log.d("debug", "设备不支持蓝牙"); return; } // 设备支持蓝牙功能,启动蓝牙 if (!mBluetoothAdapter.isEnabled()) { register.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)); Log.d("debug", "启动蓝牙"); } //打开蓝牙 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } boolean enable = mBluetoothAdapter.enable(); Log.d("debug", "蓝牙开启状态:" + String.valueOf(enable)); //取得蓝牙开启状态 //一旦蓝牙已经打开,我们可以使用蓝牙适配器来搜索附近的蓝牙设备 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //getBondedDevices 方法返回已经配对的蓝牙设备的集合。通过遍历集合,可以获取设备的名称和地址等信息 for (BluetoothDevice device : pairedDevices) { String deviceName = device.getName(); String deviceAddress = device.getAddress(); // 处理找到的设备信息 mBluetoothDevice = device; } Log.d("debug", "步骤四:连接蓝牙设备"); Toast.makeText(getApplicationContext(), "蓝牙TEST", Toast.LENGTH_SHORT).show(); /*步骤四:连接蓝牙设备 在搜索到蓝牙设备后,我们需要选择一个设备进行连接*/ MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; BluetoothSocket socket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID)); Log.d("debug", MY_UUID); socket.connect(); //连接成功后,我们可以通过蓝牙连接发送打印指令给蓝牙标签打印机。 OutputStream outputStream = socket.getOutputStream(); String ptString="壮骨麝香止痛膏\n"; ptString +="壮骨麝香止痛膏\n"; ptString +="壮骨麝香止痛膏\n"; ptString +="壮骨麝香止痛膏\n"; outputStream.write(ptString.getBytes("GBK")); socket.close();; } catch (IllegalStateException | IOException e) { Log.d("debug", e.getMessage()); Toast.makeText(getApplicationContext(), "蓝牙打开失败:" + "\n" + e.getMessage(), Toast.LENGTH_SHORT).show(); } } @RequiresApi(api = Build.VERSION_CODES.S) private void checkConnectPermission() { if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_DENIED) { Log.i("MES", "SUCCESS"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 2); } if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) { Log.i("MES", "SUCCESS"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2); } if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_DENIED) { Log.i("MES", "SUCCESS"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.BLUETOOTH_SCAN}, 2); } } /** * 动态申请权限 */ public void getPermision() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { requestList.add(Manifest.permission.BLUETOOTH_SCAN); requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE); requestList.add(Manifest.permission.BLUETOOTH_CONNECT); requestList.add(Manifest.permission.ACCESS_FINE_LOCATION); requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION); requestList.add(Manifest.permission.BLUETOOTH); } if (requestList.size() != 0) { ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE); } } /** * 打开蓝牙可见性 * @param context */ public void enableVisibly(Context context) { getPermision(); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } context.startActivity(discoverableIntent); //Context.register.launch(discoverableIntent); } /** * Toast弹窗显示 * @param text 显示文本 */ public void showToast(String text) { // 若Toast控件未初始化 if (mToast == null) { // 则初始化 mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); } // 否则 else { // 修改显示文本 mToast.setText(text); } // 显示 mToast.show(); } // 蓝牙状态改变广播 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); switch (state) { case BluetoothAdapter.STATE_OFF: showToast("STATE_OFF"); break; case BluetoothAdapter.STATE_ON: showToast("STATE_ON"); break; case BluetoothAdapter.STATE_TURNING_OFF: showToast("STATE_TURNING_OFF"); break; case BluetoothAdapter.STATE_TURNING_ON: showToast("STATE_TURNING_ON"); break; default: showToast("UnKnow STATE"); unregisterReceiver(this); break; } } }; private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { String s; BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } if (device.getBondState() == 12) { s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"; } else if (device.getBondState() == 10) { s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"; } else { s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未知" + "\n"; } if (!deviceName.contains(s)) { deviceName.add(s);//将搜索到的蓝牙名称和地址添加到列表。 arrayList.add(device.getAddress());//将搜索到的蓝牙地址添加到列表。 adapter1.notifyDataSetChanged();//更新 } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { showToast("搜索结束"); unregisterReceiver(this); } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { showToast("开始搜索"); } } }; /** * 获取绑定设备 * @return */ public ArrayList<BluetoothDevice> getBondedDeviceList() { getPermision(); return new ArrayList<BluetoothDevice>(mBluetoothAdapter.getBondedDevices()); } /** * 查找设备 */ public boolean findDevice() { assert (mBluetoothAdapter != null); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); return false; } else { return mBluetoothAdapter.startDiscovery(); } } /** * 根据蓝牙地址找到相应的设备 * @param addr * @return */ public BluetoothDevice find_device(String addr) { return mBluetoothAdapter.getRemoteDevice(addr); } /** * 连接设备 */ public void connect_init(BluetoothDevice device) { mBluetoothAdapter.cancelDiscovery(); try { Log.d("Debug ","ttttttttttttttttttttt"); Method clientMethod = device.getClass().getMethod("createRfcommSocketToServiceRecord", new Class[]{int.class}); btSocket = (BluetoothSocket) clientMethod.invoke(device, 1); connect(btSocket); } catch (Exception e) { e.printStackTrace(); } } public void connect(final BluetoothSocket btSocket) { try { if (btSocket.isConnected()) { Log.e(TAG, "connect: 已经连接"); return; } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } btSocket.connect(); if (btSocket.isConnected()){ Log.e(TAG, "connect: 连接成功"); }else{ Log.e(TAG, "connect: 连接失败"); btSocket.close(); } }catch (Exception e){e.printStackTrace();} } /** * 设置打印格式 * * @param command 格式指令 */ public static void selectCommand(byte[] command) { try { outputStream.write(command); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * 尝试取消配对 * @param device */ private void unpairDevice(BluetoothDevice device) { try { Method m = device.getClass() .getMethod("removeBond", (Class[]) null); m.invoke(device, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } } }
活到老,学到老。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步