監測是否需要升級:
PackageManager packageManager = MainActivity.getInstance().getPackageManager();PackageInfo packInfo;try{ packInfo = packageManager.getPackageInfo(MainActivity.getInstance().getPackageName(), 0); String version = packInfo.versionName; String serverVersion = NetSend.getInstance().getVersion(); ProjectMacro.apkVersion = version; if (!serverVersion.equals(version)) { showUpdataDialog(); }}catch (NameNotFoundException e){ e.printStackTrace();}
擷取伺服器版本:
public String getVersion(){ String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try { url = new URL(ProjectMacro.URL_VER_COM); connection = (HttpURLConnection)url.openConnection(); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString().trim(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
下載線程和自動安裝[分為:存在sdcard中的和存在手機記憶體中的]
private NotificationManager mNotificationManager; private Notification mNotification; private static final int HANDLER_MESSAGE_START_DOWNLOADING = 0; private static final int HANDLER_MESSAGE_IS_DOWNLOADING = 1; private static final int HANDLER_MESSAGE_DOWNLOAD_COMPLETE = 2; private static final int HANDLER_MESSAGE_INSTALL_COMPLETE = 3; private static final int CURRENT_NETWORK_ERROR = 10000; private DownloadThread thread = new DownloadThread(); private boolean isStopDownload; /** * DownloadBinder中定義了一些實用的方法 * * @author user * */ public class DownloadThread extends Thread { @Override public void run() { super.run(); startDownload(); } } private Handler mUpdateHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case HANDLER_MESSAGE_START_DOWNLOADING: setUpNotification(); break; case HANDLER_MESSAGE_IS_DOWNLOADING: setCurrentProgressInfo(msg.arg1, msg.arg2); break; case HANDLER_MESSAGE_DOWNLOAD_COMPLETE: setUpOkNotification(); thread.interrupt(); Toast.makeText(MainActivity.getInstance(), "下載完成!", Toast.LENGTH_SHORT).show(); break; case HANDLER_MESSAGE_INSTALL_COMPLETE: break; case CURRENT_NETWORK_ERROR: if (thread != null) { thread.interrupt(); } showToast("網路異常", 2); break; default: break; } }; }; /** * 設定當前進度資訊 * * @param currentProgress * @param totalSize */ private void setCurrentProgressInfo(int currentProgress, int totalSize) { // 更新進度 RemoteViews contentView = mNotification.contentView; contentView.setTextViewText(R.id.download_file_tempsize, "" + currentProgress + "Kb"); contentView.setTextViewText(R.id.download_file_size, "" + totalSize + "Kb"); contentView.setProgressBar(R.id.download_file_progressBar, 100, (int)(currentProgress * 100 / totalSize), false); mNotificationManager.notify(R.string.app_name, mNotification); } /** * 設定下載通知 */ private void setUpNotification() { mNotificationManager = (NotificationManager)MainActivity.getInstance().getSystemService(Context.NOTIFICATION_SERVICE); mNotification = new Notification(R.drawable.ic_launcher, "正在下載", System.currentTimeMillis()); mNotification.flags = Notification.FLAG_ONGOING_EVENT; RemoteViews rv = new RemoteViews(MainActivity.getInstance().getPackageName(), R.layout.update_download_apk_progressbar); mNotification.contentView = rv; Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.getInstance(), R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT); mNotification.contentIntent = contentIntent; mNotificationManager.notify(R.string.app_name, mNotification); } /** * 下載完成 */ private void setUpOkNotification() { mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotification.contentView = null; File file = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //sdCard存在,升級APK放在sdCard中 file = new File(Environment.getExternalStorageDirectory(), "MIQ.apk"); } else { //sdCard不存在, 升級APK放在本機存放區中 file = new File(getCacheDir().getAbsolutePath() + File.separator + "download", "MIQ.apk"); } Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setComponent(new ComponentName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity")); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.getInstance(), R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT); mNotification.contentIntent = contentIntent; mNotification.setLatestEventInfo(MainActivity.getInstance(), "下載完成", "檔案已下載完畢", contentIntent); mNotificationManager.notify(R.string.app_name, mNotification); } /** * 下載模組 */ private void startDownload() { Message msg = mUpdateHandler.obtainMessage(); msg.what = HANDLER_MESSAGE_START_DOWNLOADING; msg.arg1 = 0; mUpdateHandler.sendMessage(msg); HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 1000 * 60); HttpConnectionParams.setSoTimeout(httpParams, 1000 * 60); ConnManagerParams.setTimeout(httpParams, 1000 * 60); HttpGet get = new HttpGet(ProjectMacro.URL_DOWN_COM); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); Log.i("DownLoadNewAppSer", "length is " + length); InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; File file = null; if (is != null) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //sdCard存在 file = new File(Environment.getExternalStorageDirectory(), "MIQ.apk"); } else { //sdCard不存在 String apkPath = getCacheDir().getAbsolutePath() + File.separator + "download"; String apkName = "MIQ.apk"; file = new File(apkPath, apkName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } } fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[2048]; int ch = -1; int count = 0; long startTime = System.currentTimeMillis(); while ((ch = is.read(buf)) != -1) { if (!NetUtil.checkNet(MainActivity.getInstance())) { msg.what = CURRENT_NETWORK_ERROR; mUpdateHandler.sendMessage(msg); return; } long endTime = System.currentTimeMillis(); fileOutputStream.write(buf, 0, ch); count += ch; // ------ 下載完成一點發送Message通知handler更新下進度 if (isStopDownload != true) { if (endTime - startTime > 1000) { // 一秒種更新一次 msg = mUpdateHandler.obtainMessage(); msg.what = HANDLER_MESSAGE_IS_DOWNLOADING; msg.arg1 = (count / 1024); msg.arg2 = (int)(length / 1024); mUpdateHandler.sendMessage(msg); startTime = endTime; } isStopDownload = false; } } String permission = "755"; // 下載的檔案夾要具有RX許可權(可以進入檔案夾的前提) String filesCom = "chmod " + permission + " " + file.getParentFile().getAbsolutePath(); // 下載的檔案apk為android的應用程式 需要具有x的許可權,也就是可執行檔許可權,才能安裝 String apkComm = "chmod " + permission + " " + file.getAbsolutePath(); // String apkComm = "chmod -R " + permission + " " + apkPath + "/" // + apkName;//不支援 -R選項 Runtime runtime = Runtime.getRuntime(); runtime.exec(filesCom); runtime.exec(apkComm); } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } // ------下載完成發送Message通知handler if (isStopDownload != true) { msg = mUpdateHandler.obtainMessage(); msg.what = HANDLER_MESSAGE_DOWNLOAD_COMPLETE; mUpdateHandler.sendMessage(msg); isStopDownload = false; } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } protected void showUpdataDialog() { AlertDialog.Builder builer = new Builder(MainActivity.getInstance()); builer.setTitle("版本升級"); builer.setMessage("檢測到最新版本,請及時更新"); builer.setPositiveButton("確定", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { thread.start(); } }); builer.setNegativeButton("取消", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builer.create(); builer.show(); }
update_download_apk_progressbar.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/download_file_progress_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:background="@drawable/ic_launcher" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="3dp" android:text="下載新版本中" android:textColor="#FFFFFF" android:textSize="16sp" /> <LinearLayout android:id="@+id/downloud_progress_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/text" > <TextView android:id="@+id/download_file_tempsize" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="3dp" android:text="0 kb" android:textColor="#FFFFFF" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:text="/" android:textColor="#FFFFFF" /> <TextView android:id="@+id/download_file_size" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0 kb" android:textColor="#FFFFFF" /> </LinearLayout> <ImageButton android:id="@+id/stop_download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="120dp" android:background="@drawable/stop_download_btn" android:visibility="gone" /> </RelativeLayout> <ProgressBar android:id="@+id/download_file_progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="240dp" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="3dp" android:progressDrawable="@drawable/download_progressbar" /> </LinearLayout></LinearLayout>
添加許可權:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_OWNER_DATA" />