我在Android中運行並調試了此java代碼,並且我注意到return true
沒有任何作用,因爲它充當break
,然後return false
最終被執行。我已經使用Android Studio及其Step Over功能進行調試。在java中嘗試使用返回值時出現混淆執行
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;
}
UPDATE:
像EJP和其他人說,return true
不作爲休息。 doInBackground
函數按預期運行。問題是,由於外部代碼塊,執行之後,AsyncTask總是被取消。對此我很抱歉。
此信息可以被關閉。謝謝。
如果你寫一個返回,它總是作爲一個休息。再加上即使你的連接發生了一些異常,你只是捕獲它而不在那之後返回。爲什麼你想把你的connect語句放在for循環中。即使您希望確保連接一直保持連接狀態,請在do while循環中執行此操作,並在連接成功建立時進行檢入。 –
這是不是很好的編程,因爲我使用循環內的return語句,這會導致垃圾收集故障。 –
@FadySaad不,它不會導致垃圾收集故障。無法想象你有什麼想法。 – EJP