由於大家提出的注釋的問題,我做了一些修改,進行了一定的注釋說明,更新一下,希望大家多多支援,謝謝!
package com.autoupdate;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import android.webkit.URLUtil;
import com.autoupdate.R;
/**
* 版本檢測,自動更新
*
* @author shenyj-ydrh 1.通過Url檢測更新 2.下載並安裝更新 3.刪除臨時路徑
*
*/
public class MyAutoUpdate {
// 調用更新的Activity
public Activity activity = null;
// 目前的版本號
public int versionCode = 0;
// 目前的版本名稱
public String versionName = "";
// 控制台資訊標識
private static final String TAG = "AutoUpdate";
// 檔案當前路徑
private String currentFilePath = "";
// 安裝包檔案臨時路徑
private String currentTempFilePath = "";
// 獲得副檔名字串
private String fileEx = "";
// 獲得檔案名稱字串
private String fileNa = "";
// 伺服器位址
private String strURL = "http://127.0.0.1:8080/ApiDemos.apk";
private ProgressDialog dialog;
/**
* 構造方法,獲得目前的版本資訊
*
* @param activity
*/
public MyAutoUpdate(Activity activity) {
this.activity = activity;
// 獲得目前的版本
getCurrentVersion();
}
/**
* 檢測更新
*/
public void check() {
// 檢測網路
if (isNetworkAvailable(this.activity) == false) {
return;
}
// 如果網路可用,檢測到新版本
if (true) {
// 彈出對話方塊,選擇是否需要更新版本
showUpdateDialog();
}
}
/**
* 檢測是否有可用網路
*
* @param context
* @return 網路連接狀態
*/
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// 擷取網路資訊
NetworkInfo info = cm.getActiveNetworkInfo();
// 返回檢測的網路狀態
return (info != null && info.isConnected());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 彈出對話方塊,選擇是否需要更新版本
*/
public void showUpdateDialog() {
@SuppressWarnings("unused")
AlertDialog alert = new AlertDialog.Builder(this.activity)
.setTitle("新版本").setIcon(R.drawable.ic_launcher)
.setMessage("是否更新?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 通過地址下載檔案
downloadTheFile(strURL);
// 顯示更新狀態,進度條
showWaitDialog();
}
})
.setNegativeButton("否", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
/**
* 顯示更新狀態,進度條
*/
public void showWaitDialog() {
dialog = new ProgressDialog(activity);
dialog.setMessage("正在更新,請稍候...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
}
/**
* 獲得目前的版本資訊
*/
public void getCurrentVersion() {
try {
// 擷取應用程式套件資訊
PackageInfo info = activity.getPackageManager().getPackageInfo(
activity.getPackageName(), 0);
this.versionCode = info.versionCode;
this.versionName = info.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
/**
* 截取檔案名稱並執行下載
*
* @param strPath
*/
private void downloadTheFile(final String strPath) {
// 獲得檔案副檔名字串
fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())
.toLowerCase();
// 獲得檔案檔案名稱字串
fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,
strURL.lastIndexOf("."));
try {
if (strPath.equals(currentFilePath)) {
doDownloadTheFile(strPath);
}
currentFilePath = strPath;
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
// 執行下載
doDownloadTheFile(strPath);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 執行新版本進行下載,並安裝
*
* @param strPath
* @throws Exception
*/
private void doDownloadTheFile(String strPath) throws Exception {
Log.i(TAG, "getDataSource()");
// 判斷strPath是否為網路地址
if (!URLUtil.isNetworkUrl(strPath)) {
Log.i(TAG, "伺服器位址錯誤!");
} else {
URL myURL = new URL(strPath);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
if (is == null) {
throw new RuntimeException("stream is null");
}
//產生一個臨時檔案
File myTempFile = File.createTempFile(fileNa, "." + fileEx);
// 安裝包檔案臨時路徑
currentTempFilePath = myTempFile.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do {
int numread = is.read(buf);
if (numread <= 0) {
break;
}
fos.write(buf, 0, numread);
} while (true);
Log.i(TAG, "getDataSource() Download ok...");
dialog.cancel();
dialog.dismiss();
// 開啟檔案
openFile(myTempFile);
try {
is.close();
} catch (Exception ex) {
Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);
}
}
}
/**
* 開啟檔案進行安裝
*
* @param f
*/
private void openFile(File f) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
// 獲得下載好的檔案類型
String type = getMIMEType(f);
// 開啟各種類型檔案
intent.setDataAndType(Uri.fromFile(f), type);
// 安裝
activity.startActivity(intent);
}
/**
* 刪除臨時路徑裡的安裝包
*/
public void delFile() {
Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");
File myFile = new File(currentTempFilePath);
if (myFile.exists()) {
myFile.delete();
}
}
/**
* 獲得下載檔案的類型
*
* @param f
* 檔案名稱
* @return 檔案類型
*/
private String getMIMEType(File f) {
String type = "";
// 獲得檔案名稱
String fName = f.getName();
// 獲得副檔名
String end = fName
.substring(fName.lastIndexOf(".") + 1, fName.length())
.toLowerCase();
if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
type = "audio";
} else if (end.equals("3gp") || end.equals("mp4")) {
type = "video";
} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
|| end.equals("jpeg") || end.equals("bmp")) {
type = "image";
} else if (end.equals("apk")) {
type = "application/vnd.android.package-archive";
} else {
type = "*";
}
if (end.equals("apk")) {
} else {
type += "/*";
}
return type;
}
}