2016-10-26 2 views
1

Dans mon application, lorsque je clique sur le fichier, le téléchargement commence à partir du serveur et la progression s'affiche dans la barre d'état du téléphone. Mais je souhaite que la barre de progression apparaisse sur l'écran de l'application elle-même.Comment utiliser tâche asynchrone pour la boîte de dialogue de progression de téléchargement dans le fragment?

J'ai suivi ce lien: -

http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/

A l'approche énoncé du problème que je rencontre ces SYSTEM_DOWNLOADER et APP_DOWNLOADER.

  1. Que font-ils exactement?

  2. L'exemple ci-dessus est appelé en activité. Je voulais savoir comment appeler la tâche Asynch avec la barre de progression du téléchargement dans le fragment.

Je suis d'édition question de clarification, S'il vous plaît aider

 convertView.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       MoodleModule module = listObjects.get(position).module; 
       if (module == null) 
        return; 
       Intent i = new Intent(context, AppBrowserActivity.class); 

       String modurl = module.getUrl(); 
       String courseurl = session.getmUrl() 
         + "/course/view.php?id=" + courseid; 
       modurl = (modurl == null) ? courseurl : modurl; 
       i.putExtra("url", modurl); 

       if (!module.getModname().contentEquals("resource")) { 
        context.startActivity(i); 
        return; 
       } 

       if (module.getContents() == null) { 
        context.startActivity(i); 
        return; 
       } 

       if (module.getContents().isEmpty()) { 
        context.startActivity(i); 
        return; 
       } 

       MoodleModuleContent content = module.getContents().get(0); 
       String path = "/s" + session.getCurrentSiteId() + "c" 
         + courseid + "/"; 
       File file = new File(Environment 
         .getExternalStoragePublicDirectory("/MDroid") 
         + path + content.getFilename()); 
       //TODO here 
       // Download if file doesn't already exist 
       if (!file.exists()) { 
        String fileurl = content.getFileurl(); 
        fileurl += "&token=" + session.getToken(); 
        fName=content.getFilename(); 

       //FROM HERE I AM CALLING ASYNCHRONOUS TASK 
        startDownload(); 


       } else { 
        FileOpener.open(context, file); 
       } 

      } 
     }); 

     return convertView; 
    } 

    private void startDownload() { 
     String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"; 
     new DownloadFileAsync().execute(url); 
    } 

    protected Dialog onCreateDialog(int id) { 
     switch (id) { 
      case DIALOG_DOWNLOAD_PROGRESS: 
       mProgressDialog = new ProgressDialog(getActivity()); 
       mProgressDialog.setMessage("Downloading file.."); 
       mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
       mProgressDialog.setCancelable(false); 

       return mProgressDialog; 
      default: 
       return null; 
     } 
    } 
    class DownloadFileAsync extends AsyncTask<String, String, String> { 

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

      /*mProgressDialog = new ProgressDialog(getActivity()); 
      mProgressDialog.setMessage("Downloading file."); 
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      mProgressDialog.setCancelable(false); 
      mProgressDialog.show();*/ 
      /*showDialog(DIALOG_DOWNLOAD_PROGRESS);*/ 

      mProgressDialog.show(); 
     } 

     @Override 
     protected String doInBackground(String... aurl) { 
      int count; 
      /*String fName=content.getFilename();*/ 
      /*InputStream input = null; 
      OutputStream output = null;*/ 
      HttpURLConnection connection = null; 
      try { 

       URL url = new URL(aurl[0]); 
       URLConnection conexion = url.openConnection(); 
       conexion.connect(); 

       int lenghtOfFile = conexion.getContentLength(); 
       Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 

      /* File f = new File(Environment.getExternalStorageDirectory() 
        + "/sdcard/"); 
      f.mkdirs();*/ 

       InputStream input = new BufferedInputStream(url.openStream()); 
       OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg"); 

       byte data[] = new byte[1024]; 

       long total = 0; 

       while ((count = input.read(data)) != -1) { 
        total += count; 
        publishProgress(""+(int)((total*100)/lenghtOfFile)); 
        output.write(data, 0, count); 
       } 

       output.flush(); 
       output.close(); 
       input.close(); 
      } catch (Exception e) {} 
      return null; 

     } 
     protected void onProgressUpdate(String... progress) { 

      mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
     /* mProgressDialog.dismiss();*/ 
     } 

     @Override 
     protected void onPostExecute(String unused) { 
     /*dismissDialog(DIALOG_DOWNLOAD_PROGRESS);*/ 
      mProgressDialog.dismiss(); 
     } 
    } 

Lorsque je clique sur le fichier, l'application donne la force stop.what erreur que je fais ?? S'il vous plaît aidez-moi out.thanks

+0

