一上午折腾,仍是一地鸡毛。andorid 蓝牙
package com.lingrui.btprint; 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.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.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; 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=""; /** * 代表本地蓝牙适配器(蓝牙无线电)。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; public void MyClick(View v){ } @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); register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult o) { int s = o.getResultCode(); if (o == null) { Log.e("error:", "打开失败"); } else { if (o.getResultCode() == RESULT_CANCELED) { Log.d("debug", "用户取消"); } if (o.getResultCode() == RESULT_OK) { Log.d("debug", "蓝牙打开成功"); } } } }); } /* BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 如果设备不支持蓝牙 if (bluetoothAdapter == null) { Toast.makeText(getApplicationContext(), "该机型不支技蓝牙", Toast.LENGTH_SHORT).show(); return; } // 设备支持蓝牙功能,启动蓝牙 if (!bluetoothAdapter.isEnabled()) { startBlueTooth.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)); Toast.makeText(getApplicationContext(), "开启蓝牙", Toast.LENGTH_SHORT).show(); }*/ @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "蓝牙TEST", Toast.LENGTH_SHORT).show(); try { Log.d("debug", "点击打开蓝牙按钮"); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Log.d("debug", "22222222222"); // 如果设备不支持蓝牙 if (bluetoothAdapter == null) { Log.d("debug", "设备不支持蓝牙"); return; } Log.d("debug", "3333333333"); // 设备支持蓝牙功能,启动蓝牙 if (!bluetoothAdapter.isEnabled()) { register.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)); Log.d("debug", "启动蓝牙"); } Log.d("debug", "44444444444"); //取得蓝牙开启状态 //一旦蓝牙已经打开,我们可以使用蓝牙适配器来搜索附近的蓝牙设备 String tmp = String.valueOf(PackageManager.PERMISSION_GRANTED); Log.d("debug", tmp); Log.d("debug", "5111111"); tmp = String.valueOf(android.Manifest.permission.BLUETOOTH_CONNECT); Log.d("debug", tmp); tmp= String.valueOf((ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT))); Log.d("debug", tmp); if (ActivityCompat.checkSelfPermission(this, android.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. Log.d("debug", "5555555555555"); 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; } /*步骤四:连接蓝牙设备 在搜索到蓝牙设备后,我们需要选择一个设备进行连接*/ BluetoothSocket socket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(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(); } }
活到老,学到老。