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

Mil*_*ill 8 android bluetooth

来自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);
}
Run Code Online (Sandbox Code Playgroud)

但问题是如何在课堂上使用它?为什么我的代码会在点击此活动的按钮时崩溃:

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);
            }
          }
        });
}
Run Code Online (Sandbox Code Playgroud)

pio*_*hen 9

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

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>
Run Code Online (Sandbox Code Playgroud)

此外,正如文件所述:

如果您希望应用启动设备发现或操作蓝牙设置,则还必须声明BLUETOOTH_ADMIN 权限.

如果要启用这些功能之一,则需要以下代码:

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  ...
</manifest>
Run Code Online (Sandbox Code Playgroud)


neo*_*neo 5

在调用以下方法之前

!mBluetoothAdapter.isEnabled()
Run Code Online (Sandbox Code Playgroud)

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