如何同时使用ProgressDialog和Async Task get方法

发布于 2024-12-14 05:15:11 字数 1991 浏览 0 评论 0原文

我有通用的异步任务类,它从服务器获取响应。我通过使用 get 方法收到这些响应。现在我知道当我使用 get 方法时 UI 线程被阻塞,因为我的进度对话框没有按时显示。

现在有人可以告诉我替代方案吗? (在每种情况下,我都需要将响应发送回已调用执行的活动,因此打开新活动对我没有帮助)

代码: 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();
}

代码:Activity

GetDataFromNetwork request = new GetDataFromNetwork(
                                        this,
                                        ProgressDialog.STYLE_SPINNER,
                                        getResources().getText(R.string.autenticate).toString());
response= (SoapObject)request.execute().get();

I have generic async task class which fetches response from server . And i receive those response by using get method . Now i knw that UI thread is block when i use get method , bcoz of which my progress Dialog doesnt showup on time .

Now can someone tell me alternative to do this ?? (In every case i need to send back the response to the activity which has made the call of execute so opening new activity wouldn't help me )

Code :
AsyncTask Class

 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();
}

Code : Activity

GetDataFromNetwork request = new GetDataFromNetwork(
                                        this,
                                        ProgressDialog.STYLE_SPINNER,
                                        getResources().getText(R.string.autenticate).toString());
response= (SoapObject)request.execute().get();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

呢古 2024-12-21 05:15:11

我一直在我的应用程序中做这样的事情,我发现最简单的方法是创建“回调”接口并将其作为参数传递给我的“AsyncTask”。您执行“doInBackground()”处理,完成后,您可以从 onPostExecute 调用“Callback”实例,并将“result”对象作为参数传递。

下面是它的一个非常简化的版本。

回调接口的示例:

package example.app;

public interface Callback {

        void run(Object result);
}

使用上面的回调接口的 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();
  }

}

如何在应用程序中使用上面的类的示例:

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();      
   }
}

I'm doing stuff like this all the time in my apps and the easiest way I found was to create "Callback" interface and pass it as a parameter to my "AsyncTask"s. You do your "doInBackground()" processing and when it's finished you call the "Callback" instance from onPostExecute passing the "result" object as parameter.

Below is a very simplified version of it.

Example of Callback interface:

package example.app;

public interface Callback {

        void run(Object result);
}

Example of AsyncTask using the Callback interface above:

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();
  }

}

Example of how to use the classes above in your app:

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();      
   }
}
装迷糊 2024-12-21 05:15:11

就像 yorkw 所说,问题是你让 UI 线程等待这段代码的响应:

response= (SoapObject)request.execute().get();

正如 AsyncTask.get() 说:

如有必要,等待计算完成,然后检索
它的结果。

由于 UI 线程等待响应,因此无法显示进度对话框。解决方案是将处理响应的代码移至 onPostExecute() 方法:

protected void onPostExecute(Object result) {
    super.onPostExecute(result);

    // Now we have the response, dismiss the dialog and handle the response
    progressDialog.dismiss();
    response = (SoapObject) result;
}

此方法将在您获得响应后调用。同时,UI 线程可以负责显示进度对话框。

Like yorkw says, The problem is that you make the UI thread wait for the response with this code:

response= (SoapObject)request.execute().get();

As the documentation for AsyncTask.get() says:

Waits if necessary for the computation to complete, and then retrieves
its result.

Since the UI thread waits for the response, it can't show a progress dialog. The solution is to move the code that handles the response to the onPostExecute() method:

protected void onPostExecute(Object result) {
    super.onPostExecute(result);

    // Now we have the response, dismiss the dialog and handle the response
    progressDialog.dismiss();
    response = (SoapObject) result;
}

This method will be invoked after you have the response. Meanwhile, the UI thread can take care of showing a progress dialog.

笑梦风尘 2024-12-21 05:15:11

为什么不创建另一个类,在其中放置响应,并在其中包含 get 和 set 方法。然后在 onPostExecute 中,您使用 set 方法编写它并调用处理程序,您将在其中执行您想要的任何操作...这只是一个想法...:)

Why don't create another class in which you will put response and in there you will have get and set method. Then in onPostExecute you write it with set method and call a handler where you will do whatever you want...This is just an idea... :)

倚栏听风 2024-12-21 05:15:11

如果您使用 AsyncTask,您的 UI 线程将不会被阻塞。您是否在 doInBackground() 中下载数据?因为那是你应该做的地方。

If you are using the AsyncTask, your UI thread won't be blocked. Are you downloading your data inside doInBackground() ? Because that is where you should be doing it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文