Cod*_*ife 2 android progressdialog android-asynctask
我有通用的异步任务类,它从服务器获取响应.我通过使用get方法接收这些响应.现在,当我使用get方法时,我知道UI线程是块,bcoz我的进度Dialog没有按时显示.
现在可以有人告诉我替代做这个吗?(在每种情况下,我都需要将响应发送回执行调用的活动,因此打开新活动对我没有帮助)
代码:AsyncTask类
public class GetDataFromNetwork extends AsyncTask<Void,String,Object> {
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
protected Object doInBackground(Void... params) {
Object result = null;
try {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
new MarshalBase64().register(envelope);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(ipAddress + webService);
System.setProperty("http.keepAlive", "true");
try {
androidHttpTransport.call(nameSpace + methodName, envelope);
} catch (Exception e) {
e.printStackTrace();
publishProgress(e.getMessage());
}
androidHttpTransport.debug = true;
System.out.println("response: " + androidHttpTransport.requestDump);
result = envelope.getResponse();
if(result!=null){
System.out.println("GetDataFromNetwork.doInBackground() result expection---------"+result);
}
} catch (Exception e) {
System.out.println("GetDataFromNetwork.doInBackground()-------- Errors");
e.printStackTrace();
}
return result;
}
protected void onPostExecute(Object result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
Run Code Online (Sandbox Code Playgroud)
代码:活动
GetDataFromNetwork request = new GetDataFromNetwork(
this,
ProgressDialog.STYLE_SPINNER,
getResources().getText(R.string.autenticate).toString());
response= (SoapObject)request.execute().get();
Run Code Online (Sandbox Code Playgroud)
Dal*_*osa 10
我在我的应用程序中一直在做这样的事情,我发现最简单的方法是创建"回调"接口并将其作为参数传递给我的"AsyncTask".你执行"doInBackground()"处理,当它完成时,从onPostExecute调用"Callback"实例,将"result"对象作为参数传递.
下面是它的一个非常简化的版本.
回调接口示例:
package example.app;
public interface Callback {
void run(Object result);
}
Run Code Online (Sandbox Code Playgroud)
使用上面的Callback接口的AsyncTask示例:
public class GetDataFromNetwork extends AsyncTask<Void,String,Object> {
Callback callback;
public GetDataFromNetwork(Callback callback){
this.callback = callback;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
protected Object doInBackground(Void... params) {
Object result = null;
// do your stuff here
return result;
}
protected void onPostExecute(Object result) {
callback.run(result);
progressDialog.dismiss();
}
}
Run Code Online (Sandbox Code Playgroud)
如何在您的应用中使用上述类的示例:
class Example {
public onCreate(Bundle savedInstanceState){
//initialize
GetDataFromNetwork request = new GetDataFromNetwork(new Callback(){
public void run(Object result){
//do something here with the result
}});
request.execute();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5923 次 |
| 最近记录: |