SoFunction
Updated on 2025-04-05

Android implements methods to check and download APK updates, install APKs and obtain network information

Android implements methods to check and download APK updates, install APKs and obtain network information

Updated: July 28, 2014 10:34:40 Submission: shichen2014
This article mainly introduces Android to check and download APK updates, install APKs and obtain network information. It is very practical. Friends who need it can refer to it.

The examples described in this article are Android code in a weather forecast, which mainly includes downloading and installing APKs, checking Apk updates, displaying the 'already latest' or 'cannot get version information' dialog box, obtaining the current client version information, displaying the version update notification dialog box, displaying the download dialog box, determining whether the SD card is mounted, displaying the file size format: 2 decimal points, etc. The specific implementation code is as follows:

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
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 box  private Dialog noticeDialog;
  // Download dialog box  private Dialog downloadDialog;
  // Progress bar  private ProgressBar mProgress;
  // Display download value  private TextView mProgressText;
  // Query animation  private ProgressDialog mProDialog;
  // Dialog for 'already newest' or 'Cannot get the latest version'  private Dialog latestOrFailDialog;
  // The returned installation package url  private String apkUrl = "";
  // Progress value  private int progress;
  // Download thread  private Thread downLoadThread;
  // Termination mark  private boolean interceptFlag;
  // Prompt  private String updateMsg = "";
  // Download package saving path  private String savePath = "";
  // apk saves 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/";
  private Handler mHandler = new Handler() {
 public void handleMessage(Message msg) {
   switch () {
   case DOWN_UPDATE:
 (progress);
 (tmpFileSize + "/" + apkFileSize);
 break;
   case DOWN_OVER:
 ();
 installApk();
 break;
   case DOWN_NOSDCARD:
 ();
 (mContext, "Cannot download the installation file, please check whether the SD card is mounted",Toast.LENGTH_SHORT).show();
 break;
   case DOWN_ERROR:
 ();
 if(msg.arg1==0){
 (mContext, "The Internet is not good", Toast.LENGTH_SHORT).show();
 }else if(msg.arg1==1||msg.arg1==2){
 (mContext, "Resource not found",Toast.LENGTH_SHORT).show();
 }
 break;
   }
 };
  };
  public static DownloadManager getDownloadManager() {
 if (downloadManager == null) {
   downloadManager = new DownloadManager();
 }
  = false;
 return downloadManager;
  }
  public void DownLoader(Context context, AppDetail download) {
  = context;
  = download;
 showDownloadDialog();
  }
  /**
    * Check App Updates
    * @param context
    * @param isShowMsg
    * Whether to display a prompt message
    */
  public void checkAppUpdate(Context context, final boolean isShowMsg,final boolean notmain) {
  = context;
 getCurrentVersion(mContext);
 if (isShowMsg) {
   if (mProDialog == null)
 mProDialog = (mContext, null, "Testing, please wait...",true, true);
   else if (()|| (latestOrFailDialog != null && ()))
 return;
 }
 final Handler handler = new Handler() {
   public void handleMessage(Message msg) {
 // The progress bar dialog box is not displayed - the detection results are not displayed either if (mProDialog != null && !()) {
   return;
 }
 // Close and release the Release Progress Bar dialog box if (isShowMsg && mProDialog != null) {
   ();
   mProDialog = null;
 }
 // Show detection results if ( == 1) {
   mDownload = (AppDetail) ;
   if (mDownload != null) {
  if (curVersionCode < ()) {
    apkUrl = ()+();
    updateMsg = ();
    showNoticeDialog();
  } else if (isShowMsg) {
    if (notmain) {
  showLatestOrFailDialog(DIALOG_TYPE_LATEST);
    }
  }
   }
 }else if(==-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();
  ().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
  HttpGet get = new HttpGet(checkUrl);
  HttpResponse response = (get);
  if (().getStatusCode() == 200) {
  HttpEntity entity = ();
  InputStream stream = new ByteArrayInputStream( (entity, "gb2312").getBytes());
   AppDetail update = (stream);
    = 1;
    = update;
  }else{
    = -1;
  }
 } catch (Exception e) {
   ();
    = -1;
 }
 (msg);
   }
 }.start();
  }
  /*Show the 'already latest' or 'cannot get version information' dialog box*/
  private void showLatestOrFailDialog(int dialogType) {
   String ToastMsg="";
 if (latestOrFailDialog != null) {
   // Close and release the previous dialog box   ();
   latestOrFailDialog = null;
 }
//  builder = new Builder(mContext);
// ("System prompt"); if (dialogType == DIALOG_TYPE_LATEST) {
// ("You are currently in the latest version");   ToastMsg="You are currently in the latest version";
 } else if (dialogType == DIALOG_TYPE_FAIL) {
// ("Unable to obtain version update information"); ToastMsg="Unable to obtain version update information";
 }else if(dialogType==DIALOG_TYPE_INTERNETERROR){
// ("Network failure, unable to connect to the server"); ToastMsg="Network failure, unable to connect to the server";
 }
 (mContext, ToastMsg, Toast.LENGTH_SHORT).show();
  }
  /*Get the current client version information*/
  public String getCurrentVersion(Context context) {
 try {
   PackageInfo info = ().getPackageInfo((), 0);
   curVersionName = ;
   curVersionCode = ;
 } catch (NameNotFoundException e) {
   ();
 }
 return curVersionName;
  }
  /*Show version update notification dialog box*/
  private void showNoticeDialog() {
  builder = new Builder(mContext);
 ("Software Version Update");
 (updateMsg);
 ("Update now", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
 ();
 showDownloadDialog();
   }
 });
 ("Let's talk about it later", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
 ();
   }
 });
 noticeDialog = ();
 ();
  }
  /*Show download dialog box*/
  private void showDownloadDialog() {
  builder = new Builder(mContext);
 ("Downloading the installation package");
 final LayoutInflater inflater = (mContext);
 View v = (.download_progress, null);
 mProgress = (ProgressBar) (.update_progress);
 mProgressText = (TextView) (.update_progress_text);
 (v);
 ("Cancel", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
 ();
 interceptFlag = true;
   }
 });
 (new OnCancelListener() {
   @Override
   public void onCancel(DialogInterface dialog) {
 ();
 interceptFlag = true;
   }
 });
 downloadDialog = ();
 (false);
 ();
 downloadApk();
  }
  private Runnable mdownApkRunnable = new Runnable() {
 Message error_msg=new Message();
 @Override
 public void run(){
   try {
 String apkName = ().replace(".apk","")+".apk";
 String tmpApk = ().replace(".apk","")+".tmp";
 // Determine whether the SD card is mounted String storageState = ();
 if ((Environment.MEDIA_MOUNTED)) {
   savePath = ().getAbsolutePath() + "/QN/QNStore/";
   File file = new File(savePath);
   if (!()) {
  ();
   }
   apkFilePath = savePath + apkName;
   tmpFilePath = savePath + tmpApk;
 }
 // The SD card is not mounted, and the file cannot be downloaded if (apkFilePath == null || apkFilePath == "") {
   (DOWN_NOSDCARD);
   return;
 }
 File ApkFile = new File(apkFilePath);
 // Whether the updated file has been downloaded// if (()) {
//   ();
//   installApk();
//   return;
// }
 // Output temporary download file File tmpFile = new File(tmpFilePath);
 FileOutputStream fos = new FileOutputStream(tmpFile);
 URL url = new URL(()+());
 HttpURLConnection conn = (HttpURLConnection) ();
 try {
   ();
 } catch (ConnectTimeoutException e) {
   error_msg.what=DOWN_ERROR;
   error_msg.arg1=0;
   (error_msg);
 }
 int length = ();
 InputStream is = ();
 // Display file size format: 2 decimal points to display DecimalFormat df = new DecimalFormat("0.00");
 // Total file size displayed under the progress bar apkFileSize = ((float) length / 1024 / 1024) + "MB";
 int count = 0;
 byte buf[] = new byte[1024];
 do {
   int numread = (buf);
   count += numread;
   // The current download file size displayed under the progress bar   tmpFileSize = ((float) count / 1024 / 1024) + "MB";
   // Current progress value   progress = (int) (((float) count / length) * 100);
   // Update progress   (DOWN_UPDATE);
   if (numread <= 0) {
  // Download is completed - Convert temporary downloaded file to APK file  if ((ApkFile)) {
    // Notify installation    (DOWN_OVER);
  }
  break;
   }
   (buf, 0, numread);
 } while (!interceptFlag);// Click Cancel to stop downloading ();
 ();
   } catch (MalformedURLException e) {
 error_msg.what=DOWN_ERROR;
 error_msg.arg1=1;
 (error_msg);
 ();
   } catch (IOException e) {
 error_msg.what=DOWN_ERROR;
 error_msg.arg1=2;
 (error_msg);
 ();
   }
 }
  };
  /**
    * Download apk
    * @param url
    */
  private void downloadApk() {
 downLoadThread = new Thread(mdownApkRunnable);
 ();
  }
  /**
    * Install apk
    * @param url
    */
  private void installApk() {
 File apkfile = new File(apkFilePath);
 if (!()) {
   return;
 }
 Intent i = new Intent(Intent.ACTION_VIEW);
 (("file://" + ()),"application/-archive");
 (i);
  }
}

  • Android
  • APK
  • renew
  • Install

