2016-05-26 1 views
1

J'ai suivi ce post pour mettre en place une demande Http Async: HttpRequestHTTP Android: Faire plus de 1 AsyncTask demande

Donc, maintenant, je l'appelle: new DownloadTask().execute("http://www.google.com/"); pour faire cette demande.

Comment puis-je gérer différents appels? Par exemple:

new DownloadTask().execute("http://www.google.com/"); 
new DownloadTask().execute("http://www.facebook.com/"); 
new DownloadTask().execute("http://www.twitter.com/"); 

Et d'obtenir des résultats différents?

+2

Comment voulez-vous que les appels soient faits? L'un après l'autre? –

+0

Non .. Je dois faire un appel et quand le premier est fini, en faire un autre. C'est pourquoi parfois j'ai besoin du résultat du premier –

Répondre

2

Passez un argument supplémentaire au AsyncTask. Faites des constantes correspondant à vos tâches.

new DownloadTask().execute("http://www.google.com/", DownloadTask.ID_ASYNC1); 
new DownloadTask().execute("http://www.facebook.com/", DownloadTask.ID_ASYNC2); 
new DownloadTask().execute("http://www.twitter.com/", DownloadTask.ID_ASYNC3); 

intérieur AsyncTask, utilisez cet identifiant pour identifier qui est la demande appelée.

private class DownloadTask extends AsyncTask<String, Void, String> { 
    //Variable for storing the req id 
    private int id; 

    //Constants corresponding to your tasks 
    public static int ID_ASYNC1 = 0; 
    static static int ID_ASYNC1 = 0; 
    static static int ID_ASYNC1 = 0; 

    @Override 
    protected String doInBackground(String... params) { 
     id = params[1]); 
     //your code 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     if(id == ID_ASYNC1){ 
      //Do your task #1 
     } else if(id == ID_ASYNC2){ 
      //Do your task #2 
     } 
    } 
} 
+0

Oui! C'est bien ... –

+0

Est-il possible "OnPostExecute" de retourner à la classe MainActivity le résultat JSON? –

+0

Oui c'est possible, vous devez créer une 'interface' pour cela. Voir ce lien, http://cyriltata.blogspot.in/2013/10/android-re-using-asynctask-class-across.html –

0

Vous devez utiliser looper pour le téléchargement lisse pour plusieurs fichiers, il les téléchargera un par un. De cette façon, votre application fonctionne en douceur énorme quantité de téléchargements.

Comment utiliser Looper

public class MainActivity extends Activity implements DownloadThreadListener, 
     OnClickListener { 

    private DownloadThread downloadThread; 
    private Handler handler; 
    private ProgressBar progressBar; 
    private TextView statusText; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Create and launch the download thread 
     downloadThread = new DownloadThread(this); 
     downloadThread.start(); 

     // Create the Handler. It will implicitly bind to the Looper 
     // that is internally created for this thread (since it is the UI 
     // thread) 
     handler = new Handler(); 

     progressBar = (ProgressBar) findViewById(R.id.progress_bar); 
     statusText = (TextView) findViewById(R.id.status_text); 

     Button scheduleButton = (Button) findViewById(R.id.schedule_button); 
     scheduleButton.setOnClickListener(this); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 

     // request the thread to stop 
     downloadThread.requestStop(); 
    } 

    // note! this might be called from another thread 
    @Override 
    public void handleDownloadThreadUpdate() { 
     // we want to modify the progress bar so we need to do it from the UI 
     // thread 
     // how can we make sure the code runs in the UI thread? use the handler! 
     handler.post(new Runnable() { 
     @Override 
     public void run() { 
      int total = downloadThread.getTotalQueued(); 
      int completed = downloadThread.getTotalCompleted(); 

      progressBar.setMax(total); 

      progressBar.setProgress(0); // need to do it due to a 
           // ProgressBar bug 
      progressBar.setProgress(completed); 

      statusText.setText(String.format("Downloaded %d/%d", completed, 
        total)); 

      // vibrate for fun 
      if (completed == total) { 
       ((Vibrator) getSystemService(VIBRATOR_SERVICE)) 
        .vibrate(100); 
      } 
     } 
     }); 
    } 

    @Override 
    public void onClick(View source) { 
     if (source.getId() == R.id.schedule_button) { 
     int totalTasks = new Random().nextInt(3) + 1; 

     for (int i = 0; i < totalTasks; ++i) { 
      downloadThread.enqueueDownload(new DownloadTask()); 
     } 
     } 
    } 
} 

