就像我需要检查用户名是否已存在于数据库中一样,程序在响应到达之前不会继续。
看来你需要asynctask,这是一个如何使用它的例子..
public class YourFragment extends Fragment implements YourAsyncTask.YourInterface {
public YourFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_your, container, false);
//do your initial things
.
.
.
YourAsyncTask yourAsyncTask = new YourAsyncTask(this);
yourAsyncTask.execute();
return view;
}
@Override
public void onJobFinishListener(YourDataType yourData) {
//when this method is trigered by your asynctask
//it means that you are in ui thread and update your ui component
//TODO: update ui component with your data
}
}
这是asynctask;
public class YourAsyncTask extends AsyncTask {
private YourInterface yourInterfaceListener;
private YourDataType yourData; //this data should be calculated in doInBackground method and send via interface
public YourAsyncTask(YourInterface yourInterfaceListener) {
this.yourInterfaceListener = yourInterfaceListener;
}
@Override
protected Object doInBackground(Object[] objects) {
//do your all background tasks here
.
.
.
yourData = do something here to fill your data..
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
yourInterfaceListener.onJobFinishListener(yourData);
}
public interface YourInterface{
void onJobFinishListener(YourDataType yourData);
}
}
使用AsyncTask执行网络操作
public class TalkToServer extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
/*
* do things before doInBackground() code runs
* such as preparing and showing a Dialog or ProgressBar
*/
}
@Override
protected void onProgressUpdate(Void... values) {
/*
* updating data
* such a Dialog or ProgressBar
*/
}
@Override
protected Void doInBackground(Void... params) {
//do your work here
return null;
}
@Override
protected void onPostExecute(Void result) {
/*
* do something with data here
* display it or send to mainactivity
* close any dialogs/ProgressBars/etc...
*/
}
}
你可以使用它来执行它
TalkToServer myTask = new MyTask(); // can add params for a constructor if needed
myTask.execute(); // here is where you would pass data to doInBackground()
在网络调用完成并且响应获得onPostExecute()
被调用。如果AsyncTask
在你的activity
的内部类中,你可以更新onPostExecute()
内的UI。否则你可以使用Interface
创建callback
到activity
。
你可以找到AsyncTask Docs
here
您必须使用异步任务。然后你可以在你的激活这个你想要的..get方法中使用你的you_async_class.execute()。get()。主线程将等待您的异步任务。你必须改变your_async_class扩展AsyncTask