[英]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 . 我只是在分析一个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 ), at the constructor of its inner class called ConnectThread.
我正在查看其内部类的名为ConnectThread的构造函数的BluetoothChatService类( https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html )。 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? 我不明白-为什么他们先将对象分配给tmp值,然后将其复制到mmSocket属性? 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. 很快,因为
mmSocket
被标记为最终变量。
Let's see that your version of code. 让我们看看您的代码版本。 If method
createRfcommSocketToServiceRecord
or method createInsecureRfcommSocketToServiceRecord
throws exception, the variable is not initialized. 如果方法
createRfcommSocketToServiceRecord
或方法createInsecureRfcommSocketToServiceRecord
引发异常,则不会初始化变量。 So the temporary variable makes sure that there is atleast null
to be assigned to mmSocket
. 因此,临时变量确保至少有一个
null
分配给mmSocket
。
That's the reason. 这就是原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.