Android 中 AsyncTask 的通用类? [英] Common class for AsyncTask in Android?

查看:20
本文介绍了Android 中 AsyncTask 的通用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用类,例如 A 类,它扩展了 AsyncTask 并实现了所有方法,即 onPreExecutedoinbackgroundonPostExecute.

I have a common class say for eg Class A which extends AsyncTask and has all the methods implemented i.e. onPreExecute, doinbackground and onPostExecute.

现在,还有其他类想要使用 A 类对象.

Now, there are other classes which want to use Class A object.

说 B 类以下面的方式使用 A 类

Say Class B uses class A in the below manner

A a = new A(context)
a.execute(url)

然后我在 get 方法中获取结果.但是 get 方法不是使用 AsyncTask 的正确方法.我想在 onPostExecute 中得到结果.为此,我尝试使用一个布尔参数,该参数仅在 onpostexecute 中才会为真.B 类会检查直到它为真,当它为真时,它会获取结果.

Then i fetch the result in get method. But get method is not the proper way of using AsyncTask. I will like to get the result in onPostExecute. For that i tried using a boolean parameter which will get true only in onpostexecute. The class B will check till it gets true and when it gets true it will fetch the result.

但这以某种方式阻止了应用程序.

But this is somehow blocking the application.

我在下面放置了 asynctask 的代码.

I have placed the code for asynctask below.

'

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.ResponseHandler;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.BasicResponseHandler;

import org.apache.http.impl.client.DefaultHttpClient;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class A extends AsyncTask<String, Void, String> 
{
private Context context = null;

private final HttpClient httpClient = new DefaultHttpClient();

private String content = null;
//private String error = null;
private String finalResult = null;
private static boolean isResult = false;

private ProgressDialog progressDialog = null; 

public BabbleVilleSyncTask(Context context)
{
    this.context = context; 
    progressDialog = new ProgressDialog(this.context);
}

protected void onPreExecute() 
{
    progressDialog.setMessage("Please Wait....");
    progressDialog.show();
}

protected String doInBackground(String... urls) 
{
    try 
    {
        //urls[0] = URLEncoder.encode(urls[0], "UTF-8");

        HttpGet httpget = new HttpGet(urls[0]);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        content = httpClient.execute(httpget, responseHandler);
    }
    /*catch(UnsupportedEncodingException ue)
    {
        error = ue.getMessage();
    }*/
    catch (ClientProtocolException e) 
    {
        //error = e.getMessage();
        cancel(true);
    }
    catch (IOException e) 
    {
        //error = e.getMessage();
        cancel(true);
    }

    httpClient.getConnectionManager().shutdown();

    return content;
}

protected void onPostExecute(String result) 
{
    finalResult = result;
    progressDialog.dismiss();
    System.out.println("on Post execute called");
    isResult = true;
}  

public boolean getIsResult()
{
    return isResult;
}

public void setIsResult(boolean flag)
{
    isResult = flag;
}

public String getResult()
{
    return finalResult;
}
}

'

有人可以告诉我可能是什么问题吗?

Can someone let me know what the issue may be?

问候

苏尼尔

推荐答案

使用 AsyncTask 获取结果的一种简洁方法是使用回调接口.

A clean way to use AsyncTask to get a result would be to use a callback interface.

这是这个概念的一个简单例子:

Here is a simple example of this concept:

interface AsyncTaskCompleteListener<T> {
   public void onTaskComplete(T result);
}

然后在你的 B 班:

class B implements AsyncTaskCompleteListener<String> {

    public void onTaskComplete(String result) {
        // do whatever you need
    }

    public void launchTask(String url) {
        A a = new A(context, this);
        a.execute(url);
    }
}

您现在应该将以下代码添加到您的 A 类中:

you should now add the following code to your A class:

class A extends AsyncTask<String, Void, String> {
    private AsyncTaskCompleteListener<String> callback;

    public A(Context context, AsyncTaskCompleteListener<String> cb) {
        this.context = context;
        this.callback = cb;
    }

    protected void onPostExecute(String result) {
       finalResult = result;
       progressDialog.dismiss();
       System.out.println("on Post execute called");
       callback.onTaskComplete(result);
   }  
}

这样,你不需要明确地等待你的任务完成,相反,你的主代码(可能是主 UI 线程)在正常的 android 事件循环中等待,并且 onTaskComplete 方法将是自动调用,允许在那里处理任务结果.

This way, you don't need to wait explicitely for your task to complete, instead, your main code (which is probably the main UI thread), is waiting in the normal android event loop, and the onTaskComplete method will be automatically called, allowing to handle the task result there.

这篇关于Android 中 AsyncTask 的通用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