我正在重构一个使用 AsyncTask 对 Web 服务进行 HTTP 调用的应用程序。
现在使用一个简单的 Activity,此时我需要以这种方式使用 AsyncTask 调用服务:
private class MyAsyncTask extends AsyncTask {<String, Void, Boolean>
private ProgressDialog progressDialog;
private xmlHandler handler;
@ Override
protected void OnPreExecute () {
progressDialog = new ProgressDialog (home.This);
progressDialog
. SetMessage (getString (R.string.home_loadinfo_attendere));
progressDialog.setCancelable (false);
progressDialog.show ();
}
@ Override
protected Boolean doInBackground (String... params) {
try {
xmlHandler handler = new XmlHandler();
return Service
. GetInstance ()
. CallService (
ServiceType.GETINFO,
Home.This, handler, null);
} Catch (Exception e) {
e.printStackTrace ();
return false;
}
}
@ Override
protected void OnPostExecute (Boolean success) {
progressDialog.dismiss ();
String message = null;
if (success | | (handler == null))
message = getString (R.string.server_result_msg500);
else {
switch (handler.getStatusCode ()) {
case 200:
doStuffWithHandler(handler);
return;
case 500:
message = getString (R.string.server_result_msg500);
break;
case 520:
message = getString (R.string.server_result_msg520);
break;
default:
message = getString (R.string.server_result_msg500);
break;
}
}
if (message! = null) {
AlertDialog.Builder builder = new AlertDialog.Builder (home.This);
builder.setTitle (R.string.home_loadinfo_error_title)
. SetMessage (message)
. SetCancelable (true)
. SetNegativeButton (R.string.close_title,
new DialogInterface.OnClickListener () {
@ Override
public void onClick (DialogInterface dialog,
int id) {
dialog.cancel ();
}
});
AlertDialog alert = builder.create ();
Alert.show ();
}
}
}
doStuffWithHandler(handler){
// populate interface with data from service
}
我想做同样的事情,但使用 Android 兼容性库和 FragmentActivity。我读了一些关于 loader 的内容,但我不明白如何以同样的方式使用它们,你能否告诉我这是否是正确的方式(FragmentActivity、Fragment 和 Loader)以及如何实现它也解决了给我的例子?