DownloadThread.Class

public final class DownloadThread extends Thread { 

    private static final String TAG = DownloadThread.class.getSimpleName(); 
    private Handler handler; 
    private int totalQueued; 
    private int totalCompleted; 
    private DownloadThreadListener listener; 
    public DownloadThread(DownloadThreadListener listener) { 
     this.listener = listener; 
    } 

    @Override 
    public void run() { 
     try { 
     // preparing a looper on current thread 
     // the current thread is being detected implicitly 
     Looper.prepare(); 

     Log.i(TAG, "DownloadThread entering the loop"); 

     // now, the handler will automatically bind to the 
     // Looper that is attached to the current thread 
     // You don't need to specify the Looper explicitly 
     handler = new Handler(); 

     // After the following line the thread will start 
     // running the message loop and will not normally 
     // exit the loop unless a problem happens or you 
     // quit() the looper (see below) 
     Looper.loop(); 

     Log.i(TAG, "DownloadThread exiting gracefully"); 
     } catch (Throwable t) { 
     Log.e(TAG, "DownloadThread halted due to an error", t); 
     } 
    } 

    // This method is allowed to be called from any thread 
    public synchronized void requestStop() { 
     // using the handler, post a Runnable that will quit() 
     // the Looper attached to our DownloadThread 
     // obviously, all previously queued tasks will be executed 
     // before the loop gets the quit Runnable 
     handler.post(new Runnable() { 
     @Override 
     public void run() { 
      // This is guaranteed to run on the DownloadThread 
      // so we can use myLooper() to get its looper 
      Log.i(TAG, "DownloadThread loop quitting by request"); 

      Looper.myLooper().quit(); 
     } 
     }); 
    } 

    public synchronized void enqueueDownload(final DownloadTask task) { 
     // Wrap DownloadTask into another Runnable to track the statistics 
     handler.post(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       task.run(); 
      } finally { 
       // register task completion 
       synchronized (DownloadThread.this) { 
        totalCompleted++; 
       } 
       // tell the listener something has happened 
       signalUpdate(); 
      } 
     } 
     }); 

     totalQueued++; 
     // tell the listeners the queue is now longer 
     signalUpdate(); 
    } 

    public synchronized int getTotalQueued() { 
     return totalQueued; 
    } 

    public synchronized int getTotalCompleted() { 
     return totalCompleted; 
    } 

    // Please note! This method will normally be called from the download 
    // thread. 
    // Thus, it is up for the listener to deal with that (in case it is a UI 
    // component, 
    // it has to execute the signal handling code in the UI thread using Handler 
    // - see 
    // DownloadQueueActivity for example). 
    private void signalUpdate() { 
     if (listener != null) { 
     listener.handleDownloadThreadUpdate(); 
     } 
    } 
} 

DownloadTask.Class

public class DownloadTask implements Runnable { 
    private static final String TAG = DownloadTask.class.getSimpleName(); 
    private static final Random random = new Random(); 
    private int lengthSec; 
    public DownloadTask() { 
     lengthSec = random.nextInt(3) + 1; 
    } 

    @Override 
    public void run() { 
     try { 
     Thread.sleep(lengthSec * 1000); 
     // it's a good idea to always catch Throwable 
     // in isolated "codelets" like Runnable or Thread 
     // otherwise the exception might be sunk by some 
     // agent that actually runs your Runnable - you 
     // never know what it might be. 
     } catch (Throwable t) { 
     Log.e(TAG, "Error in DownloadTask", t); 
     } 
    } 
} 

DownloadThreadListener.class (Interface)

public interface DownloadThreadListener { 
    void handleDownloadThreadUpdate(); 
} 

En utilisant cela, vous pouvez ajouter énorme quantité de téléchargements il les ajoutera la file d'attente. Complete tutorial

+0

En ce moment, j'ai besoin de construire ma chaîne d'URL. J'utilise un fichier PHP sur le serveur. Comment faire? –

+0

comment vous frappez l'URL? –

+0

Frapper? Que voulez-vous dire? –