启动时蓝牙连接崩溃

Bluetooth Connectivity Crashes when launched

当我的应用程序启动时,其他所有功能都可以正常工作,但是当点击蓝牙按钮打开蓝牙时,应用程序崩溃并显示它已停止。很抱歉麻烦您并粘贴整个蓝牙代码。这是我第一次使用蓝牙,并且是 android 开发人员的新手,我不太确定哪里出了问题。非常感谢您的帮助。

谢谢

public class BluetoothActivity extends Activity {

private static final String TAG = "BluetoothActivity";
private static final int BLUETOOTH_REQUEST = 0;
private static final int SELECT_SERVER = 1;
public static final int DATA_RECEIVED = 3;
public static final int SOCKET_CONNECTED = 4;

public static final UUID APP_UUID = UUID
        .fromString("ad7b8520-f5fa-11e4-b939-0800200c9a66");
private Button on;
private Button off;
private Button server;
private Button client;
private TextView tv = null;

private BluetoothAdapter b_adapter = null;
private ConnectionThread bluetoothConnect = null;
private String data;
private boolean mServerMode;

private TextView text;
private ListView pairedList;
private Set<BluetoothDevice> pairedDevices;
private ArrayAdapter<String> BTArrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    b_adapter = BluetoothAdapter.getDefaultAdapter();
    if (b_adapter == null) {
        Log.i(TAG, "Bluetooth not supported");
        finish();
    }

    setContentView(R.layout.activity_bluetooth);
    tv = (TextView) findViewById(R.id.textView1);
    server = (Button) findViewById(R.id.server);
    server.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            startAsServer();
            mServerMode = true;
        }
    });

    client = (Button) findViewById(R.id.client);
    client.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            selectServer();
        }
    });

    if (!b_adapter.isEnabled()) {
        Intent enableBluetoothIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetoothIntent, BLUETOOTH_REQUEST);
    } else {
        setButtonsEnabled(true);
    }

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == BLUETOOTH_REQUEST && resultCode == RESULT_OK) {
        setButtonsEnabled(true);
    } else if (requestCode == SELECT_SERVER && resultCode == RESULT_OK) {
        BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        connectToBluetoothServer(device.getAddress());
    }
}

private void startAsServer() {
    setButtonsEnabled(false);
    new AcceptThread(mHandler).start();
}

private void selectServer() {
    setButtonsEnabled(false);
    Set<BluetoothDevice> pairedDevices = b_adapter.getBondedDevices();
    ArrayList<String> pairedDeviceString = new ArrayList<String>();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            pairedDeviceString.add(device.getName() + "\n"
                    + device.getAddress());
        }
    }

这里还有蓝牙线程

public class ConnectThread extends Thread {
private BluetoothSocket BTsocket;
private final BluetoothDevice mDevice;
private final BluetoothAdapter b_adapter = BluetoothAdapter.getDefaultAdapter();
private final Handler mHandler;

public ConnectThread(String deviceID, Handler handler) {
    mDevice = b_adapter.getRemoteDevice(deviceID);
    mHandler = handler;
    try {
        BTsocket = mDevice.createRfcommSocketToServiceRecord(BluetoothActivity.APP_UUID);
    } catch (IOException e){
        e.printStackTrace();
    }
}
public void run() {
    b_adapter.cancelDiscovery();
    try {
        BTsocket.connect();
        manageConnectedSocket();
    } catch (IOException connectException) {    
        try {
            BTsocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void manageConnectedSocket() {
    ConnectionThread conn = new ConnectionThread(BTsocket, mHandler);
    mHandler.obtainMessage(BluetoothActivity.SOCKET_CONNECTED, conn).sendToTarget();
    conn.start();
}
public void cancel() {
    try {
        BTsocket.close();
    }catch(IOException e){

    }
}

}

对于那些想要查看 logcat 的人。在下面。

.BluetoothActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
  at android.app.ActivityThread.-wrap11(ActivityThread.java)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5417)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
  at com.kenpar.dmsassign2.BluetoothActivity.onCreate(BluetoothActivity.java:80)
  at android.app.Activity.performCreate(Activity.java:6237)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
  at android.app.ActivityThread.-wrap11(ActivityThread.java) 
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
  at android.os.Handler.dispatchMessage(Handler.java:102) 
  at android.os.Looper.loop(Looper.java:148) 
  at android.app.ActivityThread.main(ActivityThread.java:5417) 
  at java.lang.reflect.Method.invoke(Native Method) 
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

这是因为您的BluetoothAdapter可能没有正确初始化。检查您的 LogCat,您应该会在 info 标签中看到 Bluetooth not supported 消息。现在为了避免在 Activity 中使用 NullPointerException,请将您的代码更改为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    b_adapter = BluetoothAdapter.getDefaultAdapter();
    if (b_adapter == null) {
        Log.i(TAG, "Bluetooth not supported");
        // Show proper message here
        finish();
    } else {
        setContentView(R.layout.activity_bluetooth);
        tv = (TextView) findViewById(R.id.textView1);
        server = (Button) findViewById(R.id.server);
        server.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startAsServer();
                mServerMode = true;
            }
        });

        client = (Button) findViewById(R.id.client);
        client.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                selectServer();
            }
        });

        if (!b_adapter.isEnabled()) {
            Intent enableBluetoothIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetoothIntent, BLUETOOTH_REQUEST);
        } else {
            setButtonsEnabled(true);
        }
    }
}

原因是:如果你的b_adapternull,它不应该执行使用它的行。明确地说 finish 不会跳过它旁边的行。所以你必须自己做。