【发布时间】:2018-01-05 21:17:27
【问题描述】:
我已经在 Android 中运行并调试了这个 java 代码,我注意到 return true 没有任何效果,因为它充当 break,然后 return false 最终被执行。我使用了 Android Studio 及其 Step Over 功能进行调试。
protected Boolean doInBackground(Void... params) {
// Cancel discovery because it will slow down the connection
mAdapter.cancelDiscovery();
// Start connection attempt
for(int i=0;i<10;i++) {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
// connection successful [it should return true]
return true;
}
catch (IOException connectException) {
// Unable to connect; close the socket and get out
try { mmSocket.close(); }
catch (IOException closeException) { }
}
}
// connection failed 10 times [but it always returns false]
return false;
}
更新:
就像 EJP 和其他人所说的那样,return true 不作为休息。 doInBackground 函数按预期运行。问题是,由于外部代码块,AsyncTask 在return true 执行后总是被取消。对此我很抱歉。
此帖可以关闭。谢谢。
【问题讨论】:
-
如果你在 For 中写了一个 return,它总是作为一个休息。另外,即使在您的连接中发生了一些异常,您也只是在捕获它而不是在那之后返回。为什么要将连接语句放在 for 循环中。即使您想确保它在您连接之前一直尝试,请在 do while 循环中执行此操作,如果连接成功建立,请在 while 中检查。
-
这不是很好的编程,因为我在循环中使用了 return 语句,这会导致垃圾收集失败。
-
@FadySaad 不,它不会导致垃圾收集出现故障。无法想象你的想法是从哪里来的。
标签: java android return try-catch