Android下载apk并自动安装(兼容Android7.0)

1、开启服务下载新版本

View.OnClickListener checkVersion = new View.OnClickListener () {
        @Override
        public void onClick (View v) {
            Intent startServiceIntent = new Intent (ActivityAboutUs.this, UpdateServer.class);
            Bundle bundle = new Bundle ();
            bundle.putString ("param", UpdateServer.UPDATE);
            bundle.putString ("url", mUrl);
            startServiceIntent.putExtras (bundle);
            ActivityAboutUs.this.startService (startServiceIntent);
        }
    };

2、使用downloadmanager进行下载 ,下载完成后会发送“ACTION_DOWNLOAD_COMPLETE”通知

public class UpdateServer extends IntentService {
    public static final String UPDATE = "UPATE";
    public static final String DOWN_APK = "DOAN_APK";
    private static final String TAG = "CheckUpdateServer";
    private String fileName = "shop";
    private String downloadUpdateApkFilePath;
    public UpdateServer () {
        super ("CheckUpdateServer");
    }
    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {
        if (null != intent) {
            String action = intent.getExtras ().getString ("param");
            if (action.equals (UPDATE)) {
                String url = intent.getExtras ().getString ("url");
                downLoadApk (url);
            } 
        }
        return super.onStartCommand (intent, flags, startId);
    }

 //下载新版本
    private void downLoadApk (String url) {
        if (TextUtils.isEmpty (url))
            return;
        DownloadManager manager = (DownloadManager) getSystemService (DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request (Uri.parse (url));

        request.setAllowedNetworkTypes (DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setNotificationVisibility (DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle ("下载");
        request.setDescription ("@shopguide");
        request.setAllowedOverRoaming (false);
        request.setMimeType("application/vnd.android.package-archive");
        request.setDestinationInExternalPublicDir ( Environment.DIRECTORY_DOWNLOADS, "shopguide.apk");      
        long downId = manager.enqueue (request);
        ToastUtils.showShort (this, "正在为您下载最新版本");
    }
}

3、注册 接收“ACTION_DOWNLOAD_COMPLETE”通知

//注册广播
 <receiver
            android:name="server.DownLoadCompleteReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

//广播
if (intent.getAction ().equals (DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            installApk (context);
}

//安装应用
private void installApk (Context context) {
        File file = new File (
                Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS), "shopguide.apk");
    
        String[] command = {"chmod", "777", file.toString ()};
        ProcessBuilder builder = new ProcessBuilder (command);
        try {
            builder.start ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        Intent intent = new Intent (Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//android 7.0
            Uri apkUri =
                    FileProvider.getUriForFile (context, context.getPackageName () + ".provider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType (apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType (Uri.fromFile (file), "application/vnd.android.package-archive");
        }
        context.startActivity (intent);
    }

android 7.0之后,采用FileProvider进行解析 安装,需要进行相关配置,配置如下

1)清单文件中添加如下节点

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"  //主机名
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/update_files" />
        </provider>

2)res--》xml中生成update_files文件

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <external-path
            name="download"
            path=""/>
    </paths>
</resources>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。