android实现软件自动更新的步骤

作者:HarryWeasley 时间:2022-12-27 00:48:17 

本篇文章是直接下载最新的APK安装的方法,并不是增量下载该APk。

想要实现一个android应用,自动更新下载APK软件的方法,我采取的是以下几步方法:

1.每次进入主界面时,获取服务器的数据,看是否是最新版本,是,则无操作,否,则进行以下步骤;

2.弹出是否更新软件的对话框,点击下载后

3.弹出下载的进度条的对话框,开始下载,可以上随时点击按钮,停止下载

4.下载完成后,调用系统安装软件的服务,安装软件

效果图:

 android实现软件自动更新的步骤

 android实现软件自动更新的步骤

实现过程:  

新建一个UpdateManager方法,具体内容我已经有详细的注释


package lgx.acc.updatedemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class UpdateManager {
// 应用程序Context
private Context mContext;
// 是否是最新的应用,默认为false
private boolean isNew = false;
private boolean intercept = false;
// 下载安装包的网络路径
private String apkUrl = "http://shouji.360tpcdn.com/360sj/tpi/20130201/"
  + "com.flikie.wallpapers.gallery_4.apk";
// 保存APK的文件夹
private static final String savePath = "/sdcard/updatedemo/";
private static final String saveFileName = savePath
  + "UpdateDemoRelease.apk";
// 下载线程
private Thread downLoadThread;
private int progress;// 当前进度
TextView text;
// 进度条与通知UI刷新的handler和msg常量
private ProgressBar mProgress;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;

public UpdateManager(Context context) {
 mContext = context;
}

/**
 * 检查是否更新的内容
 */
public void checkUpdateInfo() {
 //这里的isNew本来是要从服务器获取的,我在这里先假设他需要更新
 if (isNew) {
  return;
 } else {
  showUpdateDialog();
 }
}

/**
 * 显示更新程序对话框,供主程序调用
 */
private void showUpdateDialog() {
 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
 builder.setTitle("软件版本更新");
 builder.setMessage("有最新的软件包,请下载!");
 builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {

@Override
  public void onClick(DialogInterface dialog, int which) {
   showDownloadDialog();
  }

});
 builder.setNegativeButton("以后再说",
   new DialogInterface.OnClickListener() {

@Override
    public void onClick(DialogInterface dialog, int which) {
     dialog.dismiss();
    }
   });

builder.create().show();
}

/**
 * 显示下载进度的对话框
 */
private void showDownloadDialog() {
 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
 builder.setTitle("软件版本更新");
 LayoutInflater inflater = LayoutInflater.from(mContext);
 View v = inflater.inflate(R.layout.progress, null);
 mProgress = (ProgressBar) v.findViewById(R.id.progress);

builder.setView(v);
 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override
  public void onClick(DialogInterface dialog, int which) {
   intercept = true;
  }
 });
 builder.show();
 downloadApk();
}

/**
 * 从服务器下载APK安装包
 */
private void downloadApk() {
 downLoadThread = new Thread(mdownApkRunnable);
 downLoadThread.start();
}

private Runnable mdownApkRunnable = new Runnable() {

@Override
 public void run() {
  URL url;
  try {
   url = new URL(apkUrl);
   HttpURLConnection conn = (HttpURLConnection) url
     .openConnection();
   conn.connect();
   int length = conn.getContentLength();
   InputStream ins = conn.getInputStream();
   File file = new File(savePath);
   if (!file.exists()) {
    file.mkdir();
   }
   File apkFile = new File(saveFileName);
   FileOutputStream fos = new FileOutputStream(apkFile);
   int count = 0;
   byte[] buf = new byte[1024];
   while (!intercept) {
    int numread = ins.read(buf);
    count += numread;
    progress = (int) (((float) count / length) * 100);

// 下载进度
    mHandler.sendEmptyMessage(DOWN_UPDATE);
    if (numread <= 0) {
     // 下载完成通知安装
     mHandler.sendEmptyMessage(DOWN_OVER);
     break;
    }
    fos.write(buf, 0, numread);
   }
   fos.close();
   ins.close();

} catch (Exception e) {
   e.printStackTrace();
  }
 }
};

/**
 * 安装APK内容
 */
private void installAPK() {
 File apkFile = new File(saveFileName);
 if (!apkFile.exists()) {
  return;
 }
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
   "application/vnd.android.package-archive");
 mContext.startActivity(intent);
};

private Handler mHandler = new Handler() {
 public void handleMessage(android.os.Message msg) {
  switch (msg.what) {

case DOWN_UPDATE:
   mProgress.setProgress(progress);
   break;

case DOWN_OVER:
   installAPK();
   break;

default:
   break;
  }
 }

};
}

还有progressBar.xml的具体代码


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ProgressBar
 android:id="@+id/progress"
 style="?android:attr/progressBarStyleHorizontal"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />
</LinearLayout>

 之后在MainActivity的onCreate方法中,调用一下代码即可


UpdateManager manager=new UpdateManager(MainActivity.this);
 manager.checkUpdateInfo();

一定要记得在manifest里面加权限哈,


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 最后效果就出来了。

来源:https://blog.csdn.net/HarryWeasley/article/details/44955719

标签:android,软件,自动更新
0
投稿

猜你喜欢

  • Java中ThreadLocal避免内存泄漏的方法详解

    2023-04-02 12:51:42
  • java实现将数字转换成人民币大写

    2023-08-11 05:07:29
  • 浅析Android加载字体包及封装的方法

    2022-01-08 22:32:26
  • 在C#的类或结构中重写ToString方法的用法简介

    2022-04-04 04:26:14
  • SpringBoot与SpringCache概念用法大全

    2022-05-24 01:35:44
  • mybatis中<choose>标签的用法说明

    2023-07-22 19:37:27
  • Mybatis如何解决sql中like通配符模糊匹配问题

    2023-12-22 19:39:52
  • Android Framework如何实现Binder

    2021-12-09 03:54:20
  • SpringBoot自定义Starter实现流程详解

    2022-05-19 07:03:25
  • MyBatis中基于别名typeAliases的设置

    2022-03-07 22:18:19
  • 详解android使用ItemDecoration 悬浮导航栏效果

    2022-05-07 18:17:09
  • java ThreadGroup的作用及方法详解

    2022-02-03 16:49:01
  • java ThreadPool线程池的使用,线程池工具类用法说明

    2023-06-23 18:12:12
  • Java使用自定义注解实现为事件源绑定事件监听器操作示例

    2023-06-21 01:17:55
  • 浅谈C#中简单的异常引发与处理操作

    2022-03-10 04:54:49
  • C# DataSet查看返回结果集的实现

    2021-10-10 09:54:31
  • java 如何给对象中的包装类设置默认值

    2022-02-09 21:04:08
  • springboot 如何解决static调用service为null

    2022-09-05 05:30:03
  • SpringBoot 整合 ElasticSearch操作各种高级查询搜索

    2023-03-25 17:12:40
  • C# lambda表达式原理定义及实例详解

    2021-07-26 21:44:44
  • asp之家 软件编程 m.aspxhome.com