2016-06-15 13 views
1

Ich benutze Volley, um Datei mit einer asynchronen Task zu downloaden. Ich möchte den Fortschritt mit Prozent zeigen, während die Datei heruntergeladen wird. Das Problem ist jedoch, dass die asynchrone Aufgabe gestartet wird, wenn die Antwort gekommen ist. Ich kann keine Möglichkeit finden, den Fortschritt zu verfolgen, bevor die endgültige Antwort vollständig eingetroffen ist. Ich habe keine Methode in JsonRequest gefunden, die dafür verwendet werden kann.Zeigen Fortschrittsbalken mit Prozent beim Herunterladen von Datei mit Volley in Android

Unten ist die OnResponse-Methode der Anfrageklasse, die JsonRequest erweitert, die ich verwende.

protected Response<T> parseNetworkResponse(NetworkResponse response) { 
if (response.statusCode >= 200 && response.statusCode <= 299) { 
       // If the status is correct, we return a success but with a null object, because the server didn't return anything 
       return Response.success(null, HttpHeaderParser.parseCacheHeaders(response)); 
      } 
     else { 
      try { 
       if (downloadFlag) { 
        DownloadFileAsyncTask downloadFileAsyncTask = new DownloadFileAsyncTask(mContext, fileNameAndExtn,mNotifyManager,mBuilder,mDownloadNotificationUniqueId); 
        downloadFileAsyncTask.execute(response.data); 
       } else if (isResponseByteArr) { 
        return (Response<T>) Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response)); 
       } else { 
        String json = null; 
        if (isGzipped(response)) { 
         json = gzipDecompress(response.data); 
        } else { 
         json = new String(response.data,HttpHeaderParser.parseCharset(response.headers)); 
        } 

        T parsedObject = gson.fromJson(json, clazz); 
        return Response.success(parsedObject, HttpHeaderParser.parseCacheHeaders(response)); 
       } 
      } catch (UnsupportedEncodingException e) { 
       return Response.error(new ParseError(e)); 
      } catch (JsonSyntaxException e) { 
       return Response.error(new ParseError(e)); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return null; 
    } 

DownFileAsyncTask ist wie folgt: Paket com.android.webframework.webservice;

import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Build; 
import android.os.Environment; 
import android.support.v4.app.NotificationCompat; 
import android.webkit.MimeTypeMap; 
import android.widget.Toast; 

import com.android.applogger.AppLogger; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 

public class DownloadFileAsyncTask extends AsyncTask<byte[], Integer, String> { 
    private String fileNameAndExtn; 
    private Context mContext; 
    private NotificationManager mNotifyManager; 
    private NotificationCompat.Builder mBuilder; 
    private int mUniqueId; 

    public DownloadFileAsyncTask(Context context, String fileNameAndExtn, NotificationManager notifyManager, NotificationCompat.Builder builder, int uniqueId) { 
     this.fileNameAndExtn = fileNameAndExtn; 
     this.mContext = context; 
     this.mNotifyManager = notifyManager; 
     this.mBuilder = builder; 
     this.mUniqueId = uniqueId; 
    } 

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

    String MEDIA_MOUNTED = "mounted"; 

    @Override 
    protected String doInBackground(byte[]... bytes) { 
     File file = null; 
     int copyCount = 0; 
     String filePath = ""; 
     String diskState = Environment.getExternalStorageState(); 
     if (diskState.equalsIgnoreCase(MEDIA_MOUNTED)) { 
      File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 
      file = new File(sd, fileNameAndExtn); 

      String fileName = ""; 
      String fileExtn; 

      String fileNameToSave = fileNameAndExtn; 

      while (file.exists()) { 

       copyCount++; 

       String[] parts = fileNameAndExtn.split("[.]"); 

       if (parts[0] != null) 
        fileName = parts[0]; 

       fileName += "-" + copyCount; 

       fileNameToSave = fileName + "." + parts[1]; 

       file = new File(sd, fileNameToSave); 

      } 

      fileNameAndExtn = fileNameToSave; 

      /*if (file.exists()) { 

       file.delete(); 
      }*/ 

      try { 
       FileOutputStream fos = new FileOutputStream(file.getPath()); 
       fos.write(bytes[0]); 
       fos.close(); 
      } catch (IOException e) { 
       AppLogger.e("file", "Exception in photoCallback", e); 
      } 
      AppLogger.e("file Download completed", "***************"); 

      Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
      intent.setData(Uri.fromFile(file)); 
      mContext.sendBroadcast(intent); 

      filePath = file.getAbsolutePath(); 
     } else { 
      Toast.makeText(mContext, "The external disk is not mounted.", Toast.LENGTH_SHORT).show(); 
     } 
     return (filePath); 
    } 

    @Override 
    protected void onPostExecute(String filePath) { 
     super.onPostExecute(filePath); 
     if (fileNameAndExtn != null && !fileNameAndExtn.equalsIgnoreCase("")) { 
//   Toast.makeText(mContext, "File downloaded in Downloads/" + fileNameAndExtn, Toast.LENGTH_LONG).show(); 
      Toast.makeText(mContext, fileNameAndExtn + " downloaded successfully", Toast.LENGTH_LONG).show(); 
      mBuilder.setProgress(100, 100, false); 
      Intent intent = getPendingIntent(mContext, filePath); 
      mBuilder.setContentTitle(fileNameAndExtn) 
        .setAutoCancel(true) 
        .setContentText("Download complete"); 
      PendingIntent pendingIntent = null; 
      if (intent != null) { 
       pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 
      } 

      if (pendingIntent != null) { 
       mBuilder.setContentIntent(pendingIntent).setProgress(0, 0, false); 
      } 

      mNotifyManager.notify(mUniqueId, mBuilder.build()); 

     } 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values) { 
     mBuilder.setProgress(100, values[0], false); 
     mNotifyManager.notify(mUniqueId, mBuilder.build()); 
     super.onProgressUpdate(values); 
    } 

    public Intent getPendingIntent(Context context, String filePath) { 

     Intent intent = new Intent(Intent.ACTION_VIEW); 
//    File file = new File("YOUR_SONG_URI"); // set your audio path 
     File file = new File(filePath); 
     intent.setDataAndType(Uri.fromFile(file), getMimeType(filePath)); 

     if (intent.resolveActivityInfo(context.getApplicationContext(). 
       getPackageManager(), 0) != null) { 
//   context.getApplicationContext().startActivity(intent); 
      return intent; 
     } else { 
      Toast.makeText(context, "File not present or Explorer app not present.", 
        Toast.LENGTH_LONG).show(); 
      return null; 
      // if you reach this place, it means there is no any file 
      // explorer app installed on your device 
     } 
    } 

    public static String getMimeType(String url) { 
     String filePathWithoutWhiteSpace = url.replaceAll("\\s", "%20"); 
     String type = null; 
     String extension = MimeTypeMap.getFileExtensionFromUrl(filePathWithoutWhiteSpace); 
     if (extension != null) { 
      type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase()); 
     } 
     return type; 
    } 
} 

Antwort

0

Ich löste dieses Problem durch Erstellen der Benachrichtigung, sobald der Benutzer auf Download klickt und dann die asynchrone Aufgabe benachrichtigt, nachdem der Download abgeschlossen ist, aber ich konnte den genauen Fortschritt während des Downloads nicht zeigen.