我正在尝试在后台下载一些文件,因为我使用了下载管理器,并采用了以下方法:
/*** media download ***/
public long mediaDownload(ArrayList<DownloadedFile> arrayList, String foldPathName) {
long downloadReference = 0;
// Create request for android download manager
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
for (int i = 0; i < arrayList.size();i++){
DownloadManager.Request request = new DownloadManager.Request(arrayList.get(i).getUri());
request.setTitle("Data Download");
request.setDescription("New media");
//Set the local destination for the downloaded file to a path
//within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName, arrayList.get(i).getName());
File f = new File(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName + "/" + arrayList.get(i).getName());
Log.e("File:",f.toString());
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
}
return downloadReference;
}
我有一张图片和一个视频要下载以进行测试,当在资源管理器中检查下载的文件时,我发现有2个视频和2张图片,调试发现我发现onPostExecute方法被调用了两次,我不知道为什么。 这是我的onPostExecute方法:
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray region = null;
region = jsonObject.getJSONArray("regions");
Log.e("Regions:", String.valueOf(region.length()));
for (int i = 0; i < region.length(); i++) {
try {
JSONObject json_data = region.getJSONObject(i);
int height_view = Integer.parseInt(json_data.getString("height"));
int width_view = Integer.parseInt(json_data.getString("width"));
int left_view = Integer.parseInt(json_data.getString("left"));
int top_view = Integer.parseInt(json_data.getString("top"));
int right_view = Integer.parseInt(json_data.getString("right"));
int bottom_view = Integer.parseInt(json_data.getString("bottom"));
/**** Media in region ***/
JSONObject media = json_data.getJSONObject("media");
String type_media = media.getString("type");
url = media.getString("url");
name = media.getString("name");
uri = Uri.parse(url);
} catch (JSONException e) {
e.printStackTrace();
}
downloadedFiles.add(new DownloadedFile(name, uri));
}
Toast.makeText(MainActivity.this, "Layout Created with" + height + "x" + width, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Downloaded Files:",downloadedFiles.toString());
mediaDownload(downloadedFiles, folderName); // region media's download
}
在我的logcat上,我看到我的arrayList有2个元素,但是显示了两次,这意味着文件被下移了两次,因此onPostExecute方法被调用了两次,谢谢帮助。
答案 0 :(得分:0)
我花了很多时间调试所有代码后才发现,创建活动时它改变了屏幕方向,因此它创建了第二个实例,所以我的AsyncTask被调用了两次,这就是为什么我以为onPosteExecute被调用了两次,谢谢给所有想帮助的人。