Android提示自动更新

在登录页或者欢迎页就去检查更新

private void checkUpdate(){
    new Thread(){
        public void run() {
            final boolean needUpdate = UpdateAppTool.doUpdataCheckNew(LoginActivity.this);
            UpdateAppTool.doUpdataCheckNew(LoginActivity.this);
            _NeedUpdate = needUpdate;
            if(needUpdate){
                Handler mainHandler = new Handler(LoginActivity.this.getMainLooper());
                Runnable myRunnable = new Runnable(){

                    @Override
                    public void run() {
                        try {
                            UpdateAppTool.doUpdateProcess(LoginActivity.this, needUpdate);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                };
                mainHandler.post(myRunnable);
            }
        }
    }.start();
}

检查更新需要的工具类

public class NetworkTool {
  
    public static String getContent(String url) throws Exception {
        StringBuilder sb = new StringBuilder();
        HttpGet httpGet = new HttpGet(url);  
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);  
        if (httpResponse.getStatusLine().getStatusCode() == 200) {                
            String result = EntityUtils.toString(httpResponse.getEntity()).trim();  
            result = new String(result.getBytes("utf-8"));
            sb.append(result);  
        }
        return sb.toString();
    }

   public static boolean isWifiNetwork(Context context) {
      ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return network != null && network.isAvailable() && network.isConnected();
   }
}
public class UpdateAppTool {
   private static int newVerCode = 0;
   private static String newVerName = "";
   private static String forceUP = ""; // 1

   public static boolean doUpdataCheckNew(Context ctx) {
      try {
         String updateInfoUrl = Config.UPDATE_PACKAGE_INFO_URL.replace(
               Config.REPLACE_APK_NAME, Config.UPDATE_APKNAME);
         String properties = NetworkTool.getContent(updateInfoUrl);
         InputStream is = new ByteArrayInputStream(
               properties.getBytes("UTF-8"));
         Properties prop = new Properties();
         prop.load(is);
         newVerName = prop.getProperty("customversionname", "2.0");
         newVerCode = Integer.parseInt(prop.getProperty("customversioncode",
               "1"));
         forceUP = prop.getProperty("force_update", "0");
         int mandatoryVersionCode = Integer.parseInt(prop.getProperty(
               "mandatoryversioncode", "35"));
         String packageName = ctx.getPackageName();
         PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(
               packageName, 0);
         final int vercode = packageInfo.versionCode;
         float newVerNameFloat = 0;
         float oldVerNameFloat = 0;
         final String oldVerName = packageInfo.versionName;
         try {
            newVerNameFloat = Float.parseFloat(newVerName);
            oldVerNameFloat = Float.parseFloat(oldVerName);
         } catch (NumberFormatException ne) {
         }
         forceUP = packageInfo.versionCode < mandatoryVersionCode ? "1"
               : "0";
         Log.d("autoupdate", "customversionname:" + newVerName
               + ",oldVerNameFloat:" + oldVerNameFloat + ",force_update:"
               + forceUP + ",getDownloadUrl():" + getDownloadUrl());
         Log.d("autoupdate", "customversioncode:" + newVerCode + ",vercode:"
               + vercode + ",mandatoryVersionCode:" + mandatoryVersionCode);
         if (newVerNameFloat == oldVerNameFloat && newVerCode > vercode
               || newVerNameFloat > oldVerNameFloat) {
            return true;
         }
      } catch (Exception e) {
         Log.e("autoupdate", "doUpdataCheckNew:" + e.getMessage());
         return false;
      }
      return false;
   }

   public static void doUpdateProcess(Context ctx, boolean isNewer) {
      Log.e("autoupdate", "doUpdateProcess,isNewer:" + isNewer + ",forceUP:"
            + forceUP);
      if (isNewer) {
         if (forceUP.equals("1")) {
            doForceUpdate(ctx);
         } else {
            doNewVersionUpdate(ctx);
         }
      } else {
         notNewVersionShow(ctx);
      }
   }

   private static void notNewVersionShow(Context ctx) {
      int verCode = Config.getVerCode(ctx);
      String verName = Config.getVerName(ctx);
      StringBuffer sb = new StringBuffer();
      sb.append(ctx.getString(R.string.update_current_version_name));
      sb.append(verName);
      sb.append(ctx.getString(R.string.update_current_version_code));
      sb.append(verCode);
      sb.append(ctx.getString(R.string.update_newest_version));
      Dialog dialog = new AlertDialog.Builder(ctx)
            .setTitle(ctx.getString(R.string.update_software))
            .setMessage(sb.toString())// set the content
            .setPositiveButton(ctx.getString(R.string.confirm),
                  new DialogInterface.OnClickListener() {

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

                  }).create();// create
      dialog.show();
   }

   private static void doForceUpdate(final Context ctx) {
      Log.i("autoupdate", "Do the update in force!");
      int verCode = Config.getVerCode(ctx);
      String verName = Config.getVerName(ctx);
      StringBuffer sb = new StringBuffer();
      sb.append(ctx.getString(R.string.update_current_version_name));
      sb.append(verName);
      sb.append(ctx.getString(R.string.update_find_new_version));
      sb.append(newVerName);
      sb.append(ctx.getString(R.string.update_should_update_inforce));
      Dialog dialog = new AlertDialog.Builder(ctx)
            .setTitle(ctx.getString(R.string.update_software))
            .setMessage(sb.toString())
            .setPositiveButton(ctx.getString(R.string.update),
                  new DialogInterface.OnClickListener() {

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

                        String url = getDownloadUrl();
                        downloadAPK(ctx, url);
                     }

                  }).create();
      dialog.show();
   }

   private static String getFileName() {
      return Config.UPDATE_APKNAME + "_" + newVerName + "_" + newVerCode
            + ".apk";
   }

   private static String getDownloadUrl() {
      return Config.DOWNLOAD_PACKAGE_URL.replace(Config.REPLACE_APK_NAME,
            Config.UPDATE_APKNAME);
   }

   private static void doNewVersionUpdate(final Context ctx) {
      int verCode = Config.getVerCode(ctx);
      String verName = Config.getVerName(ctx);
      StringBuffer sb = new StringBuffer();
      sb.append(ctx.getString(R.string.update_current_version_name));
      sb.append(verName);
      sb.append(ctx.getString(R.string.update_current_version_code));
      sb.append(verCode);
      sb.append(ctx.getString(R.string.update_find_new_version));
      sb.append(newVerName);
      sb.append(ctx.getString(R.string.update_server_version_code));
      sb.append(newVerCode);
      sb.append(ctx.getString(R.string.update_should_update));
      Dialog dialog = new AlertDialog.Builder(ctx)
            .setTitle(ctx.getString(R.string.update_software))
            .setMessage(sb.toString())
            .setPositiveButton(ctx.getString(R.string.update),
                  new DialogInterface.OnClickListener() {

                     @Override
                     public void onClick(DialogInterface dialog,
                           int which) {
                        String url = getDownloadUrl();
                        downloadAPK(ctx, url);
                     }

                  })
            .setNegativeButton(ctx.getString(R.string.update_later),
                  new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog,
                           int whichButton) {
                        // exit the update
                        // finish();
                     }
                  }).create();
      dialog.show();
   }

   private static void downloadAPK(final Context ctx, final String url) {
      String fileName = getFileName();
      final File applictionFile = new File(
            Environment
                  .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                  + "/" + fileName);
      if (applictionFile != null && applictionFile.exists()) {
         openAPKFile(ctx, applictionFile);
      } else {
         DownloadManager downloadManager = null;
         Uri uri = Uri.parse(url);
         Request request = new Request(uri);
         try {
            downloadManager = (DownloadManager) ctx
                  .getSystemService(Context.DOWNLOAD_SERVICE);
            request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
            request.setDestinationInExternalPublicDir(
                  Environment.DIRECTORY_DOWNLOADS, fileName);
         } catch (Exception e) {
            Dialog dialog = new AlertDialog.Builder(ctx)
                  .setTitle(ctx.getString(R.string.update_software))
                  .setMessage(
                        ctx.getString(R.string.download_failded_message))
                  .setNegativeButton(ctx.getString(R.string.ok), null)
                  .create();
            dialog.show();
            return;
         }
         final ProgressDialog pBar = new ProgressDialog(ctx);
         pBar.setTitle(ctx.getString(R.string.update_downloading));
         pBar.setMessage(ctx.getString(R.string.update_wait) + getFileName());
         pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
         pBar.setCancelable(false);
         pBar.show();
         final long myDownloadReference = downloadManager.enqueue(request);
         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 (myDownloadReference == reference) {
                  ctx.unregisterReceiver(this);
                  pBar.cancel();
                  openAPKFile(ctx, applictionFile);
               }
            }
         };
         ctx.registerReceiver(receiver, filter);
      }
   }

   private static void openAPKFile(Context ctx, File apkFile) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setDataAndType(Uri.fromFile(apkFile),
            "application/vnd.android.package-archive");
      ctx.startActivity(intent);
   }
}

