这个tmp变量在android示例蓝牙聊天应用程序中的目的是什么

时间:2015-01-08 15:12:55

标签: java android android-bluetooth

我正在分析一个Android示例应用程序 - 蓝牙聊天:https://developer.android.com/samples/BluetoothChat/project.html。我在其内部类的构造函数ConnectThread中查看了BluetoothChatService类(https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html)。那里有这样的代码:

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

1 个答案:

答案 0 :(得分:2)

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

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

这就是原因。