當設定 Bluetooth 許可權限完成後,便可以開始編寫程式,首先是要設定手機藍牙,然後啟動手機藍牙,再掃描周邊的藍牙設備,顯示藍牙設備資料,選擇藍牙設備作綁定配對(Pair),便可以讀取綁定設備的 UUID。因為沒有其它這次綁定 Bluetooth(藍牙)設備,設備是一台舊 Huawei G7-TL00 手機,綁定(Pair)都成功,並讀取 G7-TL00 手機的 UUID(Universally Unique Identifier / 通用唯一標識符)。
Android Studio Bluetooth 讀取 UUID 程式 |
- 操作系統:Windows 7 64-bit 版本
- 開發環境:Android Studio 4.0.1 版本
- 原程式:C:\Development\Development_Android\Android_Project\DIY-Android-010-01C Bluetooth UUID
- 程式:C:\Development\Development_Android\Android_Project\DIY-Android-010-01C Bluetooth UUID
Bluetooth 讀取設備 UUID 程式編程步驟:
- 設定 Bluetooth 許可權限後
- 設定手機藍牙
- 啟動手機藍牙
- 掃描周邊的藍牙設備
- 顯示周邊藍牙設備資料
- 選擇藍牙設備作綁定配對
- 讀取設備 UUID
MainActivity.java:
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.ParcelUuid; import android.os.Parcelable; 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 android.content.Intent; import android.content.Context; import android.content.IntentFilter; import android.view.View;
// Bluetooth API import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver;
import java.lang.reflect.Method; import java.util.ArrayList; import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final UUID BT_MODULE_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // random UUID
// GUI Components private TextView mtv_status; private Button mbtn_on; private Button mbtn_Scan; private Button mbtn_Pair; private Button mbtn_UnPair; private ListView mlv_device; private ListView mlv_uuid; private ArrayAdapter<String> mBTArrayUUID; private int mlvPosition;
private BluetoothAdapter mBTAdapter; private ArrayAdapter<String> mBTArrayAdapter; private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>(); ArrayList mArrayUUID=new ArrayList();
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
mbtn_on = (Button) findViewById(R.id.btn_on); mbtn_Scan = (Button) findViewById(R.id.btn_scan); mbtn_Pair = (Button) findViewById(R.id.btn_pair); mbtn_UnPair=(Button) findViewById(R.id.btn_unpair);
mBTArrayUUID = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mArrayUUID); mlv_uuid = (ListView)findViewById(R.id.lv_uuid); mlv_uuid.setAdapter(mBTArrayUUID); // assign model to view
mBTArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mlv_device = (ListView)findViewById(R.id.lv_device); mlv_device.setAdapter(mBTArrayAdapter); // assign model to view
mbtn_on.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bluetoothOn(); } });
mbtn_Scan.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ scan(); } });
mbtn_Pair.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ BluetoothDevice device = mDeviceList.get(mlvPosition); Toast.makeText(getApplicationContext(),"Pair " + mlvPosition, Toast.LENGTH_SHORT).show(); pairDevice(device); showUUID(device); } });
mbtn_UnPair.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ BluetoothDevice device = mDeviceList.get(mlvPosition); Toast.makeText(getApplicationContext(),"UnPair " + mlvPosition, Toast.LENGTH_SHORT).show(); unpairDevice(device); } });
// ListView mlv_device.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView) parent; mlvPosition = position; Toast.makeText(getApplicationContext(),"Select " + text3, Toast.LENGTH_SHORT).show(); } }); }
// Bluetooth Turn ON private void bluetoothOn(){ if (!mBTAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); Toast.makeText(getApplicationContext(),"Bluetooth Turned On",Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(),"Bluetooth is Already On", Toast.LENGTH_SHORT).show(); } }
// Discovery Bluetooth Device private void scan(){ // Check if the device is already discovering mlvPosition = -1; mBTArrayAdapter.clear(); mDeviceList.clear();
if(mBTAdapter.isDiscovering()){ mBTAdapter.cancelDiscovery(); Toast.makeText(getApplicationContext(),"Scan Stop",Toast.LENGTH_SHORT).show(); } else{ if(mBTAdapter.isEnabled()) { mBTArrayAdapter.clear(); // clear items mBTAdapter.startDiscovery(); Toast.makeText(getApplicationContext(), "Discovery Started", Toast.LENGTH_SHORT).show(); registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); } else{ Toast.makeText(getApplicationContext(), "Bluetooth Not On", Toast.LENGTH_SHORT).show(); } } }
private void pairDevice(BluetoothDevice device) { try { Method method = device.getClass().getMethod("createBond", (Class[]) null); method.invoke(device, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } }
private void unpairDevice(BluetoothDevice device) { try { Method method = device.getClass().getMethod("removeBond", (Class[]) null); method.invoke(device, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } }
private String showUUID(BluetoothDevice d) { String type = "Type:"; Toast.makeText(getApplicationContext(), "UUID", Toast.LENGTH_SHORT).show(); ParcelUuid[] uuids = d.getUuids();
if (null == uuids) { type = "UUIDs"; return type; }
for (int i = 0; i < uuids.length; i++) { ParcelUuid uuid = uuids[i]; type = type + (uuid.getUuid().toString()) + " "; mArrayUUID.add(uuid.getUuid().toString()); mBTArrayUUID.notifyDataSetChanged(); } return type; }
final BroadcastReceiver blReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); mDeviceList.add(device); mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); mBTArrayAdapter.notifyDataSetChanged(); } } };
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) { Toast.makeText(getApplicationContext(), "Pair", Toast.LENGTH_SHORT).show(); } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){ Toast.makeText(getApplicationContext(), "UnPair", Toast.LENGTH_SHORT).show(); } mBTArrayAdapter.notifyDataSetChanged(); } } }; } |
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginStart="132dp" android:layout_marginLeft="132dp" android:layout_marginTop="16dp" android:text="Hello Bluetooth!" />
<Button android:id="@+id/btn_on" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginStart="12dp" android:layout_marginLeft="12dp" android:layout_marginTop="40dp" android:text="ON" />
<Button android:id="@+id/btn_scan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/btn_on" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_marginStart="10dp" android:layout_marginLeft="12dp" android:layout_marginTop="11dp" android:text="Scan" />
<ListView android:id="@+id/lv_device" android:layout_width="363dp" android:layout_height="382dp" android:layout_below="@+id/btn_scan" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginStart="16dp" android:layout_marginLeft="16dp" android:layout_marginTop="20dp" android:layout_marginBottom="182dp" android:background="@android:color/holo_green_light" />
<ListView android:id="@+id/lv_uuid" android:layout_width="353dp" android:layout_height="144dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginStart="10dp" android:layout_marginLeft="10dp" android:layout_marginBottom="15dp" android:background="@android:color/holo_orange_dark" android:textSize="2dp" />
<Button android:id="@+id/btn_pair" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginTop="40dp" android:layout_marginEnd="15dp" android:layout_marginRight="15dp" android:text="Pair" />
<Button android:id="@+id/btn_unpair" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/btn_pair" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginTop="10dp" android:layout_marginEnd="15dp" android:layout_marginRight="15dp" android:text="UnPair" /> </RelativeLayout> |
讀取 UUID:
00001112-0000-1000-8000-00805F9B34FB - HeadsetAudioGatewayServiceClass 0000111F-0000-1000-8000-00805F9B34FB - SDP_HandsfreeServiceClass 0000110A-0000-1000-8000-00805F9B34FB - SDP_AudioSourceServiceClass 0000110C-0000-1000-8000-00805F9B34FB - SDP_AVRemoteControlTargetServiceClass 0000110E-0000-1000-8000-00805F9B34FB - SDP_AVRemoteControlServiceClass 00001105-0000-1000-8000-00805F9B34FB - SDP_OBEXObjectPushServiceClass 00001116-0000-1000-8000-00805F9B34FB - NAPServiceClass 0000112F-0000-1000-8000-00805F9B34FB - Phonebook Access Server 00001203-0000-1000-8000-00805F9B34FB - GenericAudioServiceClass |
Android Studio Bluetooth 讀取 UUID 程式 |
沒有留言:
張貼留言