检查更新需要的配置信息,将properties文件和apk放在服务器中,通过读取properties文件中的versionname和versioncode与本地相比较,需要更新则做更新操作

public class Config {
    /**
     * apk的名字
     */
    public static final String UPDATE_APKNAME = "bossYang-release.apk";
    public static final String REPLACE_APK_NAME = "$APKNAME";
    /**
     * 检测版本的文件地址
     */
    public static final String UPDATE_PACKAGE_INFO_URL = "http://zero.chenksoft.com/bossyang/update/custom_project.properties";
    /**
     *下载的新版apk地址
     */
    public static final String DOWNLOAD_PACKAGE_URL = "http://zero.chenksoft.com/bossyang/update/bossYang-release.apk";
    public static final String UPDATE_BETA = "1";
    public static final String UPDATE_OFFICIAL = "2";
    public static final String UPDATE_SERVER = "http://dev.chenksoft.com/zhsq/version.do?";
    public static final String UPDATE_PACKAGE_ADDRESS = "http://dev.chenksoft.com/zhsq/apkdown.do?apkid=";
    public static final String UPDATE_PLATFORM_ANDROID_PAD = "android_pad";
    public static final String UPDATE_PLATFORM_ANDROID_PHONE = "android_phone";
    public static final String UPDATE_PLATFORM_IPHONE = "iphone";
    public static final String UPDATE_PLATFORM_IPAD = "ipad";
    public static final String currentVersion = UPDATE_BETA;
    public static int getVerCode(Context context) {
        int verCode = -1;
        String packageName = context.getPackageName();
        try{
           verCode = context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
        }catch (NameNotFoundException e){
           Log.i("autoupdate", "getVerCode:" + e.getMessage());
        }
        return verCode;
    }
    
    public static String getVerName(Context context) {
        String verName = "";
        String packageName = context.getPackageName();
        try{
           verName = context.getPackageManager().getPackageInfo(packageName, 0).versionName;
        }catch (NameNotFoundException e) {
           Log.i("autoupdate","getVerName:" + e.getMessage());
        }
        return verName; 
    }
    
    public static String getAppName(Context context) {
        String verName = UPDATE_APKNAME;
        try {
            verName = new String(verName.getBytes("utf-8"));
        }catch(Exception e) {
           e.printStackTrace();
        }
        return verName;
    }
}
properties文件内容:

# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
customdisplayname=3T分销
custompackage=com.bossyang.activity
customversionname=2
customversioncode=5
device_deployment=PHONE\&PAD
mandatoryversioncode=1
force_update=1

/**********/

其中比较customversionname与customversioncode,修改自己相对应的app名和包名。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值