gpt4 book ai didi

Android 自动安装 APK

转载 作者:太空狗 更新时间:2023-10-29 15:56:51 26 4
gpt4 key购买 nike

我有一个 webview,它基本上能够拦截各种链接、视频、apks、hrefs。

现在,我想要的是一旦我从 url 下载 APK,它就会自动安装:

这是 shouldOverrideUrlLoading() 代码的一部分:

        else if(url.endsWith(".apk")) 
{
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(final String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
}
});
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(url));
startActivity(intent);
return true;

如果我添加

intent.setDataAndType(Uri.parse(url), "application/vnd.android.package-archive");

比应用程序崩溃...

有什么想法吗?

编辑:我能够自动启动包的下载和安装(使用 sleep() ):

        else if(url.endsWith(".apk")) 
{
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(final String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
}
});
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(url));
startActivity(intent);
String fileName = Environment.getExternalStorageDirectory() + "/download/" + url.substring( url.lastIndexOf('/')+1, url.length() );
install(fileName);
return true;

并且,正如 vitamoe 所建议的那样:

protected void install(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");
startActivity(install);
}

但是,我无法捕获下载完成的确切时间,可能需要创建我自己的下载功能而不是使用浏览器的功能,有什么想法吗?

最佳答案

要在没有浏览器的情况下下载文件,请执行某项操作。像这样:

String apkurl = "http://your.url.apk";
InputStream is;
try {
URL url = new URL(apkurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
is = con.getInputStream();
} catch (SSLException e) {
// HTTPS can end in SSLException "Not trusted server certificate"
}

// Path and File where to download the APK
String path = Environment.getExternalStorageDirectory() + "/download/";
String fileName = apkurl.substring(apkurl.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs(); // creates the download directory if not exist
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);

// Save file from URL to download directory on external storage
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();

// finally, install the downloaded file
install(path + fileName);

关于Android 自动安装 APK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6109304/

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