AndroidManifest.xml
---------------------------------------------------------------------
<manifest …> …………… …………… <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" /> …………… …………… </manifest>
AndroidBluetooth.java
---------------------------------------------------------------------
import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.os.Bundle; public class Android_Bluetooth extends Activity { private static final int REQUEST_ENABLE_BT = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter != null) { if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } else{ tv1.setText("not bluetooth sensor"); } } }
在使用之前要先在 AndroidManifest.xml裡的 manifest 加入這兩行
import android.bluetooth.BluetoothAdapter;
要開啟藍芽前先要引入 BluetoothAdapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
建立一個新的 BluetoothAdapter 物件以 mBluetoothAdapter 命名
if (mBluetoothAdapter != null) {
}
這個用法是可以去檢查裝置是否有藍芽
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
這是用來判斷該裝置的藍芽是否開啟了,開啟傳True 否則 False
如果沒有開啟會跳出訊息畫面,詢問使用者藍芽是開啟
如果沒有開啟會跳出訊息畫面,詢問使用者藍芽是開啟
mBluetoothAdapter.enable();
也可以直接用直接開啟
這段是可以把已經 配對過的手機(名稱、MAC) 都紀錄起來
String res="";
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
res += device.getName() + " " + device.getAddress() +"\n";
}
}
這段是可以把已經 配對過的手機(名稱、MAC) 都紀錄起來