android 示例蓝牙聊天应用程序中此 tmp 变量的用途是什么

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

我只是在分析其中一个 android 示例应用程序 - 蓝牙聊天: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 ),在其内部 class 称为 ConnectThread 的构造函数中。那里有这样一段代码:

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;
    }
    (...)

我不明白 - 为什么他们先将对象分配给 tmp 值,然后将其复制到 mmSocket 属性?他们可以这样做更简单一些,这样:

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);
        }
    }

很快,因为mmSocket被标记为最终变量。

让我们看看您的代码版本。如果方法 createRfcommSocketToServiceRecord 或方法 createInsecureRfcommSocketToServiceRecord 抛出异常,则变量不会被初始化。所以临时变量确保至少有 null 被分配给 mmSocket.

就是这个原因。