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>