gpt4 book ai didi

java - Android:不是文件 URI:下载 .apk 文件时

转载 作者:行者123 更新时间:2023-11-29 06:53:03 26 4
gpt4 key购买 nike

我想下载 .apk 文件并安装它。当我不使用 FileProvider 时,一切顺利,但是当我使用 FileProvider 从文件创建 uri 时,我遇到了 IllegalArgumentException:不是文件 URI:content://pl.rasztabiga.klasa1a.provider/external_storage_root/klasa1a。 apk上线

final long downloadId = manager.enqueue(request);

我尝试了 stackoverflow 中的所有方法,但没有任何帮助。这是我的代码:

File file = new File(Environment.getExternalStorageDirectory(), "klasa1a.apk");
final Uri uri = FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", file);

//Delete update file if exists
//File file = new File(destination);
if (file.exists())
file.delete();

//get url of app on server
String url = "http://rasztabiga.ct8.pl/klasa1a.apk";

//set downloadmanager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading new version");
request.setTitle(MainActivity.this.getString(R.string.app_name));

//set destination
request.setDestinationUri(uri);

// get download service and enqueue file
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);

//set BroadcastReceiver to install app when .apk is downloaded
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
startActivity(install);

unregisterReceiver(this);
finish();
}
};
//register receiver for when .apk download is compete
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

最佳答案

ACTION_VIEWACTION_INSTALL_PACKAGE 仅支持自 Android 7.0 起的 content 方案。在此之前,您别无选择,只能使用 file。所以,改变:

final Uri uri = FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", file);

到:

final Uri uri = (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) ?
FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", file) :
Uri.fromFile(file);

关于java - Android:不是文件 URI:下载 .apk 文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com