(本文講解了在Android中實(shí)現(xiàn)APP版本更新,文末附有源碼。)
創(chuàng)新互聯(lián)自2013年起,先為太谷等服務(wù)建站,太谷等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為太谷企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
2.與后臺(tái)的交互
3.Android中Handler的使用
4.Android中ProgressDialog的使用
話不多說(shuō),先來(lái)看看效果圖:
package com.example.appupdatedemo; public class UpdateInfo { private String version; private String description; private String url; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package com.example.appupdatedemo; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import android.content.Context; public class UpdateInfoService { public UpdateInfoService(Context context) { } public UpdateInfo getUpDateInfo() throws Exception { String path = GetServerUrl.getUrl() + "/update.txt"; StringBuffer sb = new StringBuffer(); String line = null; BufferedReader reader = null; try { // 創(chuàng)建一個(gè)url對(duì)象 URL url = new URL(path); // 通過(guò)url對(duì)象,創(chuàng)建一個(gè)HttpURLConnection對(duì)象(連接) HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); // 通過(guò)HttpURLConnection對(duì)象,得到InputStream reader = new BufferedReader(new InputStreamReader( urlConnection.getInputStream())); // 使用io流讀取文件 while ((line = reader.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } String info = sb.toString(); UpdateInfo updateInfo = new UpdateInfo(); updateInfo.setVersion(info.split("&")[1]); updateInfo.setDescription(info.split("&")[2]); updateInfo.setUrl(info.split("&")[3]); return updateInfo; } }
package com.example.appupdatedemo; /** * 獲取服務(wù)器IP地址 */ public class GetServerUrl{ static String url="http://192.168.1.100:8080/PersonalHomePage"; //沒(méi)錯(cuò),我這里用的是本地的JAVAEE工程,各位根據(jù)實(shí)際情況修改。 public static String getUrl() { return url; } }
public class MainActivity extends Activity { // 更新版本要用到的一些信息 private UpdateInfo info; private ProgressDialog pBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast.makeText(MainActivity.this, "正在檢查版本更新..", Toast.LENGTH_SHORT).show(); // 自動(dòng)檢查有沒(méi)有新版本 如果有新版本就提示更新 new Thread() { public void run() { try { UpdateInfoService updateInfoService = new UpdateInfoService( MainActivity.this); info = updateInfoService.getUpDateInfo(); handler1.sendEmptyMessage(0); } catch (Exception e) { e.printStackTrace(); } }; }.start(); } @SuppressLint("HandlerLeak") private Handler handler1 = new Handler() { public void handleMessage(Message msg) { // 如果有更新就提示 if (isNeedUpdate()) { //在下面的代碼段 showUpdateDialog(); //下面的代碼段 } }; };
private void showUpdateDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("請(qǐng)升級(jí)APP至版本" + info.getVersion()); builder.setMessage(info.getDescription()); builder.setCancelable(false); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { downFile(info.getUrl()); //在下面的代碼段 } else { Toast.makeText(MainActivity.this, "SD卡不可用,請(qǐng)插入SD卡", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } private boolean isNeedUpdate() { String v = info.getVersion(); // 最新版本的版本號(hào) Log.i("update",v); Toast.makeText(MainActivity.this, v, Toast.LENGTH_SHORT).show(); if (v.equals(getVersion())) { return false; } else { return true; } } // 獲取當(dāng)前版本的版本號(hào) private String getVersion() { try { PackageManager packageManager = getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( getPackageName(), 0); return packageInfo.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); return "版本號(hào)未知"; } }
void downFile(final String url) { pBar = new ProgressDialog(MainActivity.this); //進(jìn)度條,在下載的時(shí)候?qū)崟r(shí)更新進(jìn)度,提高用戶友好度 pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pBar.setTitle("正在下載"); pBar.setMessage("請(qǐng)稍候..."); pBar.setProgress(0); pBar.show(); new Thread() { public void run() { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); int length = (int) entity.getContentLength(); //獲取文件大小 pBar.setMax(length); //設(shè)置進(jìn)度條的總長(zhǎng)度 InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; if (is != null) { File file = new File( Environment.getExternalStorageDirectory(), "Test.apk"); fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[10]; //這個(gè)是緩沖區(qū),即一次讀取10個(gè)比特,我弄的小了點(diǎn),因?yàn)樵诒镜?,所以?shù)值太大一 下就下載完了,看不出progressbar的效果。 int ch = -1; int process = 0; while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch); process += ch; pBar.setProgress(process); //這里就是關(guān)鍵的實(shí)時(shí)更新進(jìn)度了! } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } down(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } void down() { handler1.post(new Runnable() { public void run() { pBar.cancel(); update(); } }); } //安裝文件,一般固定寫(xiě)法 void update() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(Environment .getExternalStorageDirectory(), "Test.apk")), "application/vnd.android.package-archive"); startActivity(intent); }這一段主要是利用progressdialog在下載的時(shí)候?qū)崟r(shí)更新進(jìn)度,主要利用的是一個(gè)字節(jié)數(shù)組的緩沖區(qū)。即每次獲取到的內(nèi)容填滿緩沖區(qū)后就寫(xiě)入到本地本件中。這里我把緩沖區(qū)的大小設(shè)置為10個(gè)字節(jié)(1024會(huì)比較好),理由是因?yàn)樵谕粋€(gè)局域網(wǎng)中速度特別快,刷一下就下載完了,看不出進(jìn)度條效果,緩沖區(qū)調(diào)小點(diǎn)就OK了。
========================================
寫(xiě)在后面:
源代碼已上傳到我的Github,或者到CSDN下載區(qū)下載。
任何問(wèn)題,歡迎留言交流!