如何通过点击请求Android用户开启蓝牙?

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

来自 http://developer.android.com/guide/topics/connectivity/bluetooth.html 我知道我需要执行以下操作来请求用户启用他的 BT:

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

但问题是如何在 class 中使用它?为什么我的代码会在单击 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);
            }
          }
        });
}

您是否在 AndroidManifest.xml 文件中设置了适当的权限? 当然,您需要 BLUETOOTH 许可。

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

此外,如文档所述:

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

如果您想启用其中一项功能,您将需要以下代码:

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

调用以下方法之前

!mBluetoothAdapter.isEnabled()

在适配器上,您必须确保 mBluetoothAdapter 不为空。在您的情况下,它必须为空并且崩溃。如果 mBluetoothAdapter 为 null,android 文档说明该设备不支持蓝牙。