Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to request Android user to enable Bluetooth through a click?

from http://developer.android.com/guide/topics/connectivity/bluetooth.html i know that i need to the following to request the user to enable his BT:

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

but the question is how to use it in a class? why does my code crash whenever click on the button of this activity:

public class Opponents extends Activity 
{
      private final static int REQUEST_ENABLE_BT=1;
      BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

      @Override
      protected void onCreate(Bundle savedInstancesState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.opponents);

        final Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() 
        {
          public void onClick(View view)
          {
            if(!mBluetoothAdapter.isEnabled())
            {
              Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
          }
        });
}
like image 323
Mill Avatar asked Feb 09 '15 14:02

Mill


2 Answers

Did you set proper permissions in your AndroidManifest.xml file? For sure, you will need BLUETOOTH permission.

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

In addition, as documentation says:

If you want your app to initiate device discovery or manipulate Bluetooth settings, you must also declare the BLUETOOTH_ADMIN permission.

If you want to enable one of these features you will need the following code:

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  ...
</manifest>
like image 169
Piotr Wittchen Avatar answered Nov 18 '22 20:11

Piotr Wittchen


Before you call the following method

!mBluetoothAdapter.isEnabled()

on the adapter, you have to make sure mBluetoothAdapter is not null. In your case it must be null and crashing. And if mBluetoothAdapter is null, the android documentation says that the device doesn't support Bluetooth.

like image 44
neo Avatar answered Nov 18 '22 20:11

neo