我想使用Android Native运行两个连接:
public class MyPublicClass extends AppCompatActivity {
这是第一堂课
private class GetNextQuestionIndex extends AsyncTask<String, Void, Void> {
//some code
protected Void doInBackground(String... params) {
URL url = new URL("url1");
//some code to initialize connection and get the output
MyPublicClass.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mytxtview.setText(output1)
System.out.println("1");
progress.dismiss();
}
});
这是第二类
private class GetLibelleOfQuestion extends AsyncTask<String, Void, Void> {
//some code
protected Void doInBackground(String... params) {
URL url = new URL("url2");
//some code to initialize another connection and get another output
MyPublicClass.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mytxtview.setText(output2)
System.out.println("2");
progress.dismiss();
}
});
}//the end of the public class
但是当我运行我的代码时,它会给我
2 1
我该怎么做
1 2
吗
这意味着在GetNextQuestionIndex
GetLibelleOfQuestion
的运行
答案 0 :(得分:1)
onCreateActivity(...){
...
ShowDialog();
AsyncTask1(...).execute();
}
public void callAsyncTask2(){
AsyncTask2(...).execute();
}
class AsyncTask1(...){
....
onPostExecute(...){
activity.callAsyncTask2();
}
}
class AsyncTask2(...){
....
onPostExecute(...){
activity.dismissDialog();
}
}
希望它有所帮助。
答案 1 :(得分:0)
您可以使用set第二个线程暂时休眠(等待第一个线程执行):
private class GetLibelleOfQuestion extends AsyncTask<String, Void, Void> {
...
MyPublicClass.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Thread.sleep(WAIT_TIME_IN_MILLISECONDS);
mytxtview.setText(output2)
System.out.println("2");
progress.dismiss();
}
});
}//the end of the public class
答案 2 :(得分:0)
这是调用2 asyn任务的正确方法。
private class GetNextQuestionIndex extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
URL url = new URL("url2");
//run your background task
return results;
}
@Override
protected void onPostExecute(String result) {
mytxtview.setText(output1)
System.out.println("1");
new GetLibelleOfQuestion ().execute("");
}
@Override
protected void onPreExecute() {
progress.dismiss();
}
@Override
protected void onProgressUpdate(Void... values) {}
}
}
//Second asyn task
private class GetLibelleOfQuestion extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
URL url = new URL("url2");
//run your background task
return results;
}
@Override
protected void onPostExecute(String result) {
mytxtview.setText(output2)
System.out.println("2");
progress.dismiss();
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
}
oncreate方法调用或按钮点击,您想要的地方
new GetNextQuestionIndex ().execute("");