Beispielprojekt https://github.com/ry0takaha4/android-bluetooth-on-off-sample-app
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
// MainActivity.java
/**
*Bluetooth-Verbindungserkennungs-Listener
*Wird jedes Mal aufgerufen, wenn die Bluetooth-Funktion des Hauptgeräts ein- oder ausgeschaltet wird
*/
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
System.out.println("Bluetooth ist eingeschaltet.");
hoge();
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = proxy;
}
}
public void onServiceDisconnected(int profile) {
System.out.println("Bluetooth ist ausgeschaltet.");
foo();
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null;
}
}
};
// MainActivity.java
private BluetoothAdapter mBluetoothAdapter;
private BluetoothProfile mBluetoothHeadset;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Bluetooth-fähige Prüfung
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
//Diesmal Bluetooth-Profil.HEADSET, aber alles ist in Ordnung, solange es erkannt wird
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET);
} else {
System.out.println("Bluetooth wird auf diesem Gerät nicht unterstützt oder deaktiviert.");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//Schließen Sie die Profil-Proxy-Verbindung zum Dienst
if (mBluetoothAdapter != null && mBluetoothHeadset != null) {
mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
}
}
Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.
Quelle: https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#enable ()
Wenn Sie Bluetooth aktivieren möchten Aktivieren Sie Bluetooth nicht ohne die Zustimmung des Benutzers. Wenn Sie es aktivieren möchten, sollten Sie die Absicht "ACTION_REQUEST_ENABLE" verwenden und ein Dialogfeld anzeigen, in dem Sie um Benutzerberechtigung gebeten werden.