一上午力所,仍是一地雞毛。andorid 藍芽

一贴灵發表於2024-04-18

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



}

相關文章