Android app內更新,兼容7.0

之前項目有需求做app內更新,試了很多都不行,最後自己結合網上找到的資料,自己寫了一個工具類,兼容Android7.0,有問題的話歡迎留言。二話不說直接上代碼吧

/**
 * 2018-01-09 haoshiwei
 * app內部更新的工具類
 * 兼容7.0
 */
public class DownloadUtils {
    //下載器
    private DownloadManager downloadManager;
    //上下文
    private Context mContext;
    //下載的ID
    private long downloadId;
    public DownloadUtils(Context context){
        this.mContext = context;
    }

    //下載apk
    public void downloadAPK(String url, String name) {

        //創建下載任務
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //移動網絡情況下是否允許漫遊
        request.setAllowedOverRoaming(false);

        //在通知欄中顯示,默認就是顯示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("狐小狸");
        request.setDescription("Apk Downloading");
        request.setVisibleInDownloadsUi(true);

        //設置下載的路徑
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS , name);

       //獲取DownloadManager
        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //將下載請求加入下載隊列,加入下載隊列後會給該任務返回一個long型的id,通過該id可以取消任務,重啓任務、獲取下載的文件等等
        downloadId = downloadManager.enqueue(request);

        //註冊廣播接收者,監聽下載狀態
        mContext.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    //廣播監聽下載的各個狀態
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };


    //檢查下載狀態
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通過下載的id查找
        query.setFilterById(downloadId);
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                 //下載暫停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下載延遲
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下載
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下載完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下載完成安裝APK
                    installAPK();
                    break;
                //下載失敗
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(mContext, "下載失敗", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        c.close();
    }


//下載到本地後執行安裝
private void installAPK() {
    //獲取下載文件的Uri
    Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadId);
    if (downloadFileUri != null) {
        Intent intent= new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
        mContext.unregisterReceiver(receiver);
    }
}
}
這裏使用了Android自帶的downloadManager,但是有一個 問題就是在Android7.0以上的手機不兼容。

/**
 * 7.0兼容
 */
private void installAPK() {
    File apkFile =
            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "huxiaoli.apk");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (Build.VERSION.SDK_INT >= 24) {
        Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", apkFile);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    } else {
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    }
    mContext.startActivity(intent);
}
這裏我們在7.0以上的手機上使用file.provider要在manifest文件裏面配置一下

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="你的包名.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>
在drawable目錄下創建xml包下面創建provider_paths文件

<?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>
   這樣就大功告成了,有問題的話歡迎留言

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章