简体   繁体   中英

what is the purpose of this tmp variable in android sample bluetooth chat application

I'm just analyzing one of android sample applications - the bluetooth chat: https://developer.android.com/samples/BluetoothChat/project.html . I'm looking at the BluetoothChatService class ( https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html ), at the constructor of its inner class called ConnectThread. There is such piece of code there:

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    (...)
    public ConnectThread(BluetoothDevice device, boolean secure) {
        (...)
        BluetoothSocket tmp = null;
        (...)
        try {
            if (secure) {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
            } else {
                tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
            }
        } catch (IOException e) {
            Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
        mmSocket = tmp;
    }
    (...)

I don't understand - why they first assign the object to the tmp value and then copy it to mmSocket attribute? They could do it a bit simpler, this way:

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    (...)
    public ConnectThread(BluetoothDevice device, boolean secure) {
        (...)
        try {
            if (secure) {
                mmSocket =  device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
            } else {
                mmSocket =  device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
            }
        } catch (IOException e) {
            Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
    }

Shortly, because mmSocket is marked as final variable.

Let's see that your version of code. If method createRfcommSocketToServiceRecord or method createInsecureRfcommSocketToServiceRecord throws exception, the variable is not initialized. So the temporary variable makes sure that there is atleast null to be assigned to mmSocket .

That's the reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM