如何从我的 Android 应用程序中的 Web 服务器下载一些文件,并将它们存储在根位置的应用程序文件夹中或内部/外部内存中的私有文件夹中。
我可以下载文件,但我不能将它们存储在私人文件夹中。
我已经写了我的下载管理器,但我在显示通知(如下载百分比)方面遇到了一些问题。
我不确定你想用“私人文件夹”做什么......但这是我下载带有进度回调的文件的方式:
public class Downloader extends Thread implements Runnable{
private String url;
private String path;
private DownloaderCallback listener=null;
public Downloader(String path, String url){
this.path=path;
this.url=url;
}
public void run(){
try {
URL url = new URL(this.url);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
String filename = urlConnection.getHeaderField("Content-Disposition");
// your filename should be in this header... adapt the next line for your case
filename = filename.substring(filename.indexOf("filename")+10, filename.length()-2);
int total = urlConnection.getContentLength();
int count;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path+"/"+filename);
byte data[] = new byte[4096];
long current = 0;
while ((count = input.read(data)) != -1) {
current += count;
if(listener!=null){
listener.onProgress((int) ((current*100)/total));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
if(listener!=null){
listener.onFinish();
}
} catch (Exception e) {
if(listener!=null)
listener.onError(e.getMessage());
}
}
public void setDownloaderCallback(DownloaderCallback listener){
this.listener=listener;
}
public interface DownloaderCallback{
void onProgress(int progress);
void onFinish();
void onError(String message);
}
}
使用方法:
Downloader dl = new Downloader("/path/to/save/file", "http://server.com/download");
dl.setDownloaderCallback(new DownloaderCallback{
@Override
void onProgress(int progress){
}
@Override
void onFinish(){
}
@Override
void onError(String message){
}
});
dl.start();
对于您的私人模式,您必须加密文件并将其存储在 SD 卡/内部。参考这个
如果你想在外部存储中下载文件,你可以使用。
String storagePath = Environment.getExternalStorageDirectory().getPath()+ "/Directory_name/";
//Log.d("Strorgae in view",""+storagePath);
File f = new File(storagePath);
if (!f.exists()) {
f.mkdirs();
}
//storagePath.mkdirs();
String pathname = f.toString();
if (!f.exists()) {
f.mkdirs();
}
//Log.d("Storage ",""+pathname);
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse(image);
checkImage(uri.getLastPathSegment());
if (!downloaded) {
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/Directory_name", uri.getLastPathSegment());
Long referese = dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_SHORT).show();
}
要使用 DownloadManager 下载文件并将其保存到您的应用程序的私有存储目录,您可以在
null
方法中将 setDestinationInExternalFilesDir
作为目录参数传递。这将确保文件被下载到您应用程序的私有文件存储空间,其他应用程序或用户无法访问该文件存储空间。
例子
val request = DownloadManager.Request(Uri.parse(fileUrl))
.setDestinationInExternalFilesDir(context, null, fileName)
完整的例子
这是一个将文件下载到您应用程序的私有文件夹的函数的完整示例,只需将上下文、fileUrl、fileName 和 fileDescription 传递给它,您可以根据需要修改它:
private fun downloadFile(
context: Context,
fileUrl: String,
fileName: String,
fileDescription: String
) {
val request = DownloadManager.Request(Uri.parse(fileUrl))
.setTitle(fileName)
.setDescription(fileDescription)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalFilesDir(context, null, "$fileName.${getFileExtension(fileUrl)}")
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager
downloadManager?.enqueue(request)
}
此函数用于获取文件扩展名以使其正常工作:
private fun getFileExtension(fileUrl: String): String {
return MimeTypeMap.getFileExtensionFromUrl(fileUrl)
}