APP实现更新功能(带效果图)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

前言

**本篇博客主要讲述Android在app内部安装其他app或者更新本app

一、主页面布局代码

//这里面有一些自定义背景,可以直接去掉
//这个地方只写了一个按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".func.APP_Update_Activity">

    <Button
        android:textColor="#fff"
        android:text="更新"
        android:textSize="@dimen/public_20_dp"
        android:layout_marginTop="@dimen/public_100_dp"
        android:background="@drawable/shape_login6"
        android:id="@+id/jiance"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

二、主页面代码,一定要注意DownloadNewApk()这个方法里面的下载连接换成你自己的,不然会出现解析包异常

package com.ami.myzonghe_demo.func;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ami.myzonghe_demo.BuildConfig;
import com.ami.myzonghe_demo.R;
import com.ami.myzonghe_demo.mvp.Constant22;
import com.ami.myzonghe_demo.mvp.NetUtil22;
import com.ami.myzonghe_demo.mvp.base.BaseActivity22;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class APP_Update_Activity extends BaseActivity22 {
    @BindView(R.id.jiance)
    Button jiance;

    @Override
    protected int Layout() {
        return R.layout.activity_app_update;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        jiance.setOnClickListener(v -> {
            //这个地方检测版本号
            //版本号小于更新的版本号就更新
            //这里直接更新
            showUpDateDialog();
        });
    }

    private void showUpDateDialog() {
        //Dialog弹窗,updateDialog.setCancelable(false);   设置为强制更新setCancelable状态未false的时候弹框不可以取消
        Dialog updateDialog = new Dialog(APP_Update_Activity.this, R.style.custom_dialog);
        updateDialog.setOwnerActivity((Activity) APP_Update_Activity.this);
        //获取子布局以及获取id
        View contentView = LayoutInflater.from(APP_Update_Activity.this).inflate(R.layout.app_upgrade_dialog, null);

        Button confirmBtn = contentView.findViewById(R.id.btn_confirm);
        TextView versionName = contentView.findViewById(R.id.tv_version_name);

        versionName.setText("版本过低需要更新到最新版本:"  );

        //确定按钮点击事件,点击开始下载qpk
        confirmBtn.setOnClickListener(v -> {
                    updateDialog.dismiss();
                    //得到安装包的下载路径
                    String filePath = getInstallFilePath();
                    Log.e("aaa","filePath"+filePath);
                    File installFile = new File(filePath);
                    //判断apk是否存在,若存在则直接安装,不存在下载安装
                    if (installFile.exists()) {
                        //在已经下载好文件的情况下,根据下载路径直接安装
                        installApp(filePath);
                    } else {
                        //发现在安装包下载路径没有文件,需要下载
                        DownloadNewApk();
                    }
                }
        );

        updateDialog.setContentView(contentView);
        updateDialog.setCancelable(false);
        updateDialog.setCanceledOnTouchOutside(false);
        updateDialog.show();
    }


    private String getInstallFilePath() {
        String filePackagePath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/";
        String fileName = "1.8.1" + ".apk";
        String installFilePath = filePackagePath + fileName;
        return installFilePath;
    }


    //普通安装
    private void installApp(String apkPath) {
        try {
            //版本在7.0以上是不能直接通过uri访问的
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                File file = (new File(apkPath));
                Log.e("aaa","已经安装的文件路径:"+file.getPath());
                Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", file);

                Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                intent.setData(contentUri);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
            } else {
                Log.e("aaa","apkPath:"+apkPath);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载新apk
     */
    private void DownloadNewApk() {
        File installFile = new File(getInstallFilePath());
        DownloadManager downloadManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        //这个地方放你自己的apk下载地址
        Uri uri = Uri.parse("http://down.这个地方放你自己的apk下载地址");
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationUri(Uri.fromFile(installFile));
        long downloadId = downloadManager.enqueue(request);
        //下载监听器
        registerDownLoadFinishReceiver(downloadId);

        //下载进度条弹框
        showDownloadDialog(downloadId);
    }

    private void registerDownLoadFinishReceiver(long downloadId) {
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (downloadId == reference) {
                    // 下载完成后取消监听
                    context.unregisterReceiver(this);
                    // 安装应用
                    installApp(getInstallFilePath());
                }
            }
        };
        this.registerReceiver(receiver, filter);
    }


    private void showDownloadDialog(long downloadId) {
        Dialog dialog = new Dialog(this, R.style.custom_dialog);
        dialog.setOwnerActivity((Activity) this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.app_download_dialog, null);

        ProgressBar progressBar = contentView.findViewById(R.id.pb_download_progress);

        dialog.setContentView(contentView);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        new Thread(new Runnable() {

            @Override
            public void run() {

                boolean downloading = true;

                while (downloading) {

                    DownloadManager.Query q = new DownloadManager.Query();
                    q.setFilterById(downloadId);

                    Cursor cursor = ((DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE)).query(q);
                    cursor.moveToFirst();
                    int bytes_downloaded = cursor.getInt(cursor
                            .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                    if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        downloading = false;
                        dialog.dismiss();
                    }
                    final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setProgress(dl_progress);
                            Log.d("Download", "dl_progress = " + dl_progress);
                        }
                    });
                    cursor.close();
                }
            }
        }).start();
    }


    @Override
    protected void startCoding() {

    }

    @Override
    public void onSuccess(Object o) {

    }

    @Override
    public void onError(String error) {

    }
}

