蓝牙导致NPE [复制]

问题描述 投票:-2回答:1

这个问题已经在这里有一个答案:

我想使用蓝牙我在清单中加入这个

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

接下来我这样做:

String uid = "0000111f-0000-1000-8000-00805f9b34fb";
    UUID uuid = UUID.fromString(uid.toUpperCase()); //Standard SerialPortService ID
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();

但在这儿 ;

mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

我有这样的错误

va.lang.NullPointerException:尝试调用虚拟方法“android.bluetooth.BluetoothSocket上一个空对象引用

android nullpointerexception
1个回答
0
投票

mmDevice不正确实例化,这就是为什么你要NullPointerException。简单nullcheck防止这种情况:if(mmDevice!=null)

  1. 你问在运行时的权限?由于Android男,你应该检查从你的活动权限:
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();
    }
}
  1. 确保你实例化对象BluetoothDevice类正确。对于这一点,您应该使用BluetoothManager设备扫描:
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();
    }
  }
}
};

或者,如果你知道设备address,您可以使用mBluetoothManager.adapter.getRemoteDevice("deviceAddress")方法。

© www.soinside.com 2019 - 2024. All rights reserved.