问题
So i use this code to call my AsyncTask
Log.d("before","make_connection");
new Make_Connection().execute();
Log.d("after","make_connection");
My class
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();
}
}
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");
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
回答1:
Try:
new Make_Connection().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
instead of only
new Make_Connection().execute();
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
回答2:
AsyncTasks are run sequentially by default. They all execute on the same executor. Taken from here https://developer.android.com/reference/android/os/AsyncTask.html
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
来源:https://stackoverflow.com/questions/43426810/asynctask-executes-but-only-sometimes