一、首先,參考了以下文章《Android自動檢測版本及自動升級》 http://www.linuxidc.com/Linux/2011-10/45718p2.htm: 步驟: 1.檢測當前版本的信息AndroidManifest.xml-->manifest-->android:versionName。 2.從服務器獲取版本號(版本號存在於xml文件中)並與當前檢測到的版本進行匹配,如果不匹配,提示用戶進行升級,如果匹配則進入程序主界面。 3.當提示用戶進行版本升級時,如果用戶點擊了確定,系統將自動從服務器上下載並進行自動升級,如果點擊取消將進入程序主界面。 [java] view plaincopy 獲取當前程序的版本號: 1./* 2. * 獲取當前程序的版本號 3. */ 4.private String getVersionName() throws Exception{ 5. //獲取packagemanager的實例 6. PackageManager packageManager = getPackageManager(); 7. //getPackageName()是你當前類的包名,0代表是獲取版本信息 8. PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0); 9. return packInfo.versionName; 10.} [java] view plaincopy 獲取服務器端的版本號: 1./* 2. * 用pull解析器解析服務器返回的xml文件 (xml封裝了版本號) 3. */ 4.public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{ 5. XmlPullParser parser = Xml.newPullParser(); 6. parser.setInput(is, "utf-8");//設置解析的數據源 7. int type = parser.getEventType(); 8. UpdataInfo info = new UpdataInfo();//實體 9. while(type != XmlPullParser.END_DOCUMENT ){ 10. switch (type) { 11. case XmlPullParser.START_TAG: 12. if("version".equals(parser.getName())){ 13. info.setVersion(parser.nextText()); //獲取版本號 14. }else if ("url".equals(parser.getName())){ 15. info.setUrl(parser.nextText()); //獲取要升級的APK文件 16. }else if ("description".equals(parser.getName())){ 17. info.setDescription(parser.nextText()); //獲取該文件的信息 18. } 19. break; 20. } 21. type = parser.next(); 22. } 23. return info; 24.} [java] view plaincopy 從服務器下載apk: 1.public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{ 2. //如果相等的話表示當前的sdcard掛載在手機上並且是可用的 3. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 4. URL url = new URL(path); 5. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 6. conn.setConnectTimeout(5000); 7. //獲取到文件的大小 8. pd.setMax(conn.getContentLength()); 9. InputStream is = conn.getInputStream(); 10. File file = new File(Environment.getExternalStorageDirectory(), "updata.apk"); 11. FileOutputStream fos = new FileOutputStream(file); 12. BufferedInputStream bis = new BufferedInputStream(is); 13. byte[] buffer = new byte[1024]; 14. int len ; 15. int total=0; 16. while((len =bis.read(buffer))!=-1){ 17. fos.write(buffer, 0, len); 18. total+= len; 19. //獲取當前下載量 20. pd.setProgress(total); 21. } 22. fos.close(); 23. bis.close(); 24. is.close(); 25. return file; 26. } 27. else{ 28. return null; 29. } 30.} 匹配、下載、自動安裝: [java] view plaincopy /* * 從服務器獲取xml解析並進行比對版本號 */ public class CheckVersionTask implements Runnable{ public void run() { try { //從資源文件獲取服務器 地址 String path = getResources().getString(R.string.serverurl); //包裝成url的對象 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); InputStream is =conn.getInputStream(); info = UpdataInfoParser.getUpdataInfo(is); if(info.getVersion().equals(versionname)){ Log.i(TAG,"版本號相同無需升級"); LoginMain(); }else{ Log.i(TAG,"版本號不同 ,提示用戶升級 "); Message msg = new Message(); msg.what = UPDATA_CLIENT; handler.sendMessage(msg); } } catch (Exception e) { // 待處理 Message msg = new Message(); msg.what = GET_UNDATAINFO_ERROR; handler.sendMessage(msg); e.printStackTrace(); } } } [java] view plaincopy Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case UPDATA_CLIENT: //對話框通知用戶升級程序 showUpdataDialog(); break; case GET_UNDATAINFO_ERROR: //服務器超時 Toast.makeText(getApplicationContext(), "獲取服務器更新信息失敗", 1).show(); LoginMain(); break; case DOWN_ERROR: //下載apk失敗 Toast.makeText(getApplicationContext(), "下載新版本失敗", 1).show(); LoginMain(); break; } } }; [java] view plaincopy /* * * 彈出對話框通知用戶更新程序 * * 彈出對話框的步驟: * 1.創建alertDialog的builder. * 2.要給builder設置屬性, 對話框的內容,樣式,按鈕 * 3.通過builder 創建一個對話框 * 4.對話框show()出來 */ protected void showUpdataDialog() { AlertDialog.Builder builer = new Builder(this) ; builer.setTitle("版本升級"); builer.setMessage(info.getDescription()); //當點確定按鈕時從服務器上下載 新的apk 然后安裝 builer.setPositiveButton("確定", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG,"下載apk,更新"); downLoadApk(); } }); //當點取消按鈕時進行登錄 builer.setNegativeButton("取消", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub LoginMain(); } }); AlertDialog dialog = builer.create(); dialog.show(); } [java] view plaincopy /* * 從服務器中下載APK */ protected void downLoadApk() { final ProgressDialog pd; //進度條對話框 pd = new ProgressDialog(this); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMessage("正在下載更新"); pd.show(); new Thread(){ @Override public void run() { try { File file = DownLoadManager.getFileFromServer(info.getUrl(), pd); sleep(3000); installApk(file); pd.dismiss(); //結束掉進度條對話框 } catch (Exception e) { Message msg = new Message(); msg.what = DOWN_ERROR; handler.sendMessage(msg); e.printStackTrace(); } }}.start(); } [java] view plaincopy //安裝apk protected void installApk(File file) { Intent intent = new Intent(); //執行動作 intent.setAction(Intent.ACTION_VIEW); //執行的數據類型 intent.setDataAndType(Uri.fromFile(file), "application/vnd.Android.package-archive");//編者按:此處Android應為android,否則造成安裝不了 startActivity(intent); } [java] view plaincopy /* * 進入程序的主界面 */ private void LoginMain(){ Intent intent = new Intent(this,MainActivity.class); startActivity(intent); //結束掉當前的activity this.finish(); } 二、參考后使用情況: 1.可以下載apk,但安裝失敗: 1)以為配置文件中需定義了android.permission.INSTALL_PACKAGES,其實不需; 2)以為是要在執行安裝的activity中配置 [html] view plaincopy <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> ,其實不是; 3)代碼中application/vnd.Android.package-archive有一個字母A大寫了,改小寫后解決;