我有一个聊天应用程序,让用户通过Firebase发送图像,视频等,当其他用户开始与Firebase数据库同步时,它首先将文件下载到本地存储,如其他应用程序(Whatapp,Messenger),然后从那里播放。
但我的问题是每当用户活动刷新所有文件时,一次又一次地下载并制作相同文件的重复副本。我怎样才能避免这种情况。
这是我的AsyncTask,我从Firebase存储中下载文件。
public class DownloadAttachment extends AsyncTask<Void, String, String> {
String DownloadUrl,fileName;
File file;
Context context;
ProgressBar progressBar;
public static final String TAG="###Download Attachment";
public DownloadAttachment(Context context, String downloadUrl, String fileName) {
DownloadUrl = downloadUrl;
this.fileName = fileName; //UUID.randomUUID().toString()
this.context=context;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected String doInBackground(Void... params) {
int count;
try {
File root = android.os.Environment.getExternalStorageDirectory();
Log.d(TAG,"DO IN BACKGROUND RUNNING");
File dir = new File(root.getAbsolutePath() + "/Downloaded Files/");
if (dir.exists() == false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d(TAG, "download begining");
Log.d(TAG, "download url:" + url);
Log.d(TAG, "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
//this will be useful so that you can show a typical 0-100% progress bar
int lengthOfFile=ucon.getContentLength();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayOutputStream baf = new ByteArrayOutputStream(5000);
int current = 0;
long total=0;
while ((current = bis.read()) != -1) {
baf.write((byte) current);
total=total+current;
//PUBLISH THE PROGRESS
//AFTER THIS onProgressUpdate will be called
publishProgress(""+(int)(total*100)/lengthOfFile);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
Log.d(TAG,"File Path "+file);
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
return file.toString();
}
}
我无法检查文件的名称因为我正在使用UUID生成文件的随机名称。
请指导我解决这个问题
答案 0 :(得分:1)
在我看来,您可以在本地sqlite数据库中维护一个下载文件的表,其中包含两列:
在下载任何文件之前,您应该使用TAG列检查其条目是否存在于表中。如果确实如此,则不要从firebase下载它,而是使用URI从设备中获取它。如果没有,则可以下载该文件并在表中为该文件插入一行。