所以我用这段代码来调用我的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监视器中看到这两个总是执行
Log.d("before","make_connection");
Log.d("after","make_connection");
但有一半时间我无法看到
产生的输出Log.d("Connection","Started");
Log.e("Connec","this runs");
即使onPreExecute()
每次都正常运行。
我已经测试了两个运行7.1和7.0的不同的手机
有人可以告诉我为什么会这样吗
答案 0 :(得分:4)
尝试:
new Make_Connection().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
而不仅仅是
new Make_Connection().execute();
这是必需的,因为在Android SDK 13或更高版本中,它们默认以串行方式运行。因此,如果您想同时运行多个AsyncTask
,请使用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
有关详细信息,请参阅This docs
答案 1 :(得分:1)
AsyncTasks默认按顺序运行。它们都在同一个执行器上执行。取自https://developer.android.com/reference/android/os/AsyncTask.html
如果您真的想要并行执行,可以调用 executeOnExecutor(java.util.concurrent.Executor,Object [])with THREAD_POOL_EXECUTOR。