Related Articles

  • Android WebView cache mechanism optimization problem slow loading

    I know you must be worried about the performance problems of Android Webview. What is particularly prominent is that it is slow loading speed and consumes traffic. It proposes some effective solutions to the performance problems of Android Webview.
    2023-02-02
  • Android custom controls

    This article mainly introduces the scale controls of Android custom controls. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2020-06-06
  • Android Glide image loading (load monitoring, load animation)

    This article mainly introduces the specific implementation methods of Android Glide image loading, including loading monitoring and loading animations, which have certain reference value. Interested friends can refer to it.
    2016-11-11
  • Android high-quality WeChat 5.2.1 main interface and message reminder

    This article mainly introduces the main interface and message reminders of Android high-imitation WeChat 5.2.1, which has certain reference value. Interested friends can refer to it.
    2016-09-09
  • Analysis of three Android GSM mobile phone technology

    This article will introduce the differences between the three Android GSM technologies. Interested friends can refer to it.
    2012-12-12
  • Android development tutorial: The combination of shape and selector

    Shape and selector are often used in Android UI design. For example, if we want to customize a rounded Button, click on some changes in the effect of Button, we need to use shape and selector. Next, through this article, we will introduce to you the combination of shape and selector. Interested friends, let’s learn together.
    2016-01-01
  • Recyclerview adds head layout and tail layout, and detailed explanation of item click event

    This article mainly introduces the relevant information about the head layout and tail layout of Recyclerview, and item click events. It has certain reference value. Interested friends can refer to it.
    2017-08-08
  • Kotlin using scroll control RecyclerView instance tutorial

    RecyclerView is a more powerful control for Android. It not only achieves the same effect as ListView, but also optimizes various shortcomings in ListView. It can realize vertical scrolling of data or horizontal scrolling (ListView cannot perform horizontal scrolling). Next, explain the usage of RecyclerView
    2022-12-12
  • Android layout custom Shap circular ImageView can set background and image separately

    This article mainly introduces Android layout custom Shap circular ImageView that can set background and pictures separately. Friends who need it can refer to it.
    2016-01-01
  • Android studio implements simple calculator small functions

    This article mainly introduces the small functions of Android studio to implement simple calculator. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2022-05-05

Latest Comments