Vous pouvez utiliser '' ProgressBar' ou ProgressDialog' jusqu'à ce que votre fichier soit en cours de téléchargement. – Piyush

+0

Donc, j'ai besoin de connaître la différence entre ces deux choses –

+0

Si vous utilisez _DownloadManager_ alors votre progression sera affichée dans la barre de notification jusqu'à ce que vos fichiers téléchargent et si vous utilisez 'ProgressBar' ou 'ProgressDialog' dans' AsyncTask' alors il sera rejeté dans 'onPostExecuted()' méthode de 'AsyncTask' – Piyush

Répondre

2

J'ai trouvé la réponse par moi-même. J'espère que cela aidera tout le monde. Je voulais appeler une tâche asynchrone en fragment et je voulais montrer un diologue de progrès qui montrerait la progression du téléchargement du fichier en pourcentage.

1> J'ai appelé la tâche asynch en classe.

DownloadTask.java classe

//This is important 
public DownloadTask(Context context) { 
    this.context = context; 
    mProgressDialog = new ProgressDialog(context); 

    mProgressDialog.setMessage("Downloading file.."); 
    mProgressDialog.setIndeterminate(false); 
    mProgressDialog.setMax(100); 
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    mProgressDialog.setCanceledOnTouchOutside(false); 
} 

@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
public void download(String fileUrl, String filepath, String fileName, 
        Boolean visibility, Boolean choice) { 
    // Make directories if required 
    this.fileUrl=fileUrl; 
    this.filepath=filepath; 
    this.fileName=fileName; 
    this.visibility=visibility; 
    File f = new File(
      Environment.getExternalStoragePublicDirectory("/MDroid") 
        + filepath); 
    if (!f.exists()) 
     f.mkdirs(); 


    if (choice == SYSTEM_DOWNLOADER) { 

     String url=fileUrl; 
     new MyAsyncTask().execute(url); 

    } else { 
     mdroidDownload(fileUrl, fileName); 
     reqId =0; 
    } 

} 

class MyAsyncTask extends AsyncTask<String, String, Void> { 

    boolean running; 


    @Override 
    protected Void doInBackground(String...fUrl) { 
     int count; 


     InputStream input = null; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     try { 

      URL url = new URL(fUrl[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 

      int lenghtOfFile = connection.getContentLength(); 

      // download the file 
      input = connection.getInputStream(); 
      output = new FileOutputStream(
        Environment.getExternalStorageDirectory() + "/MDroid/" 
          + fileName); 

//################################# 

    mydownload(fileUrl, filepath, fileName, 
     visibility); 


//########################################## 

      byte data[] = new byte[4096]; 
      long total = 0; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       publishProgress(""+(int)((total*100)/lenghtOfFile)); 
       output.write(data, 0, count); 
      } 

      output.close(); 
      input.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
return null; 

    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     running = true; 

     mProgressDialog.show(); 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 

     mProgressDialog.dismiss(); 
    } 

    protected void onProgressUpdate(String... progress) { 

     // Update the progress dialog 
     mProgressDialog.setProgress(Integer.parseInt(progress[0])); 

    } 


} 




public long mydownload(String fileUrl,String filepath,String fileName,Boolean visibility) 
{ 
    DownloadManager manager = (DownloadManager) context 
      .getSystemService(Context.DOWNLOAD_SERVICE); 

/* TODO- Offer better alternative. Only a temporary, quick, 
* workaround for 2.3.x devices. May not work on all sites. 
*/ 
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) 
     fileUrl = fileUrl.replace("https://", "http://"); 
    Request request = new Request(Uri.parse(fileUrl)); 
    try { 
     request.setDestinationInExternalPublicDir("/MDroid", filepath 
       + fileName); 
    } catch (Exception e) { 
     Toast.makeText(context, "External storage not found!", 
       Toast.LENGTH_SHORT).show(); 
     return 0; 
    } 
    request.setTitle(fileName); 
    request.setDescription("MDroid file download"); 

    // Visibility setting not available in versions below Honeycomb 
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) 
     if (!visibility) 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); 
     else 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 

    // -TODO- save this id somewhere for progress retrieval 
    reqId = manager.enqueue(request); 
    return reqId; 
} 

2> J'ai appelé cette méthode de téléchargement du fichier de classe DownloadTask.java dans mon activité de fragment comme celui-ci

// Download if file doesn't already exist 
       if (!file.exists()) { 
        fileurl = content.getFileurl(); 

        fileurl += "&token=" + session.getToken(); 
        fName = content.getFilename(); 

        //FROM HERE I AM CALLING ASYNCHRONOUS TASK 

        DownloadTask dt = new DownloadTask(context); 
        dt.download(fileurl, path, content.getFilename(), false, 
          DownloadTask.SYSTEM_DOWNLOADER); 


       } else { 

        FileOpener.open(context, file); 
       }