Android App checks for new versions automatically download, install and upgrade versions compatible Android7.0 above and below

Preface

After completion of the development of a number of companies may not go to App App store shelves, but later things also need regular maintenance update, we will choose to publish packaged apk to your server, and then build a table in the database version number , then the rest is up to you to develop an android, android version of himself to achieve detection update, due android comes DownloadManager you can achieve download functions, using them will be very simple, do not write a lot of code, and other related downloads but in downloading some in the notification bar notification, then the user to manually click to install, some downloaded himself into the installed state, the user only needs to confirm the installation on it, but due to the automatic number of high version of the system and lower versions different installation.

Android 7.0 or lower, after downloading automatically pop installation interface, prompts to install;

Android 7.0 and above, after the download is not automatically pop installation interface;

text

Download , Util tools, a static method and a top downLoadApk (), and comparing the version number of the request will be omitted here.

/**
 * 更新下载apk
 * @param context  上下文对象
 * @param title    程序的名字
 * @param url       下载的url地址
 *
 */

public static long downLoadApk(Context context,String title,String url){

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS,"ausee.apk");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置 Notification 信息
        request.setTitle(title);
        request.setDescription("下载完成后请点击打开");
        request.setVisibleInDownloadsUi(true);
        request.allowScanningByMediaScanner();
        request.setMimeType("application/vnd.android.package-archive");

        // 实例化DownloadManager 对象
        DownloadManager downloadManager = (DownloadManager) MyApp.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
        final long refrence = downloadManager.enqueue(request);

        return refrence;
}
The static method above can be achieved downloaded, the url pass over to OK; Here's to deal with the rest, we note that the above method returns a value of type long ,

When we call this method of activity, to get the return value, and then build a radio receiver activity inside, because the return value is above DownloadManager download a download after the return of id, comes with each download task will returns a unique id, and will send a broadcast, here I define a method in which activity: listener (id), and built a radio receiver; as follows:

private void listener(final long Id) {
    // 注册广播监听系统的下载完成事件。
    IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
            // 这里是通过下面这个方法获取下载的id,
            long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            // 这里把传递的id和广播中获取的id进行对比是不是我们下载apk的那个id,如果是的话,就开始获取这个下载的路径
            if (ID == Id) {

                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(Id);

                Cursor cursor = manager.query(query);
                if (cursor.moveToFirst()){
                    // 获取文件下载路径
                    String fileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                    // 如果文件名不为空,说明文件已存在,则进行自动安装apk
                    if (fileName != null){

                        openAPK(fileName);

                    }
                }
                cursor.close();
            }
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);
}

Installation, automatic installation window pop

/**
 * 安装apk
 * @param fileSavePath
 */
private void openAPK(String fileSavePath){
    File file=new File(Uri.parse(fileSavePath).getPath());
    String filePath = file.getAbsolutePath();
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
        // 生成文件的uri,,
        // 注意 下面参数com.ausee.fileprovider 为apk的包名加上.fileprovider,
        data = FileProvider.getUriForFile(LoginActivity.this, "com.ausee.fileprovider", new File(filePath));
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
    } else {
        data = Uri.fromFile(file);
    }

    intent.setDataAndType(data, "application/vnd.android.package-archive");
    startActivity(intent);
}

fileprovider file

The above basic on it, but above that parameter com.ausee.fileprovider, this should be noted, the following configuration.
In the first new project res files in a folder named xml; after a new xml file: file_paths.xml; 
Xml content as follows:
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="name" path="."/>
</paths>

Manifest file

After written here, the following configuration in manifest a provider label inside: so you can write:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.ausee.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

A close look at the above android: authorities = "com.ausee.fileprovider" (com.ausee for your own package name), and the content of that argument in front of the same, right? Because here, the content here is so filled, plus a fileprovider package name on it, and then in the meta-data inside the configuration xml file just opened configuration can come in!

Finish! ! !


Original link: https: //blog.csdn.net/I123456789T/article/details/81584352

Published 106 original articles · won praise 65 · views 220 000 +

Guess you like

Origin blog.csdn.net/xialong_927/article/details/104003231