国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android實(shí)現(xiàn)檢查并下載APK更新、安裝APK及獲取網(wǎng)絡(luò)信息的方法

2020-04-11 11:47:39
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文所述實(shí)例為一個(gè)天氣預(yù)報(bào)中的android代碼,主要包括了下載和安裝APK、檢查Apk更新、顯示'已經(jīng)是最新'或者'無(wú)法獲取版本信息'對(duì)話框、獲取當(dāng)前客戶(hù)端版本信息、顯示版本更新通知對(duì)話框、顯示下載對(duì)話框、判斷是否掛載了SD卡、顯示文件大小格式:2個(gè)小數(shù)點(diǎn)顯示等。具體實(shí)現(xiàn)代碼如下:

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;  // 通知對(duì)話框  private Dialog noticeDialog;  // 下載對(duì)話框  private Dialog downloadDialog;  // 進(jìn)度條  private ProgressBar mProgress;  // 顯示下載數(shù)值  private TextView mProgressText;  // 查詢(xún)動(dòng)畫(huà)  private ProgressDialog mProDialog;  // '已經(jīng)是最新' 或者 '無(wú)法獲取最新版本' 的對(duì)話框  private Dialog latestOrFailDialog;  // 返回的安裝包url  private String apkUrl = "";  // 進(jìn)度值  private int progress;  // 下載線程  private Thread downLoadThread;  // 終止標(biāo)記  private boolean interceptFlag;  // 提示語(yǔ)  private String updateMsg = "";  // 下載包保存路徑  private String savePath = "";  // apk保存完整路徑  private String apkFilePath = "";  // 臨時(shí)下載文件路徑  private String tmpFilePath = "";  // 下載文件大小  private String apkFileSize;  // 已下載文件大小  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, "無(wú)法下載安裝文件,請(qǐng)檢查SD卡是否掛載",Toast.LENGTH_SHORT).show(); break;   case DOWN_ERROR: downloadDialog.dismiss(); if(msg.arg1==0){ Toast.makeText(mContext, "網(wǎng)絡(luò)不給力啊", Toast.LENGTH_SHORT).show(); }else if(msg.arg1==1||msg.arg1==2){ Toast.makeText(mContext, "未找到資源",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();  }  /**   * 檢查App更新   * @param context   * @param isShowMsg   * 是否顯示提示消息   */  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, "正在檢測(cè),請(qǐng)稍后...",true, true);   else if (mProDialog.isShowing()|| (latestOrFailDialog != null && latestOrFailDialog.isShowing())) return; } final Handler handler = new Handler() {   public void handleMessage(Message msg) { // 進(jìn)度條對(duì)話框不顯示 - 檢測(cè)結(jié)果也不顯示 if (mProDialog != null && !mProDialog.isShowing()) {   return; } // 關(guān)閉并釋放釋放進(jìn)度條對(duì)話框 if (isShowMsg && mProDialog != null) {   mProDialog.dismiss();   mProDialog = null; } // 顯示檢測(cè)結(jié)果 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();  }  /*顯示'已經(jīng)是最新'或者'無(wú)法獲取版本信息'對(duì)話框*/  private void showLatestOrFailDialog(int dialogType) {   String ToastMsg=""; if (latestOrFailDialog != null) {   // 關(guān)閉并釋放之前的對(duì)話框   latestOrFailDialog.dismiss();   latestOrFailDialog = null; }// AlertDialog.Builder builder = new Builder(mContext);// builder.setTitle("系統(tǒng)提示"); if (dialogType == DIALOG_TYPE_LATEST) {//   builder.setMessage("您當(dāng)前已經(jīng)是最新版本");   ToastMsg="您當(dāng)前已經(jīng)是最新版本"; } else if (dialogType == DIALOG_TYPE_FAIL) {//   builder.setMessage("無(wú)法獲取版本更新信息"); ToastMsg="無(wú)法獲取版本更新信息"; }else if(dialogType==DIALOG_TYPE_INTERNETERROR){// builder.setMessage("網(wǎng)絡(luò)故障,無(wú)法連接服務(wù)器"); ToastMsg="網(wǎng)絡(luò)故障,無(wú)法連接服務(wù)器"; } Toast.makeText(mContext, ToastMsg, Toast.LENGTH_SHORT).show();  }  /*獲取當(dāng)前客戶(hù)端版本信息*/  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;  }  /*顯示版本更新通知對(duì)話框*/  private void showNoticeDialog() { AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("軟件版本更新"); builder.setMessage(updateMsg); builder.setPositiveButton("立即更新", new OnClickListener() {   @Override   public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); showDownloadDialog();   } }); builder.setNegativeButton("以后再說(shuō)", new OnClickListener() {   @Override   public void onClick(DialogInterface dialog, int which) { dialog.dismiss();   } }); noticeDialog = builder.create(); noticeDialog.show();  }  /*顯示下載對(duì)話框*/  private void showDownloadDialog() { AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("正在下載安裝包"); 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("取消", 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"; // 判斷是否掛載了SD卡 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; } // 沒(méi)有掛載SD卡,無(wú)法下載文件 if (apkFilePath == null || apkFilePath == "") {   mHandler.sendEmptyMessage(DOWN_NOSDCARD);   return; } File ApkFile = new File(apkFilePath); // 是否已下載更新文件// if (ApkFile.exists()) {//   downloadDialog.dismiss();//   installApk();//   return;// } // 輸出臨時(shí)下載文件 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(); // 顯示文件大小格式:2個(gè)小數(shù)點(diǎn)顯示 DecimalFormat df = new DecimalFormat("0.00"); // 進(jìn)度條下面顯示的總文件大小 apkFileSize = df.format((float) length / 1024 / 1024) + "MB"; int count = 0; byte buf[] = new byte[1024]; do {   int numread = is.read(buf);   count += numread;   // 進(jìn)度條下面顯示的當(dāng)前下載文件大小   tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";   // 當(dāng)前進(jìn)度值   progress = (int) (((float) count / length) * 100);   // 更新進(jìn)度   mHandler.sendEmptyMessage(DOWN_UPDATE);   if (numread <= 0) {  // 下載完成 - 將臨時(shí)下載文件轉(zhuǎn)成APK文件  if (tmpFile.renameTo(ApkFile)) {    // 通知安裝    mHandler.sendEmptyMessage(DOWN_OVER);  }  break;   }   fos.write(buf, 0, numread); } while (!interceptFlag);// 點(diǎn)擊取消就停止下載 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();   } }  };  /**   * 下載apk   * @param url   */  private void downloadApk() { downLoadThread = new Thread(mdownApkRunnable); downLoadThread.start();  }  /**   * 安裝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);  }}

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 丹巴县| 五大连池市| 凤台县| 华池县| 新巴尔虎右旗| 奉新县| 石狮市| 青龙| 收藏| 五指山市| 专栏| 英超| 镇赉县| 南川市| 平江县| 安国市| 寿宁县| 林西县| 于都县| 金阳县| 麻栗坡县| 友谊县| 邯郸市| 琼中| 宣化县| 聂荣县| 磐安县| 丰台区| 安塞县| 镇安县| 突泉县| 南京市| 屯门区| 溧阳市| 莱州市| 新龙县| 建昌县| 福泉市| 伊川县| 靖远县| 合川市|