我正在尝试执行此AsyncTask
以连接到服务器,但它已卡住但未到达onPostExecute()
。
class UnoConnection extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
IP = enterIP.getText().toString();
Response = "";
Log.i("Network", "Available");
}
@Override
protected Boolean doInBackground(Void... params) {
try {
InetAddress serverAddress = InetAddress.getByName(IP);
Log.i("Socket", "Trying to create...");
socket = new Socket();
socket.connect(new InetSocketAddress(serverAddress, 4444), 2000);
Log.i("Socket", "Created: " + socket.toString());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
Log.i("Socket", "Post..." + aBoolean);
super.onPostExecute(aBoolean);
if (aBoolean) {
connect.setChecked(true);
showToast("Connected :)", "long");
enable(controls);
enterIP.setEnabled(false);
} else {
showToast("Unable to connect...!", "long");
connect.setChecked(false);
disable(controls);
enterIP.setEnabled(true);
}
Log.i("Socket", "Post..." + aBoolean);
}
}
调用此AsyncTask的方法如下:
switch (thisView.getId()) {
case R.id.connect:
UnoCon = new UnoConnection();
UnoCon.execute();
while (!(UnoCon.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("UnoCon",UnoCon.getStatus().toString());
}
if (socket == null) break;
cmdSend = new commandSender();
cmdSend.execute('2', 'R');
while (!(cmdSend.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("cmdSend", "Not Finished Yet");
}
if (commandSent) {
respRec = new responseReceiver();
respRec.execute();
while (!(respRec.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("respRec", "Not Finished Yet");
}
switch (Response) {
case "1":
Relay1.setChecked(true);
break;
case "0":
Relay1.setChecked(false);
break;
default:
break;
}
}
Log.i("Socket", socket.getInetAddress().toString());
break;
因此,当启用上述//Log.i("UnoCon",UnoCon.getStatus().toString());
时,它始终会运行。
当我尝试使用一些断点时,我意识到了这一点:
doInBackground
&amp;做一切毫无例外AsyncTask
课程&amp;然后我不知道会发生什么答案 0 :(得分:0)
也许你在AsyncTask上调用了cancel()
请参阅:http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
答案 1 :(得分:0)
问题在于这一行:
while (!(UnoCon.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("UnoCon",UnoCon.getStatus().toString());
}
你在bakcgorund线程上启动了这些东西,但是你阻止了UI线程。
首先,这是完全错误的。使用while loop
等待来自后台线程的内容来阻止UI线程与直接在UI线程上执行后台工作一样糟糕。
然后onPostExecute
未执行的原因是因为此方法在队列上要在UI线程上处理,但是您阻止了UI线程。
要解决此问题,您必须删除此循环并找到另一种处理后台线程完成后正在处理的内容的方法。