子布局代码 app_upgrade_dialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:paddingVertical="100dp"
    android:layout_height="match_parent">



    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <LinearLayout
            android:background="#fff"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp" />

            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="版本更新通知!"
                android:textColor="#202020"
                android:textSize="20dp"
                android:visibility="gone" />

            <TextView
                android:layout_gravity="center"
                android:id="@+id/tv_version_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_title"
                android:layout_centerInParent="true"
                android:layout_marginTop="30dp"
                android:text="当前有新版本可以更新"
                android:textSize="18sp" />



            <Button
            android:id="@+id/btn_confirm"
            android:layout_width="match_parent"
            android:layout_height="36dp"
            android:layout_alignParentBottom="true"
            android:layout_marginHorizontal="20dp"
            android:background="@drawable/shape_login3"
            android:text="确定"
            android:textColor="#FFFFFF"
            android:textSize="16sp"
            android:layout_marginVertical="20dp"/>




        </LinearLayout>
    </ScrollView>
 
</RelativeLayout>

子布局代码 app_download_dialog

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_content"
    android:layout_width="690px"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:gravity="center_vertical"
        android:background="@android:color/white"
        android:paddingLeft="37px"
        android:text="提示"
        android:textSize="30px"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="150px"
        android:layout_weight="1"
        android:background="@android:color/white"
        android:gravity="center_vertical"
        android:padding="20px"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30px"
            android:layout_gravity="right"
            android:text="正在下载"/>

        <ProgressBar
            android:id="@+id/pb_download_progress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="?android:attr/progressBarStyleHorizontal"
            android:max="100"/>
    </LinearLayout>

</LinearLayout>

三、 在清单文件中配置,注意android:authorities里面是自己的包名

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="这个地方是你的项目包名.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true"
    tools:replace="android:authorities">

    <!-- 指定Uri的共享路径 -->
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

内容提供者需要的文件,在xml文件下创建file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--    <external-path-->
<!--        name="external_storage_root"-->
<!--        path="." />-->
<!--    <files-path-->
<!--        name="files-path"-->
<!--        path="." />-->
<!--    <cache-path-->
<!--        name="cache-path"-->
<!--        path="." />-->
<!--    &lt;!&ndash;/storage/emulated/0/Android/data/...&ndash;&gt;-->
<!--    <external-files-path-->
<!--        name="external_file_path"-->
<!--        path="." />-->
<!--    &lt;!&ndash;代表app 外部存储区域根目录下的文件 Context.getExternalCacheDir目录下的目录&ndash;&gt;-->
<!--    <external-cache-path-->
<!--        name="external_cache_path"-->
<!--        path="." />-->
<!--    &lt;!&ndash;配置root-path。这样子可以读取到sd卡和一些应用分身的目录,否则微信分身保存的图片,就会导致 java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/999/tencent/MicroMsg/WeiXin/export1544062754693.jpg,在小米6的手机上微信分身有这个crash,华为没有-->
<!--&ndash;&gt;-->
<!--    <root-path-->
<!--        name="root-path"-->
<!--        path="" />-->

<!--    <external-path-->
<!--        name="images"-->
<!--        path="."/>-->

    <external-path
        path="Android/data/${applicationId}/"
        name="files_root" />
    <external-path
        path="."
        name="external_storage_root" />
    <files-path
        name="files"
        path="." />

</paths>

在这里插入图片描述

五、需要注意一下,这两个位置的名字一定要一样,

在这里插入图片描述
在这里插入图片描述
请添加图片描述
请添加图片描述

以上就是Android中下载安装其他app 的代码,地址里面如果是当前apk 的话且版本号比当前版本高,就是实现更新的代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值