Android'de programlı olarak bluetooth nasıl etkinleştirilir / devre dışı bırakılır


104

Program üzerinden bluetooth'u etkinleştirmek / devre dışı bırakmak istiyorum. Takip koduna sahibim.

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

Ancak bu kod SDK 1.5'te çalışmıyor. Nasıl çalıştırabilirim?


Nasıl çalışmıyor? Bir hata mı alıyorsun? Eğer öyleyse, hata nedir?
— Adam Driscoll

1
BluetoothAdapter SDK 1.5'te hata gösteriyor
— user458295

Yanıtlar:



164

bu kod benim için çalıştı ..

//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
} 

Bunun çalışması için aşağıdaki izinlere sahip olmanız gerekir:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

benim için de gerçekten işe yarıyor. android cihazlarda bluetooth bağlantısını kesmek için basit bir yöntem. çok teşekkürler dostum.
— Amit Thaper

7
BLUETOOTH_ADMIN izni eklerseniz çalışır, ancak yoksa startActivityForResult (enableBtIntent, 0) kullanmanız gerekir; Bluetooth'unuzu etkinleştirmek için
— Majid Golshadi

1
Faydalı cevabınız için teşekkürler +1. sadece bunu nasıl etkinleştireceğini bilmeyenler için eklemek istiyorum: mBluetoothAdapter.enable ()
— Chris Sim

97

İşte bunu yapmanın biraz daha sağlam bir yolu, ayrıca enable()\disable()yöntemlerin dönüş değerlerini de ele almak :

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

Ve manifest dosyanıza aşağıdaki izinleri ekleyin:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Ancak şu önemli noktaları unutmayın:

Bu, eşzamansız bir çağrıdır: hemen geri döner ve istemciler, ACTION_STATE_CHANGED'in sonraki bağdaştırıcı durumu değişikliklerinden haberdar edilmesini dinlemelidir. Bu çağrı true döndürürse, bağdaştırıcı durumu hemen STATE_OFF'tan STATE_TURNING_ON'a ve bir süre sonra STATE_OFF veya STATE_ON'a geçecektir. Bu çağrı yanlış dönerse, o zaman adaptörün açılmasını engelleyecek bir sorun vardı - örneğin Uçak modu veya adaptör zaten açık.

GÜNCELLEME:

Peki, bluetooth dinleyicisi nasıl uygulanır ?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

Ve alıcı nasıl kaydedilir / kaydı nasıl iptal edilir? ( ActivitySınıfınızda)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

1
BLUETOOTH_ADMINizin eklerseniz çalışır, ancak değilse startActivityForResult(enableBtIntent, 0);bluetooth'unuzu etkinleştirmek için kullanmanız gerekir
— Majid Golshadi

1
vurgulanan bilgi, özellikle enable () yöntemi için BluetoothAdapter belgelerinden alıntılanmıştır.
— Kevin Lee

hey, doktorlar bunun 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.ne anlama geldiğini söylüyor ? Örn. Kodunuzdan küçük bir uygulama yaptım ve işe yaradı. Ama Play Store'a yüklemek istersem çalışmaz mı?
— Hilal

@Hilal işe yarayacak. Ancak kullanıcıların kurulumdan önce izin vermesi gerekir. Şöyle
— Caner

23

Bluetooth'u etkinleştirmek için aşağıdaki işlevlerden birini kullanabilirsiniz:

 public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        // The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() 
        // implementation as the requestCode parameter. 
        int REQUEST_ENABLE_BT = 1;
        startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
        }
  }

İkinci işlev:

public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.enable();
    }
}

Aradaki fark, ilk işlevin uygulamanın kullanıcıdan Bluetooth'u açma veya reddetme izni istemesine neden olmasıdır. İkinci işlev, uygulamanın Bluetooth'u doğrudan açmasını sağlar.

Bluetooth'u devre dışı bırakmak için aşağıdaki işlevi kullanın:

public void disableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.disable();
    }
}

NOT / İlk işlevin AndroidManifest.xml dosyasında tanımlanması için yalnızca aşağıdaki iznin olması gerekir:

<uses-permission android:name="android.permission.BLUETOOTH"/>

İkinci ve üçüncü işlevler aşağıdaki izinlere ihtiyaç duyarken:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

(Görünüm görünümü) parametresinin gerekli olmadığını düşünüyorum
— CitrusO2

6

Prijin'in çözümü benim için mükemmel çalıştı. İki ek izne ihtiyaç olduğunu belirtmek doğru olur:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Bunlar eklendiğinde, varsayılan bluetooth adaptörüyle etkinleştirme ve devre dışı bırakma sorunsuz çalışır.


4

Uygulamam başladığında ve iyi çalıştığında BT'yi devre dışı bırakmak için aşağıdaki kodu kullandım. Google "bluetooth.disable ()" kullanılmamasını önerdiğinden, bunu uygulamanın doğru yolu olup olmadığından emin değilim; Bluetooth'u kapatmak için açık kullanıcı eylemi olmadan.

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    bluetooth.disable();

Ben sadece aşağıdaki izni kullandım.

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

2

Aşağıdaki izinleri manifest dosyanıza ekleyin:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Bluetooth'u etkinleştir bunu kullan

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.enable(); 
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}

Bluetooth'u devre dışı bırak, bunu kullan

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
}

0

bunu dene:

//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            // Bluetooth is not enable :)
            return false;
        }
        else{
            return true;
        }

    }

//method to enable bluetooth
    public static void enableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

//method to disable bluetooth
    public static void disableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

Bu izinleri manifest'e ekle

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.