Android下載apk并自動(dòng)安裝(兼容Android7.0)

1、開啟服務(wù)下載新版本

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進(jìn)行下載 ,下載完成后會(huì)發(fā)送“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、注冊(cè) 接收“ACTION_DOWNLOAD_COMPLETE”通知

//注冊(cè)廣播
 <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);
}

//安裝應(yīng)用
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環(huán)境下啟動(dòng)Activity,設(shè)置下面的標(biāo)簽
        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);
            //添加這一句表示對(duì)目標(biāo)應(yīng)用臨時(shí)授權(quán)該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進(jìn)行解析 安裝,需要進(jìn)行相關(guān)配置,配置如下

1)清單文件中添加如下節(jié)點(diǎn)

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"  //主機(jī)名
            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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容