private String remoteurl = "http://jcw.591hx.com/djgnew/djgupdatefile/android_alert/hxsw_android_ver.txt";//這是一個伺服器端的地址的定義
private final String tempfile = "version_alet_time";
private String version;
1.
// 擷取裝置資訊
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imsi = tm.getSubscriberId();
String model = android.os.Build.MODEL;
String strDownFrom = null;
String strModel = null;
String strUrl = null;
PackageManager manager = this.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
strVersionText = info.versionName; // 本地存放的版本號碼
} catch (NameNotFoundException e) {
e.printStackTrace();
}
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(remoteurl);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
reader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
version = reader.readLine();//伺服器端存放的版本號碼
url = reader.readLine();//伺服器端存放的
Float remoteversion = Float.parseFloat(version);
Float localversion = Float.parseFloat(strVersionText);
if (remoteversion - localversion > 0.00001) {
long curtime = new Date().getTime();
long prevalerttime = readTimeFromFile();// 從檔案中讀取
if (curtime - prevalerttime > 7 * 24 * 3600 * 1000) {
//每七天進行一次彈框提示
new AlertDialog.Builder(HXStockWarningActivity.this)
.setMessage("當前有新版本,是否升級?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("確定",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
//這裡面可以根據自己的需要修改
setResult(RESULT_OK);// 確定按鈕事件
Uri uri = Uri.parse(url);
Intent intent = new Intent(
Intent.ACTION_VIEW, uri);
startActivity(intent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
}
}).show();
// 寫入檔案
writeTimeToFile(curtime);
}
}
}
} catch (Exception e) {
Log.e("HttpConnectionUtil", e.getMessage(), e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
2.
// 把版本升級彈框的時間寫入檔案
private void writeTimeToFile(long time) {
try {
FileOutputStream fout = openFileOutput(tempfile, MODE_PRIVATE);
byte[] bytes = Comm.LongToBytes(time);
fout.write(bytes);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 從檔案裡讀上一次版本彈框的時間
public long readTimeFromFile() {
long ress = 0;
try {
FileInputStream fin = openFileInput(tempfile);
byte[] buffer = new byte[8];
fin.read(buffer);
ress = Comm.BytesToLong(buffer, 0);
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
return ress;
}