Android 蓝牙导致NPE

Android 蓝牙导致NPE,android,nullpointerexception,Android,Nullpointerexception,我想使用我在清单中添加的蓝牙 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" /> 但是在这里 mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); 我有这个错误 va.lang.NullP

我想使用我在清单中添加的蓝牙

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
但是在这里

mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
我有这个错误

va.lang.NullPointerException:尝试调用虚拟方法 'android.bluetooth.BluetoothSocket位于空对象引用上


您的
mmDevice
没有正确实例化,这就是您得到
NullPointerException
的原因。通过简单的空检查来防止这种情况:
如果(mmDevice!=null)

  • 您是否在运行时请求权限?自Android M以来,您应该检查活动的权限:
  • 或者,如果您知道设备
    地址
    ,则可以使用
    mblueothmanager.adapter.getRemoteDevice(“deviceAddress”)

    方法。

    什么是mmsocket?如果它是一个对象而不是像这样初始化,例如:Textview text;并引用id(如果存在)。
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    
    private void checkPermissions() {
        ArrayList<String> permissions = ArrayList();
        if (checkSelfPermission(applicationContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            permissions.add(ACCESS_FINE_LOCATION);
        if (checkSelfPermission(applicationContext, BLUETOOTH) != PackageManager.PERMISSION_GRANTED)
            permissions.add(BLUETOOTH);
        if (checkSelfPermission(applicationContext, BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED)
            permissions.add(BLUETOOTH_ADMIN);
        if (permissions.isNotEmpty())
            requestPermissions(permissions.toTypedArray(), REQUEST_PERMISSIONS);
        else {
        startBluetoothService();
        }
    }
    
    BluetoothManager mBluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter mBluetoothAdapter = mBluetoothManager.adapter;
    //check if bluetooth is enabled 
    if (mBluetoothAdapter.isEnabled){
        mBluetoothAdapter.startDiscovery(); 
        //make sure you register this receiver to properly receive callbacks
        mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //Finding devices                 
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                doThingsWithDevice();
        }
      }
    }
    };