java - 如何将 mp3 文件从 url 下载到内部存储?
问题描述
我做了一个下载器,它可以工作,但问题是当我从手机下载时没有外部存储它不起作用
这是我的代码,它适用于外部存储:-
lateinit var downloadManager :DownloadManager
lateinit var request : DownloadManager.Request
downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
btndownload.setOnClickLisner{
request = DownloadManager.Request(Download_Uri)
request.setAllowedOverRoaming(false)
request.setTitle(songdownloadedname)
request.setDescription(null)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, songdownloadedname)
request.setVisibleInDownloadsUi(true)
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
downloadManager.enqueue(request)
}
我可以编辑什么以将其下载到内部存储而不是外部存储?
解决方案
您可以使用DownloadManager下载文件。你可以使用这个博客(不是我的博客)作为参考。以下源代码取自博客:
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("your mp3 url"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
推荐阅读
- salesforce - 如何在 Salesforce 中自定义 RemoteAccessAuthorizationPage?
- python - Python 检查网站状态是否正常,并返回响应时间
- javascript - 离子 SQLite ; 无法打开数据库
- logging - 如何使用 Terraform 11.14 启用 Azure Key Vault 日志记录?
- ios - 如何从 Firestore 返回数组中的数据?
- java - 如何启用单击按钮格式,并使用窗口增加文本大小
- python - 如何检查我的停用词删除算法是否有效?
- python - 遍历目录中的所有文件夹和文件
- angular - 如何通过 SPA 中的组件重定向到 payulatam
- discord.js - 如何修复“无法读取未定义的属性‘toLowerCase’”