1

サーバーにデータを送信するために、いくつかのAsyncTasksを作成しています。SendOnlyOneFactでは、いくつかの画像、GPS位置、文字列、音声などをすべてBase64文字列に変換して送信します。その後、サーバーはデータを取得するたびにIDで応答するため、フィールド「id_Data」に保存します。私の問題は、サーバーの応答を順番に取得する必要があることです。つまり、他のアクションを実行する必要があるため、「順序付けられた非同期タスク」に似たものが必要です。

私はAPI8で作業しています。助けていただければ幸いです。これが私のコードです。

主な手順:

for (int k=0; k<activities.size(); k++){
new SendOnlyOneFact().execute(definition, act, null, k);
}

クラスSendOnlyOneFact:

private class SendOnlyOneFact extends AsyncTask<Object, Void, Void>{
private HttpResponse response;
private int kkk;
private HttpClient httpClient;

@Override
protected void onPreExecute(){
    httpClient = new DefaultHttpClient();
}
@Override
protected void onProgressUpdate(Void... values){}
@Override
protected Void doInBackground(Object... params) {
    kkk = ((Integer) params[3]);
    actividades.get(kkk).saveData((android.app.Activity) params[1]);
    // Serializar los datos creados
    String cosa_serializada = actividades.get(kkk).getMeasure().serializeData(actividades.get(kkk), (android.app.Activity) params[1]);



    HttpHost targetHost = new HttpHost(((GateDefinition) params[0]).getServer(), ((GateDefinition) params[0]).getPort(), "http");

    HttpPost httpPost = new HttpPost("http://" + ((GateDefinition) params[0]).getServer() + ":" + ((GateDefinition) params[0]).getPort() + "/" + ((GateDefinition) params[0]).getWeb_service());
    // Also be sure to tell the server what kind of content we are sending
    httpPost.setHeader("content-type", "text/plain");
    try {
        StringEntity entity = new StringEntity(cosa_serializada, "UTF-8");
        entity.setContentType("text/plain");
        httpPost.setEntity(entity);

        // execute is a blocking call, it's best to call this code in a
        // thread separate from the ui's
        response = httpClient.execute(targetHost, httpPost);

        entity.consumeContent();
    } catch (SocketException ex){
        Log.e("SendOnlyOneFact", "No existe conexión con el servidor");
        ex.printStackTrace();
    } catch (Exception ex){
        ex.printStackTrace();
    } 
    return null;
}

@Override
protected void onPostExecute(Void result){
    if (response != null){
        try {
            this.get();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ExecutionException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedReader reader = null;
        String respuesta = null;
        try {
            reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8192);
            respuesta = reader.readLine();
                actividades.get(kkk).getMeasure().setId_Data(respuesta);

            Log.i("onPostExecute SendOnlyOneFact", "Llegó un ID: " + respuesta);
                reader.close();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SocketException ex){
                ex.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            // Entra aquí cuando ocurre una excepción
            // La IP del servidor es incorrecta
            // El servidor no está ejecutándose
            Toast.makeText(mActivity, "Imposible conectar con el servidor.", Toast.LENGTH_LONG).show();
        }
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.getConnectionManager().shutdown();
    }
}
4

3 に答える 3

2

あなたが求めているのは、AsyncTasksの実行をシリアル化する方法だと思います。これを行うには、forループを削除して、onPostExecuteで次のasyncTaskを開始できます。もう1つの方法は、AsyncTasksを破棄し、ThreadPoolExecutor.newSingleThreadExecutorを使用することです。

于 2013-02-07T21:56:10.270 に答える
0

このデモプロジェクトを見て、助けを求めてください。https://github.com/vitkhudenko/test_asynctask

具体的には、

            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

            task.execute();

このデモプロジェクトは、スレッドプールがどのように機能するかをよりよく理解できるはずです。

于 2013-02-07T21:08:22.373 に答える
0

次のリンクを試してください。

http://android-developers.blogspot.co.uk/2010/07/multithreading-for-performance.html

同時実行性を処理するセクションがあり、返されるデータが正しいAsyncTaskに関連付けられていることを確認するのに役立ちます。

于 2013-02-07T22:45:11.320 に答える