AsyncTask执行,但仅在某些情况下执行 [英] AsyncTask executes but only sometimes
问题描述
所以我用这段代码来调用我的AsyncTask
So i use this code to call my AsyncTask
Log.d("before","make_connection");
new Make_Connection().execute();
Log.d("after","make_connection");
我的课
private class Make_Connection extends AsyncTask<Void,Void,String>{
final int port = 4445;
@Override
protected void onPreExecute() {
Toast.makeText(KeyboardActivity.this,"This runs",Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
Log.d("Connection","Started");
Log.e("Connec","this runs");
try {
socket = new Socket(IP,port);
//dout = new DataOutputStream(socket.getOutputStream());
//dout.writeUTF("Connection Formed");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
Toast.makeText(KeyboardActivity.this,"Connection Made",Toast.LENGTH_SHORT).show();
}
}
现在我可以在android监视器中看到这两个始终执行
Now i can see in the android monitor that these two are always execute
Log.d("before","make_connection");
Log.d("after","make_connection");
但是有一半时间我看不到产生的输出
But half of the time i cannot see the output produced by
Log.d("Connection","Started");
Log.e("Connec","this runs");
即使onPreExecute()
每次都能正常运行.
我已经对运行7.1和7.0的两种不同的移动设备进行了测试
Even though onPreExecute()
runs properly everytime.
I have tested on two diffent mobilies running 7.1 and 7.0
有人可以告诉我为什么会发生这种情况吗
Can someone please tell me why this is happening
推荐答案
尝试:
new Make_Connection().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
而不只是
new Make_Connection().execute();
这是必需的,因为在默认情况下,它们在Android SDK 13或更高版本中按顺序运行.因此,如果要同时运行多个AsyncTask
,请使用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
有关更多详细信息,请参见该文档
This is needed, because in Android SDK 13 or higher they run serially by default. So if you want to run more than one AsyncTask
simultaneously, use executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
For more details, see explanation under order of execution from This docs
这篇关于AsyncTask执行,但仅在某些情况下执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!