从几个AsyncTasks获取结果

时间:2013-03-25 13:39:04

标签: android service android-asynctask

嗨,谢谢你的帮助。

我有一个method来调用AsyncTask从网络中检索一些数据。

method 会按顺序多次调用,因此会启动多个AsyncTasks

method的每次发布开始,我需要从相对的AsyncTask(而不是之前或之后调用的其他AsyncTask)中获取正确的结果。

非常感谢任何帮助。


编辑编辑编辑 添加了其余代码。

请注意:整个过程在服务中运行。

public static class UpdateService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int[] appWidgetIds = intent.getIntArrayExtra("widgetsids");
        final int N = appWidgetIds.length;
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];
            Log.e("","i="+Integer.toString(i)+ " di "+Integer.toString(N));
            RemoteViews view = buildUpdate(getApplicationContext(),
                    appWidgetIds);
            manager.updateAppWidget(appWidgetId, view);
        }
        return (START_NOT_STICKY);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

private static  RemoteViews buildUpdate(Context ctxt, int[] appWidgetIds) {
    RemoteViews updateViews = new RemoteViews(ctxt.getPackageName(),
            R.layout.widget);
        updateViews.setTextViewText(R.id.price1, getPrice(list.get(0)
            .getSymbol()));

 }        
    //THIS METHOD IS CALLED SEVERAL TIMES IN SEQUENCE    <----
    private static String getPrice(String symbol) {
    String result="";
    UpdateTaskPrice up = new UpdateTaskPrice();
    up.execute(symbol, null, null);
    //HERE I WANT THE RESULT FROM onPostExecute()    <----
    return result;
}

//THIS IS THE ASYNCTASK WHICH IS LAUNCHED SEVERAL TIMES
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {

    @Override
    protected void onProgressUpdate(Void... progress) {
    }

    @Override
    protected void onPostExecute(String result) {
    //HERE I RECEIVE THE RESULT FROM doInBackground    <----
    //I NEED TO PASS IT BACK TO getPrice()    <----
    }

    @Override
    protected String doInBackground(String... symbol) {
        String result = "";
        DefaultHttpClient client = new DefaultHttpClient();
        String srt = "";

        String url = context.getString(R.string.urlaternativo).concat(
                symbol[0]);

        HttpGet getMethod = new HttpGet(url);
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            srt = client.execute(getMethod, responseHandler);
            int inizio = srt.indexOf("<last data=\"");
            int fine = srt.indexOf("\"/>", inizio + 12);
            result = srt.substring(inizio + 12, fine);

        } catch (Throwable t) {
            // Log.e("ERROR", "ERROR", t);
        }
        //HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute()    <----
        return result;
    }
}

3 个答案:

答案 0 :(得分:10)

AsyncTask是异步的,在一个单独的线程中运行。因此,在执行它之后,不可能在下一个语句中获得AsyncTask的结果。

要从AsyncTask获取相关结果,请在UpdateTaskPrice类中添加成员变量“mRequestId”,并在调用UpdateTaskPrice.execute之前设置唯一请求ID。

在UpdateTaskPrice类的“onPostExecute”方法中,您可以使用此请求ID返回并处理结果。

public class UpdateTaskPrice extends AsyncTask<String, Void, String> {

    protected int mRequestId;

    public void setRequestId (int requestId)
    {
        this.mRequestId = requestId;
    }

    @Override
    protected void onProgressUpdate(Void... progress) {
    }

    @Override
    protected void onPostExecute(String result) {
        // do whatever with result using mRequestId
    }

    @Override
    protected String doInBackground(String... symbol) {
        String result = "";
        DefaultHttpClient client = new DefaultHttpClient();
        String srt = "";

        String url = context.getString(R.string.urlaternativo).concat(
                symbol[0]);

        HttpGet getMethod = new HttpGet(url);
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            srt = client.execute(getMethod, responseHandler);
            int inizio = srt.indexOf("<last data=\"");
            int fine = srt.indexOf("\"/>", inizio + 12);
            result = srt.substring(inizio + 12, fine);

        } catch (Throwable t) {
            // Log.e("ERROR", "ERROR", t);
        }
        //HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute()    <----
        return result;
    }
}

答案 1 :(得分:0)

好吧,我认为您可以在AsyncTask的构造函数中传递唯一的请求ID。然后在postExecute()方法中,使用结果和唯一请求ID -

更新UI
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {

    private int mIdentifier;
    private Service mService;

    public UpdateTaskPrice(Service service, int identifier) {
        this.mIdentifier = identifier;
    }

    @Override
    protected void onProgressUpdate(Void... progress) {
    }

    @Override
    protected void onPostExecute(String result) {
        ((UpdateService) mService).informPrice(mIdentifier, result);
    }

    @Override
    protected String doInBackground(String... symbol) {
        String result = "";
        DefaultHttpClient client = new DefaultHttpClient();
        String srt = "";

        String url = context.getString(R.string.urlaternativo).concat(
                symbol[0]);

        HttpGet getMethod = new HttpGet(url);
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            srt = client.execute(getMethod, responseHandler);
            int inizio = srt.indexOf("<last data=\"");
            int fine = srt.indexOf("\"/>", inizio + 12);
            result = srt.substring(inizio + 12, fine);

        } catch (Throwable t) {
            // Log.e("ERROR", "ERROR", t);
        }
        //HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute()    <----
        return result;
    }
}

答案 2 :(得分:0)

您可以从多个asynctask中获取数据,但您无法获得所需的结果 使用asyctask,你需要使用更多的封装来解决这个问题。

你的结构问题是......

 private static String getPrice(String symbol) {
    String result="";
    UpdateTaskPrice up = new UpdateTaskPrice();
    up.execute(symbol, null, null);
    //HERE I WANT THE RESULT FROM onPostExecute()    <----
    return result;
}

当你启动新线程时,它将首先执行在task.execute(符号)之后返回的语句;在你的情况下,它是return语句然后它将exucute pre .. doin ..并发布...

Hear是您可以用来从多个AsycTask

中检索数据的模式
//Calling to the method callAsyncTask;
callAsyncTask(new AsyncResultCallback(){
    public void onResult(String result, String symbol){
        //TODO dosomthing with the result
    }
});


public void callAsyncTask(AsyncResultCallback callback){
    new UpdateTaskPrice(callback).execurte(symbol);
}

public interface AsyncResultCallback{
    public void onResult(String result, String symbol);
}

public class UpdateTaskPrice extends AsyncTask<String, Void, String> {

    AsyncResultCallback callback;
    String symbol;

    UpdateTaskPrice(AsyncResultCallback callback){
        this.callback = callback;
    }

    @Override
    protected void onProgressUpdate(Void... progress) {
    }

    @Override
    protected void onPostExecute(String result) {
        callback.onResult(result, symbol);
    }

    @Override
    protected String doInBackground(String... symbol) {
        this.symbol = symbol;
        String result = "";
        DefaultHttpClient client = new DefaultHttpClient();
        String srt = "";

        String url = context.getString(R.string.urlaternativo).concat(symbol[0]);

        HttpGet getMethod = new HttpGet(url);
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            srt = client.execute(getMethod, responseHandler);
            int inizio = srt.indexOf("<last data=\"");
            int fine = srt.indexOf("\"/>", inizio + 12);
            result = srt.substring(inizio + 12, fine);

        } catch (Throwable t) {
            // Log.e("ERROR", "ERROR", t);
        }
            //HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute()    <----
        return result;
    }
}

希望有所帮助。