安裝APK 發送請求獲取輸入流 解析XML文件 可以開始下載 跟蹤下載進度 下載完畢啟動安裝 獲取項目包名 ...
安裝APK
public class DownLoadApk { public static SharedPreferences sharedPrederences = null; //啟動安裝界面 public static void DownId(Context context, long downId){ DownloadManager mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = mDownloadManager.getUriForDownloadedFile(downId); startInstall(context, downloadUri); } /** * 跳轉到安裝界面 * @param context 作用域 * @param uri 包名 */ private static void startInstall(Context context, Uri uri) { Intent install = new Intent(Intent.ACTION_VIEW); install.setDataAndType(uri, "application/vnd.android.package-archive"); install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(install); } //刪除文件 public static boolean fileDelete(String filePath) { File file = new File(filePath); if (file.exists() == false) { return false; } return file.delete(); }
發送請求獲取輸入流
Thread thread = new Thread() { @Override public void run() { super.run(); //XML存放在ftp伺服器的地址 String path = FileUtils.getDevice_address()+"News.XML"; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //發送http GET請求,獲取相應碼 if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); //使用pull解析器,開始解析這個流 parseNewsXml(is); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread.start();
解析XML文件
private void parseNewsXml(InputStream is) { XmlPullParser xp = Xml.newPullParser(); try { xp.setInput(is, "utf-8"); //對節點的事件類型進行判斷,就可以知道當前節點是什麼節點 int type = xp.getEventType(); News news = null; while (type != XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_TAG: if ("newslist".equals(xp.getName())) { newsList = new ArrayList<>(); break; } else if ("news".equals(xp.getName())) { news = new News(); break; } else if ("name".equals(xp.getName())) { String name = xp.nextText(); news.setName(name); break; } else if ("code".equals(xp.getName())) { String code = xp.nextText(); news.setCode(code); break; } case XmlPullParser.END_TAG: if ("news".equals(xp.getName())) { newsList.add(news); } break; default: break; } //解析完當前節點後,把指針移動至下一個節點,直至節點完畢,並返回它的事件類型 type = xp.next(); } // 發消息 handler.sendEmptyMessage(1); } catch (Exception e) { e.printStackTrace(); } }
可以開始下載
//獲取下載管理器 DownloadManager manager =(DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); News news = newsList.get(0); Log.i("aii", "XML: "+news.getCode()+",apk:"+getPackageInfo(mContext)); if(Integer.valueOf(news.getCode())>Integer.valueOf(getPackageInfo(mContext))){ if(dowmCliek) { //開啟進度條線程 isRun = true; dowmCliek = false; //更新APK前刪除原來的安裝包 DownLoadApk.fileDelete(path + "/" + mAPK); //創建下載請求 DownloadManager.Request down = new DownloadManager.Request( Uri.parse(mWebsite)); //設置允許使用的網路類型,這裡是移動網路和wifi都可以 down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); //禁止發出通知,既後臺下載 down.setShowRunningNotification(true); //不顯示下載界面 down.setVisibleInDownloadsUi(true); //標題 down.setDestinationInExternalFilesDir(mContext, null, "XXX升級中..."); //將下載請求放入隊列,返回下載id downId = manager.enqueue(down); }else{ Toast.makeText(mContext,"升級中...",Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(mContext,"已是最新版本無需升級...",Toast.LENGTH_SHORT).show(); } } };
跟蹤下載進度
//定時任務 ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { if(isRun) { Message msg = mHandler.obtainMessage(); msg.what = 1; mHandler.sendMessage(msg); } } }, 0, 100, TimeUnit.MILLISECONDS);//延遲0,間隔100,單位毫秒 private Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 1: //android下載管理器 DownloadManager.Query query = new DownloadManager.Query().setFilterById(downId); Cursor cursor = manager.query(query); if (cursor != null && cursor.moveToFirst()) { //此處直接查詢文件大小 long downSize = cursor.getLong(cursor.getColumnIndex( DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); //獲取文件下載總大小 fileTotalSize =cursor.getLong(cursor.getColumnIndex( DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); cursor.close(); Log.w("列印", "總大小" + downSize); Log.w("列印", "下載進度 " + fileTotalSize); if (fileTotalSize>0) { NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMaximumFractionDigits(2); String result = numberFormat.format((float)fileTotalSize/(float)downSize*100); Log.w("列印", "downloaded size: " + result+"%"); downBtn.setText(result+"%"); } //下載完畢 if(fileTotalSize==downSize) { isRun = false; downBtn.setText("點擊升級"); } } } return true; } });
下載完畢啟動安裝
DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); //下載完成後的廣播 class DownloadCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){ long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if(downId!=-1) { //啟動安裝 DownLoadApk.DownId(context,downId); dowmCliek=true; } }else{ Toast.makeText(context, intent.getAction()+"下載失敗", Toast.LENGTH_SHORT).show(); } } } //啟動下載完成廣播 mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
獲取項目包名
private static String getPackageInfo(Context context) { PackageInfo pi = null; try { PackageManager pm = context.getPackageManager(); pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS); return pi.versionCode+""; } catch (Exception e) { e.printStackTrace(); } return null; }