BluetoothAdapter.getDefaultAdapter() throws exception

二次信任 提交于 2019-12-13 04:16:53

问题


I try to add Bluetooth to my libgdx android project. I added the following to the Android manifest:

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

I tried to run

   mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

in non activity class - exception . I have read that the class should be activity class. Okay. I have created

   public class BluetoothServer extends Activity {
    ...
       public void GetBluetoothAdapter () {
         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      }
    }

I ran it as follows:

BluetoothServer.GetBluetoothAdapter()

Crashes again in the same place. I tried on two devices with Bluetooth onboard. Of course, Bluetooth is enabled on these devices. I have no idea what to do.

Thanks.


回答1:


It would help greatly if you could get the reason for the crash. For some reason you seem not able to access stacktrace, try at least this to see the crash reason:

...
try {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
} catch (Exception e) {

    Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), 1000);
    toast.show();
}
...



回答2:


To get a BluetoothAdapter representing the local Bluetooth adapter, when running on JELLY_BEAN_MR1 and below, call the static getDefaultAdapter() method; when running on JELLY_BEAN_MR2 and higher, retrieve it through getSystemService(String) with BLUETOOTH_SERVICE. Source



来源:https://stackoverflow.com/questions/11468955/bluetoothadapter-getdefaultadapter-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!