Android implements methods for checking and downloading APK updates installing APK and obtaining network information

  • 2020-06-03 08:16:53
  • OfStack

Described in this article android code of instance for a weather forecasts, mainly including the download and install APK, check for updates Apk, display 'is the latest' or 'unable to get version information dialog box, access to current client version information, display version update notification dialog, download dialog, judge whether a mount SD card, display format file size: 2 decimal display, etc. The specific implementation code is as follows:


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.lmw.weather.R;
import org.lmw.weather.entity.AppDetail;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadManager {
  private static final int DOWN_NOSDCARD = 0;
  private static final int DOWN_UPDATE = 1;
  private static final int DOWN_OVER = 2;
  private static final int DOWN_ERROR=3;
  private static final int DIALOG_TYPE_LATEST = 0;
  private static final int DIALOG_TYPE_FAIL = 1;
  private static final int DIALOG_TYPE_INTERNETERROR = 2;
  private static DownloadManager downloadManager;
  private Context mContext;
  //  Notification dialog 
  private Dialog noticeDialog;
  //  Download dialog box 
  private Dialog downloadDialog;
  //  The progress bar 
  private ProgressBar mProgress;
  //  Display download value 
  private TextView mProgressText;
  //  Query the animation 
  private ProgressDialog mProDialog;
  // ' It's up to date '  or  ' Unable to get the latest version '  The dialog 
  private Dialog latestOrFailDialog;
  //  The installation package returned url
  private String apkUrl = "";
  //  The progress of value 
  private int progress;
  //  Download the thread 
  private Thread downLoadThread;
  //  End tag 
  private boolean interceptFlag;
  //  The clues 
  private String updateMsg = "";
  //  Download package save path 
  private String savePath = "";
  // apk Save the full path 
  private String apkFilePath = "";
  //  Temporary download file path 
  private String tmpFilePath = "";
  //  Download file size 
  private String apkFileSize;
  //  Downloaded file size 
  private String tmpFileSize;
  private String curVersionName = "";
  private int curVersionCode;
  private AppDetail mDownload;
  private String checkUrl="http://192.168.0.133:8080/lmw/androidMarket/SimpleWeather-20130701093349937/update.xml";
  private Handler mHandler = new Handler() {
 public void handleMessage(Message msg) {
   switch (msg.what) {
   case DOWN_UPDATE:
 mProgress.setProgress(progress);
 mProgressText.setText(tmpFileSize + "/" + apkFileSize);
 break;
   case DOWN_OVER:
 downloadDialog.dismiss();
 installApk();
 break;
   case DOWN_NOSDCARD:
 downloadDialog.dismiss();
 Toast.makeText(mContext, " Unable to download the installation file, please check SD Whether the card is mounted ",Toast.LENGTH_SHORT).show();
 break;
   case DOWN_ERROR:
 downloadDialog.dismiss();
 if(msg.arg1==0){
 Toast.makeText(mContext, " The Internet doesn't work ", Toast.LENGTH_SHORT).show();
 }else if(msg.arg1==1||msg.arg1==2){
 Toast.makeText(mContext, " Resources not found ",Toast.LENGTH_SHORT).show();
 }
 break;
   }
 };
  };
  public static DownloadManager getDownloadManager() {
 if (downloadManager == null) {
   downloadManager = new DownloadManager();
 }
 downloadManager.interceptFlag = false;
 return downloadManager;
  }
  public void DownLoader(Context context, AppDetail download) {
 this.mContext = context;
 this.mDownload = download;
 showDownloadDialog();
  }
  /**
   *  check App update 
   * @param context
   * @param isShowMsg
   *  Whether to display a prompt message 
   */
  public void checkAppUpdate(Context context, final boolean isShowMsg,final boolean notmain) {
 this.mContext = context;
 getCurrentVersion(mContext);
 if (isShowMsg) {
   if (mProDialog == null)
 mProDialog = ProgressDialog.show(mContext, null, " Testing is underway, please wait ...",true, true);
   else if (mProDialog.isShowing()|| (latestOrFailDialog != null && latestOrFailDialog.isShowing()))
 return;
 }
 final Handler handler = new Handler() {
   public void handleMessage(Message msg) {
 //  The progress bar dialog box is not displayed  -  The test results don't show up 
 if (mProDialog != null && !mProDialog.isShowing()) {
   return;
 }
 //  Close and release the release progress bar dialog 
 if (isShowMsg && mProDialog != null) {
   mProDialog.dismiss();
   mProDialog = null;
 }
 //  Display test results 
 if (msg.what == 1) {
   mDownload = (AppDetail) msg.obj;
   if (mDownload != null) {
  if (curVersionCode < mDownload.getVersionCode()) {
    apkUrl = mDownload.getUri()+mDownload.getFileName();
    updateMsg = mDownload.getAppHistory();
    showNoticeDialog();
  } else if (isShowMsg) {
    if (notmain) {
  showLatestOrFailDialog(DIALOG_TYPE_LATEST);
    }
  }
   }
 }else if(msg.what==-1&&isShowMsg){
  showLatestOrFailDialog(DIALOG_TYPE_INTERNETERROR);
 }else if (isShowMsg) {
   showLatestOrFailDialog(DIALOG_TYPE_FAIL);
 }
   }
 };
 new Thread() {
   public void run() {
 Message msg = new Message();
 try {
  DefaultHttpClient client = new DefaultHttpClient();
  client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
  HttpGet get = new HttpGet(checkUrl);
  HttpResponse response = client.execute(get);
  if (response.getStatusLine().getStatusCode() == 200) {
  HttpEntity entity = response.getEntity();
  InputStream stream = new ByteArrayInputStream( EntityUtils.toString(entity, "gb2312").getBytes());
   AppDetail update = AppDetail.parseXML(stream);
   msg.what = 1;
   msg.obj = update;
  }else{
   msg.what = -1;
  }
 } catch (Exception e) {
   e.printStackTrace();
   msg.what = -1;
 }
 handler.sendMessage(msg);
   }
 }.start();
  }
  /* According to ' It's up to date ' or ' Unable to get version information ' dialog */
  private void showLatestOrFailDialog(int dialogType) {
   String ToastMsg="";
 if (latestOrFailDialog != null) {
   //  Close and release the previous dialog 
   latestOrFailDialog.dismiss();
   latestOrFailDialog = null;
 }
// AlertDialog.Builder builder = new Builder(mContext);
// builder.setTitle(" The system prompt ");
 if (dialogType == DIALOG_TYPE_LATEST) {
//   builder.setMessage(" You are currently up to date ");
   ToastMsg=" You are currently up to date ";
 } else if (dialogType == DIALOG_TYPE_FAIL) {
//   builder.setMessage(" Unable to get version update information ");
 ToastMsg=" Unable to get version update information ";
 }else if(dialogType==DIALOG_TYPE_INTERNETERROR){
// builder.setMessage(" Network failure, unable to connect to server ");
 ToastMsg=" Network failure, unable to connect to server ";
 }
 Toast.makeText(mContext, ToastMsg, Toast.LENGTH_SHORT).show();
  }
  /* Gets current client version information */
  public String getCurrentVersion(Context context) {
 try {
   PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
   curVersionName = info.versionName;
   curVersionCode = info.versionCode;
 } catch (NameNotFoundException e) {
   e.printStackTrace(System.err);
 }
 return curVersionName;
  }
  /* Displays the version update notification dialog box */
  private void showNoticeDialog() {
 AlertDialog.Builder builder = new Builder(mContext);
 builder.setTitle(" Software version update ");
 builder.setMessage(updateMsg);
 builder.setPositiveButton(" Update now ", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
 dialog.dismiss();
 showDownloadDialog();
   }
 });
 builder.setNegativeButton(" later ", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
 dialog.dismiss();
   }
 });
 noticeDialog = builder.create();
 noticeDialog.show();
  }
  /* Displays the download dialog box */
  private void showDownloadDialog() {
 AlertDialog.Builder builder = new Builder(mContext);
 builder.setTitle(" Downloading the installation package ");
 final LayoutInflater inflater = LayoutInflater.from(mContext);
 View v = inflater.inflate(R.layout.download_progress, null);
 mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
 mProgressText = (TextView) v.findViewById(R.id.update_progress_text);
 builder.setView(v);
 builder.setNegativeButton(" cancel ", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
 dialog.dismiss();
 interceptFlag = true;
   }
 });
 builder.setOnCancelListener(new OnCancelListener() {
   @Override
   public void onCancel(DialogInterface dialog) {
 dialog.dismiss();
 interceptFlag = true;
   }
 });
 downloadDialog = builder.create();
 downloadDialog.setCanceledOnTouchOutside(false);
 downloadDialog.show();
 downloadApk();
  }
  private Runnable mdownApkRunnable = new Runnable() {
 Message error_msg=new Message();
 @Override
 public void run(){
   try {
 String apkName = mDownload.getFileName().replace(".apk","")+".apk";
 String tmpApk = mDownload.getFileName().replace(".apk","")+".tmp";
 //  Determines whether it is mounted SD card 
 String storageState = Environment.getExternalStorageState();
 if (storageState.equals(Environment.MEDIA_MOUNTED)) {
   savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/QN/QNStore/";
   File file = new File(savePath);
   if (!file.exists()) {
  file.mkdirs();
   }
   apkFilePath = savePath + apkName;
   tmpFilePath = savePath + tmpApk;
 }
 //  No mount SD Card, unable to download file 
 if (apkFilePath == null || apkFilePath == "") {
   mHandler.sendEmptyMessage(DOWN_NOSDCARD);
   return;
 }
 File ApkFile = new File(apkFilePath);
 //  Whether the update file has been downloaded 
// if (ApkFile.exists()) {
//   downloadDialog.dismiss();
//   installApk();
//   return;
// }
 //  Output temporary download file 
 File tmpFile = new File(tmpFilePath);
 FileOutputStream fos = new FileOutputStream(tmpFile);
 URL url = new URL(mDownload.getUri()+mDownload.getFileName());
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 try {
   conn.connect();
 } catch (ConnectTimeoutException e) {
   error_msg.what=DOWN_ERROR;
   error_msg.arg1=0;
   mHandler.sendMessage(error_msg);
 }
 int length = conn.getContentLength();
 InputStream is = conn.getInputStream();
 //  Display file size format: 2 Decimal point display 
 DecimalFormat df = new DecimalFormat("0.00");
 //  The total file size shown below the progress bar 
 apkFileSize = df.format((float) length / 1024 / 1024) + "MB";
 int count = 0;
 byte buf[] = new byte[1024];
 do {
   int numread = is.read(buf);
   count += numread;
   //  The current download file size shown below the progress bar 
   tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
   //  Current progress value 
   progress = (int) (((float) count / length) * 100);
   //  Update progress 
   mHandler.sendEmptyMessage(DOWN_UPDATE);
   if (numread <= 0) {
  //  The download is complete  -  Convert temporary download files to APK file 
  if (tmpFile.renameTo(ApkFile)) {
    //  Notify the installation 
    mHandler.sendEmptyMessage(DOWN_OVER);
  }
  break;
   }
   fos.write(buf, 0, numread);
 } while (!interceptFlag);//  Click Cancel to stop the download 
 fos.close();
 is.close();
   } catch (MalformedURLException e) {
 error_msg.what=DOWN_ERROR;
 error_msg.arg1=1;
 mHandler.sendMessage(error_msg);
 e.printStackTrace();
   } catch (IOException e) {
 error_msg.what=DOWN_ERROR;
 error_msg.arg1=2;
 mHandler.sendMessage(error_msg);
 e.printStackTrace();
   }
 }
  };
  /**
   *  download apk
   * @param url
   */
  private void downloadApk() {
 downLoadThread = new Thread(mdownApkRunnable);
 downLoadThread.start();
  }
  /**
   *  The installation apk
   * @param url
   */
  private void installApk() {
 File apkfile = new File(apkFilePath);
 if (!apkfile.exists()) {
   return;
 }
 Intent i = new Intent(Intent.ACTION_VIEW);
 i.setDataAndType(Uri.parse("file://" + apkfile.toString()),"application/vnd.android.package-archive");
 mContext.startActivity(i);
  }
}


Related articles: