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

标签 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);
}

但问题是如何在类里面使用它?为什么每次单击此 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>

关于android - 如何通过点击请求Android用户启用蓝牙?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28411991/

相关文章:

java - Android选项菜单不显示

android - 单击 CardView 时的高程动画

android - 如何使用 Apache POI 给出驻留在 android 项目 Assets 文件夹中的 xls 文件的路径

java - 编码标签中的 Sax 解析

ios - 在 iOS 7 上通过 NSNetService 连接到 BLE 设备并发送/读取数据

android - java.lang.IllegalStateException : Could not execute method for android:onClick 错误

android - 无需扫描即可连接其他蓝牙 LE 设备?

android - 在android中创建一个圆形 View

android - 为什么 setCharacteristicNotification() 实际上没有启用通知?

java - 从其他 Activity 向处理程序发送消息