Android 自动安装 APK

发布于 2024-11-09 13:04:44 字数 1874 浏览 1 评论 0原文

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

现在,我想要的是,一旦我从网址下载 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);
}

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

I have a webview which basically is capable of intercepting all sorts of links, video, apks, hrefs.

Now, what I want is once I download an APK from a url, that it'll be auto installed:

This is part of the shouldOverrideUrlLoading() code:

        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;

If I add

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

Than the application crashes...

Any ideas as to what to do?

EDIT: I was able to initiate a download and an installation of the package automatically (using a 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;

and, as vitamoe suggested:

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);
}

However, I'm unable to capture the exact time that the download is finished, might need to create my own download function and not use the browser's one, any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雪落纷纷 2024-11-16 13:04:44

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

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);

To download a file without the browser do sth. like this:

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);
孤独患者 2024-11-16 13:04:44

你可以临时。将其下载到 SD 卡,使用包管理器安装,然后再次删除。

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);
}

You can temp. download it to an sd card, install it with the package manager and then remove it again.

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);
}
等往事风中吹 2024-11-16 13:04:44

由于 Android 安全模型,无法自动安装 Apk 文件。

Due to Android security model it is not possible to install Apk file automatically.

記憶穿過時間隧道 2024-11-16 13:04:44

为什么不尝试使用下载管理器和在下载完成时拦截的广播接收器?下载管理器适用于 ANDROID 2.3+,

示例如下:

myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
            Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
            if (url.endsWith(".apk")) {
                Uri source = Uri.parse(url);
                // Make a new request pointing to the .apk url
                DownloadManager.Request request = new DownloadManager.Request(source);
                // appears the same in Notification bar while downloading
                request.setDescription("Description for the DownloadManager Bar");
                request.setTitle("YourApp.apk");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
                // save the file in the "Downloads" folder of SDCARD
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
                // get download service and enqueue file
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            }
            else if(url.endsWith(".mp3")) {
                // if the link points to an .mp3 resource do something else
            }
            // if there is a link to anything else than .apk or .mp3 load the URL in the webview
            else view.loadUrl(url);
            return true;                
    }
});

完整答案:用户 bboydflo
将文件下载到Android WebView(代码中没有下载事件或 HTTPClient)

下载完成时拦截的广播接收器

    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            // toast here - download complete 
        }
    }
};

记住在主活动中注册接收器,如下所示:

registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

why not trying with a download manage and a broadcast receiver that would intercept when download is finished? Download manager works for ANDROID 2.3+ though

Example here:

myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
            Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
            if (url.endsWith(".apk")) {
                Uri source = Uri.parse(url);
                // Make a new request pointing to the .apk url
                DownloadManager.Request request = new DownloadManager.Request(source);
                // appears the same in Notification bar while downloading
                request.setDescription("Description for the DownloadManager Bar");
                request.setTitle("YourApp.apk");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
                // save the file in the "Downloads" folder of SDCARD
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
                // get download service and enqueue file
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            }
            else if(url.endsWith(".mp3")) {
                // if the link points to an .mp3 resource do something else
            }
            // if there is a link to anything else than .apk or .mp3 load the URL in the webview
            else view.loadUrl(url);
            return true;                
    }
});

Full answer here: user bboydflo
Downloading a file to Android WebView (without the download event or HTTPClient in the code)

Broadcast receiver to intercept when download has finished

    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            // toast here - download complete 
        }
    }
};

remember to recister recevier in the main activity like this:

registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文