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

如何通过点击请求Android用户启用蓝牙?,android,bluetooth,Android,Bluetooth,从中,我知道我需要执行以下操作以请求用户启用其BT: if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } 但问题是如何在课堂上使用它?为什么每次单击此活动的按钮时,我的代码都会崩溃: public

从中,我知道我需要执行以下操作以请求用户启用其BT:

if (!mBluetoothAdapter.isEnabled()) 
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
但问题是如何在课堂上使用它?为什么每次单击此活动的按钮时,我的代码都会崩溃:

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
文件中设置了适当的权限? 当然,您需要
蓝牙
权限

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

在调用以下方法之前

!mBluetoothAdapter.isEnabled()

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

show
logcat
查看它的位置。Crassesi完全忘记了AndroidManifest.xml,这就是问题所在。不管怎样,谢谢,因为我知道mBA也不需要为空。
!mBluetoothAdapter.isEnabled()