直接安装最新的apk而不用打开其他的程序的实现

本文介绍了一种在不使用浏览器的情况下直接下载并安装最新APK文件的方法,包括下载流程、权限添加及关键代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原问题来自于CSDN问答频道,更多解决方案见:http://ask.csdn.net/questions/1384

原问题描述:

我在web服务器的后台每24小时检查一次应用程序版本。
如果更新可用,它会提示用户下载新的apk。

Uri uri = Uri.parse(downloadURL);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);


上面的代码打开用户的浏览器,并开始下载。
我不想打开浏览器,但是需要下载apk文件文件。 或者直接安装最新的apk而不用打开其他的程序。如何实现呢?

解决方案:

首先,你需要下载apk文件

String extStorageDirectory =        Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, "APPS");
        folder.mkdir();
        File file = new File(folder, "AnyName."+"apk");
        try {
                file.createNewFile();
        } catch (IOException e1) {
                e1.printStackTrace();
        }
        /**
         * APKURL is your apk file url(server url)
         */
         DownloadFile("APKURL", file);


DownloadFile函数是

public  void DownloadFile(String fileURL, File directory) {
       try {

            FileOutputStream f = new FileOutputStream(directory);
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            //c.setDoOutput(true);
            c.connect();
            InputStream in = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                    f.write(buffer, 0, len1);
            }
            f.close();
    } catch (Exception e) {
        System.out.println("exception in DownloadFile: --------"+e.toString());
            e.printStackTrace();
    }


下载apk文件后,添加下面的代码

Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new   File(Environment.getExternalStorageDirectory() + "/APPS/" + "AnyName.apk")), "application/vnd.android.package-archive");
            startActivity(intent);


在 manifest文件中添加权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值