我有一个下载文件的类,目的是将其存储在用户的Downloads
文件夹中。我声明了正确的权限。我可以看到该文件正在根据此类发送回调用活动的广播进行下载。但是,完成此操作后,文件似乎未保存在任何位置,当然不在Downloads
文件夹中。
任何人都可以看到为什么我无法访问此文件夹和/或为什么它无法正确保存?谢谢。
public class FileDownloader extends IntentService {
public static final String FILENAME = "filename";
public static final String FULLPATH = "fullpath";
public static final String FILESIZE = "filesize";
public static final String RECEIVER = "receiver";
public static String broadcastReceiver;
public FileDownloader() {
super("DownloadFile");
}
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(FULLPATH);
String filename = intent.getStringExtra(FILENAME);
int filesize = intent.getIntExtra(FILESIZE, 1);
broadcastReceiver = intent.getStringExtra(RECEIVER);
// THIS IS WHERE I AM ATTEMPTING TO CREATE A PATH TO THE DOWNLOADS FOLDER
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
if (outputFile.exists()) {
outputFile.delete();
}
downloadFile(urlPath, outputFile, filesize);
}
private void downloadFile(String urlPath, File outputFile, int filesize) {
Intent intent = new Intent(broadcastReceiver);
URL url;
try {
url = new URL(urlPath);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
int bytes_downloaded = 0;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
bytes_downloaded += length;
final int progress = (int) ((bytes_downloaded * 100l) / filesize);
String message = Integer.toString(progress) + "%";
intent.putExtra("message", message);
LocalBroadcastManager.getInstance(TexasApp.getContext()).sendBroadcast(intent);
}
intent.putExtra("message", "done");
LocalBroadcastManager.getInstance(TexasApp.getContext()).sendBroadcast(intent);
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以防万一,这是我的清单:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
最后一件事:我知道我正在正确浏览Android 6权限,因此请假设这与此问题无关。
谢谢!
答案 0 :(得分:0)
要使您的文件显示在文件管理器中(例如,在您的开发计算机上),您需要安排将其编入MediaStore
的索引。这最终会发生,但可能需要几个小时。要更快地对其编制索引,请使用MediaScannerConnection
及其scanFile()
方法。