蓝牙连接启动时崩溃

时间:2016-06-01 11:03:59

标签: android bluetooth android-bluetooth android-developer-api

当我的应用程序启动时,每个其他功能都可以正常工作,但是当点击蓝牙按钮打开蓝牙时,应用程序崩溃并说它已停止。很抱歉是痛苦并粘贴整个蓝牙代码。这是我第一次使用蓝牙技术并在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) 

1 个答案:

答案 0 :(得分:1)

这是因为您的BluetoothAdapter可能无法正确初始化。查看您的LogCat,您应该会在 info 标记中看到 Bluetooth不支持消息。现在,为了避免NullPointerException中的Activity,请将代码更改为:

@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不会跳过它旁边的行。所以你必须自己做。