如何在我的Android应用程序中从我的Web服务器下载一些文件,并将它们存储在根位置的应用程序文件夹中或内部/外部存储器的私人文件夹中。
我可以下载文件但我无法将它们存储在私人文件夹中。
我已经编写了我的下载管理器,并且在使用它时显示通知(例如下载百分比)方面存在一些问题。
答案 0 :(得分:3)
我不确定你想要做什么"私人文件夹" ...但这是我用进度回调下载文件的方式:
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();
答案 1 :(得分:1)
如果您希望将下载的文件保存在外部存储设备中,可以使用。
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();
}
答案 2 :(得分:0)
对于您的私人模式,您必须加密文件并将其存储在SD卡/内部。参考this