私はvolleyを使用して非同期タスクを使用してファイルをダウンロードしています。ファイルのダウンロード中に進行状況をパーセンテージで表示します。しかし、問題は、応答が来たときに非同期タスクが開始されることです。最終的な対応が完全に来る前に進捗状況を追跡する方法は見つけられません。 JsonRequestでこれに使用できるメソッドが見つかりませんでした。アンドロイドでVolleyを使用してファイルをダウンロードしているときの進行状況バーを表示
以下は、私が使用しているJsonRequestを拡張した要求クラスのonResponseメソッドです。次のようにDownFileAsyncTaskがある
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;
}
: パッケージ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;
}
}