我正在使用REST从服务器检索一些信息。我使用AsyncTask进行Get调用。但是我需要等待结果...有什么办法可以同步进行吗?这样我就可以得到结果。
码:
private void sendStuff(Context context, String[] params) {
RESTGet restGet = new RESTGet(context);
restGet.setMessageLoading("Loading...");
try {
restGet.execute(params);
} catch (Exception e) {
e.printStackTrace();
}
restGet.stopMessageLoading();
Intent intent = new Intent(context, ShowPictures.class);
((Activity)context).startActivity(intent);
}
谢谢...
最佳答案
您可以使用get()等待任务结束甚至获得结果。但我不建议这样做,因为它将冻结您的应用程序。
假设RESTGet扩展了AsyncTask的示例:
private void sendStuff(Context context, String[] params) {
final int TIMEOUT = 2000;
RESTGet restGet = new RESTGet(context);
restGet.setMessageLoading("Loading...");
try {
restGet.execute(params).get(TIMEOUT, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
}
restGet.stopMessageLoading();
Intent intent = new Intent(context, ShowPictures.class);
((Activity)context).startActivity(intent);
}
而不是使用get,而是将代码放在onPostExecute方法中,以便在任务执行后调用它。
例如:
private void sendStuff(Context context, String[] params) {
RESTGet restGet = new RESTGet(context) {
@Override
protected void onPostExecute(String feed) {
super.onPostExecute(feed);
this.stopMessageLoading();
Intent intent = new Intent(context, ShowPictures.class);
((Activity)context).startActivity(intent);
}
}.execute(params);
}
希望能帮助到你...
关于java - 有什么方法可以拨打电话吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28224541/