蓝牙打印开发代码示例(日拱一卒,有点进步,UUID仍报错)

健康一贴灵 / 2024-04-22 / 原文

 

package com.lingrui.btprint;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
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.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    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;


    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    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
            {
                Log.e("DEBUG:","6666666666666666666666666666666");
                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);

        CheckBox ck_1 = findViewById(R.id.ck_1);



    }

    @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) {
                // 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;
            }
            boolean enable = mBluetoothAdapter.enable();
            Log.d("debug", "蓝牙开启状态:"+String.valueOf(enable));
            //取得蓝牙开启状态

            //一旦蓝牙已经打开,我们可以使用蓝牙适配器来搜索附近的蓝牙设备

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions

                return;
            }
            Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
            //getBondedDevices 方法返回已经配对的蓝牙设备的集合。通过遍历集合,可以获取设备的名称和地址等信息
            for (BluetoothDevice device : pairedDevices) {
                String deviceName = device.getName();
                String deviceAddress = device.getAddress();
                // 处理找到的设备信息
                Log.d("debug", deviceName);
                Log.d("debug", deviceAddress);
                mBluetoothDevice = device;
            }
            Log.d("debug", "步骤四:连接蓝牙设备");
            Toast.makeText(getApplicationContext(), "蓝牙TEST", Toast.LENGTH_SHORT).show();
            /*步骤四:连接蓝牙设备
            在搜索到蓝牙设备后,我们需要选择一个设备进行连接*/
            BluetoothSocket socket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
            Log.d("debug", MY_UUID);
            socket.connect();

            //连接成功后,我们可以通过蓝牙连接发送打印指令给蓝牙标签打印机。
            OutputStream outputStream = socket.getOutputStream();

        }catch (IllegalStateException | IOException e) {
            Log.d("debug", e.getMessage());
            Toast.makeText(getApplicationContext(), "蓝牙打开失败:"+"\n"+e.getMessage(), Toast.LENGTH_SHORT).show();
        }




    }

    public void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar_MinWidth);
        builder.setMessage("需要读SD卡权限,用来获取照片\n需要获取手机状态权限,用来获取设备号\n需要获取联系人权限,用来...");
        builder.setTitle("权限说明");
        builder.setCancelable(true);
        builder.setPositiveButton("申请", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ;
            }
        });
        builder.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);
        }
    }


}

 

<?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:background="#E8E8E8">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/tv_1"
            android:text="物料名称"
            android:textColor="@color/black"
            />
        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/et_1"
            android:text="物料名称"
            android:textColor="@color/black"
            />


    </LinearLayout>
    <Button
        android:id="@+id/bt_blt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="打开蓝牙"/>
    <Button
        android:id="@+id/bt_blt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关闭蓝牙"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/tv_2"
        android:text="物料名称"
        android:textColor="@color/black"
        />
    <CheckBox
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ck_1"
        android:text="测试"/>
</LinearLayout>
<?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>