正如标题所述,我有一个下载管理器,它可以工作,但仅有时。这很奇怪,我找不到模式。我有一个按钮,当单击该按钮时,它会将请求发送到服务器,该服务器返回要下载的文件,然后有时会下载,有时则不会。我看不到任何模式,电话或服务器也没有收到任何错误。
这对我的应用程序不利,因为我需要知道它已成功下载,所以我要么需要找出有时为何它不起作用的原因,要么需要找到一种在下载失败时运行功能的方法。这是我用来下载文件的代码:
GlobalVariables globalVariables = new GlobalVariables();
String url = globalVariables.getIPAddress() + "downloadsong/" + Integer.toString(songId) + "/";
SharedPreferences sharedPreferences = getSharedPreferences("StoredValues", MODE_PRIVATE);
String token = sharedPreferences.getString("token", "null");
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle("Downloading");
request.setDescription("Downloading new titles");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "" + songId + ".mp3");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.addRequestHeader("Authorization", "Token " + token);
request.allowScanningByMediaScanner();
request.setAllowedOverMetered(true);
request.setAllowedOverRoaming(true);
long downloadReference = downloadManager.enqueue(request);
if (downloadReference != 0) {
Toast.makeText(getApplicationContext(), "download started", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "no download started", Toast.LENGTH_SHORT).show();
}
感谢您的帮助或见识。谢谢!
您必须注册一个广播接收者
public static int validDownload(Context context, long downloadId) {
//Verify if download is a success
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId));
try {
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
return 0; //Download is valid, celebrate
} else {
return c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
}
}
} finally {
c.close();
}
return -1;
}
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadID == id) {
validDownload(this, id);
}
}
};
并在您的活动的onCreate方法中注册ACTION_DOWNLOAD_COMPLETE。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}