summaryrefslogtreecommitdiff
authorTing Li <ting.li@amlogic.com>2016-11-16 11:46:28 (GMT)
committer Ting Li <ting.li@amlogic.com>2016-11-16 11:46:54 (GMT)
commit20aa906d4c178a85d2f9b950789bc1669649afd9 (patch)
treef2b90ae365dc1db5db4cf60538469b06a229560e
parent13c5f8962a0882dc76a5bdc12baa081a0373e559 (diff)
downloadOTAUpgrade2-20aa906d4c178a85d2f9b950789bc1669649afd9.zip
OTAUpgrade2-20aa906d4c178a85d2f9b950789bc1669649afd9.tar.gz
OTAUpgrade2-20aa906d4c178a85d2f9b950789bc1669649afd9.tar.bz2
pd#134964 use data store update file when file size is more than 460M
Change-Id: I2a9d3fb0de57db6d75d252cbf702a6d2e9685a6f
Diffstat
-rw-r--r--AndroidManifest.xml1
-rw-r--r--libs/libotaupdate.jar4376
-rw-r--r--res/values-zh-rCN/strings.xml3
-rw-r--r--res/values/strings.xml3
-rw-r--r--src/com/droidlogic/otaupgrade/InstallPackage.java7
-rw-r--r--src/com/droidlogic/otaupgrade/LoaderReceiver.java4
-rw-r--r--src/com/droidlogic/otaupgrade/MainActivity.java3
-rw-r--r--src/com/droidlogic/otaupgrade/PrefUtils.java20
-rw-r--r--[-rwxr-xr-x]src/com/droidlogic/otaupgrade/UpdateActivity.java42
-rw-r--r--src/com/droidlogic/otaupgrade/UpdateService.java4
10 files changed, 4074 insertions, 389 deletions
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 0dffbb8..2c8bd3e 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.droidlogic.otaupgrade"
android:versionCode="2"
+ android:sharedUserId="android.uid.system"
android:versionName="2.0201411271418" >
<uses-permission android:name="android.permission.BACKUP" />
diff --git a/libs/libotaupdate.jar b/libs/libotaupdate.jar
index f41aa4d..a7e1d0a 100644
--- a/libs/libotaupdate.jar
+++ b/libs/libotaupdate.jar
@@ -1,9 +1,9 @@
-PK
-
+PK
+
SourceFile
-
+
@@ -72,46 +72,289 @@ I

-
+
+ * Description:
+ *
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+package com.amlogic.update;
+
+import android.app.backup.BackupManager;
+import android.app.backup.IBackupManager;
+import android.content.Context;
+import android.os.Build;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.Build.VERSION;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+
+import com.amlogic.update.util.PrefUtil;
+import com.amlogic.update.util.UpgradeInfo;
+
+public final class Backup {
+ private boolean DEBUG = false || UpgradeInfo.isDebugAble();
+ private IBackupConfirmListener mConfirmListener;
+ static final String TAG = PrefUtil.TAG;
+ static String[] mArgs;
+ int mNextArg;
+ private IBinder mIBinder;
+ private IBackupManager mBackupManager;
+ private Context mCxt;
+
+ public Backup(Context cxt) {
+ mCxt = cxt;
+ }
+
+ public void setConfirmListener(IBackupConfirmListener confirmlistener) {
+ mConfirmListener = confirmlistener;
+ }
+
+ public void main(String[] args) {
+ if (DEBUG)
+ Log.d(TAG, "Beginning: " + args[0]);
+ mArgs = args;
+ try {
+ // new Backup().
+ run();
+ } catch (Exception e) {
+ if (DEBUG)
+ Log.e(TAG, "Error running backup/restore", e);
+ }
+ if (DEBUG)
+ Log.d(TAG, "Finished.");
+ }
+
+ String mFileName = null;
+
+ public void run() {
+ mBackupManager = IBackupManager.Stub.asInterface(ServiceManager.getService("backup"));
+ if (mBackupManager == null) {
+ if (DEBUG)
+ Log.e(TAG, "Can't obtain Backup Manager binder");
+ return;
+ }
+ mFileName = nextArg();
+ int socketFd = 0; // Integer.parseInt(nextArg());
+ String arg = nextArg();
+ if (arg.equals("backup")) {
+ doFullBackup(socketFd);
+ } else if (arg.equals("restore")) {
+ doFullRestore(socketFd);
+ } else {
+ if (DEBUG)
+ Log.e(TAG, "Invalid operation '" + arg + "'");
+ }
+ }
+
+ private void doFullBackup(int socketFd) {
+ ArrayList<String> packages = new ArrayList<String>();
+ boolean saveApks = true;
+ boolean saveObbs = false;
+ boolean saveShared = false;
+ boolean doEverything = true;
+ boolean allIncludesSystem = true;
+ String arg;
+ while ((arg = nextArg()) != null) {
+ if (arg.startsWith("-")) {
+ if ("-apk".equals(arg)) {
+ saveApks = true;
+ } else if ("-noapk".equals(arg)) {
+ saveApks = false;
+ } else if ("-obb".equals(arg)) {
+ saveObbs = true;
+ } else if ("-noobb".equals(arg)) {
+ saveObbs = false;
+ } else if ("-shared".equals(arg)) {
+ saveShared = true;
+ } else if ("-noshared".equals(arg)) {
+ saveShared = false;
+ } else if ("-system".equals(arg)) {
+ allIncludesSystem = true;
+ } else if ("-nosystem".equals(arg)) {
+ allIncludesSystem = false;
+ } else if ("-all".equals(arg)) {
+ doEverything = true;
+ } else {
+ Log.w(TAG, "Unknown backup flag " + arg);
+ continue;
+ }
+ } else {
+ // Not a flag; treat as a package name
+ packages.add(arg);
+ }
+ }
+ if (doEverything && packages.size() > 0) {
+ if (DEBUG)
+ Log.w(TAG, "-all passed for backup along with specific package names");
+ }
+ if (!doEverything && !saveShared && packages.size() == 0) {
+ if (DEBUG)
+ Log.e(TAG, "no backup packages supplied and neither -shared nor -all given");
+ return;
+ }
+ // try {
+ ParcelFileDescriptor fd = null;
+ try {
+ fd = ParcelFileDescriptor.open(new File(mFileName),
+ ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_READ_WRITE);
+ Log.d(TAG, "param: saveApks " + saveApks + "saveObbs " + saveObbs + " saveShared " + saveShared
+ + " fd==null" + (fd == null));
+ String[] packArray = new String[packages.size()];
+ try {
+ Method getbuMethod = null;
+ Log.d("tt", "android.os.version:" + android.os.Build.VERSION.SDK_INT);
+ if (android.os.Build.VERSION.SDK_INT < 21) {
+ getbuMethod = getbuMethod = Class.forName("android.app.backup.IBackupManager")
+ .getMethod("fullBackup", new Class[] { ParcelFileDescriptor.class, boolean.class,
+ boolean.class, boolean.class, boolean.class, boolean.class, String[].class });
+ getbuMethod.invoke(mBackupManager, fd, saveApks, saveObbs, saveShared, doEverything,
+ allIncludesSystem, (Object) (packages.toArray(packArray)));
+ } else {
+ getbuMethod = getbuMethod = Class.forName("android.app.backup.IBackupManager")
+ .getMethod("fullBackup",
+ new Class[] { ParcelFileDescriptor.class, boolean.class, boolean.class,
+ boolean.class, boolean.class, boolean.class, boolean.class, boolean.class,
+ String[].class });
+ getbuMethod.invoke(mBackupManager, fd, saveApks, saveObbs, saveShared, doEverything,
+ allIncludesSystem, allIncludesSystem, true, /* compress */
+ (Object) (packages.toArray(packArray)));
+
+ }
+ } catch (NoSuchMethodException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (SecurityException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (ClassNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalArgumentException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ /*
+ * mBackupManager.fullBackup(fd, saveApks, saveObbs, saveShared,
+ * doEverything, allIncludesSystem, allIncludesSystem,
+ * allIncludesSystem, packages.toArray(packArray));
+ */
+ } catch (FileNotFoundException e) {
+ Log.e(TAG, "file not found ", e);
+ } finally {
+ if (fd != null) {
+ try {
+ fd.close();
+ } catch (IOException e) {
+ }
+ }
+ if (mConfirmListener != null) {
+ mConfirmListener.onBackupComplete();
+ }
+ }
+ /*
+ * } catch (RemoteException e) { Log.e(TAG,
+ * "Unable to invoke backup manager for backup"); }
+ */
+ }
+
+ private void doFullRestore(int socketFd) {
+ // No arguments to restore
+ ParcelFileDescriptor fd = null;
+ try {
+ fd = ParcelFileDescriptor.open(new File(mFileName),
+ ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_READ_WRITE);
+ // ParcelFileDescriptor fd = ParcelFileDescriptor.adoptFd(socketFd);
+ mBackupManager.fullRestore(fd);
+ } catch (FileNotFoundException e) {
+ Log.e(TAG, "file not found ", e);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Unable to invoke backup manager for restore");
+ } finally {
+ if (fd != null) {
+ try {
+ fd.close();
+ } catch (IOException e) {
+ }
+ }
+ if (mConfirmListener != null) {
+ mConfirmListener.onRestoreComplete();
+ }
+ }
+ }
+
+ private String nextArg() {
+ if (mNextArg >= mArgs.length) {
+ return null;
+ }
+ String arg = mArgs[mNextArg];
+ mNextArg++;
+ return arg;
+ }
+
+ public interface IBackupConfirmListener {
+ public void onBackupComplete();
+
+ public void onRestoreComplete();
+ }
+}
+PK
+
SourceFile
-
+
SourceFile
*+
-*
+*
-
-L
+
+*
-
+
-
+
updateSize
-
-deleteSize
+
+deleteSize
SourceFile
*+
-*
+*
-
+
*
-
-
-Y
+
+
+Y
-
-Y
+
+Y
-
+
-
+
downloader
@@ -128,240 +371,1132 @@ mErrorCode
-
-
-doDownload
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Exceptions
- "!
- & #$
- * (
- - +
-
-
-
-
-
+
+
+
+
+doDownload
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Exceptions#
+%'&
+%+ ()
+%/ -
+%2 0
+%
+
+
+
+
SourceFile
-
+
-
-:
-*
-
-
-*
-*
-*
-
-
+
+:
+*
+
+
+*
+*
+*
+
+
+ * Description: Main Download Thread, get Download Tasks from db, executing
+ * Download ordinal
+ *
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ * @time: 2013-2-15
+ */
+package com.amlogic.update;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.amlogic.update.util.DownFileDao;
+import com.amlogic.update.util.DownFilesInfo;
+import com.amlogic.update.util.DownloadUtil;
+import com.amlogic.update.util.PrefUtil;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Color;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+import android.view.LayoutInflater;
+
+/**
+ * @ClassName DownloadUpdateTask
+ * @Description Download Update files from Server
+ * @see UpdateTasks
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+public class DownloadUpdateTask extends UpdateTasks {
+ private static final String TAG = PrefUtil.TAG;
+ public static final int ERROR_NETWORK_UNAVAIBLE = 1;
+ public static final int ERROR_UNKNOWN = 2;
+ public static final int ERROR_IOERROR = 3;
+ private Notifier notifier;
+ private Context mContext;
+ private PrefUtil mPrefs;
+ private DownFileDao dao;
+ private DownFilesInfo curTask = null;
+ private DownloadUtil downloader = null;
+ private String targetString = "";
+ private DownloadSize mDownSize = null;
+ private CheckPathCallBack mcheckTaskCallback;
+
+ /**
+ * Constructs a object of DownloadUpdateTask for Download Update Files
+ *
+ * @param mContext
+ */
+ public DownloadUpdateTask(Context mContext) {
+ this.mContext = mContext;
+ mPrefs = new PrefUtil(mContext);
+ mDownSize = new DownloadSize();
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ dao = new DownFileDao(mContext);
+ }
+
+ public void setErrorCode(int err) {
+ mErrorCode = err;
+ }
+
+ public void setCallbacks(CheckPathCallBack callback) {
+ mcheckTaskCallback = callback;
+ }
+
+ @Override
+ protected void onRunning() {
+ super.onRunning();
+ List<DownFilesInfo> tasks = dao.getDowntasks();
+ for (DownFilesInfo t : tasks) {
+ t.setLocal(mcheckTaskCallback.onExternalPathSwitch(t.getLocal()));
+ }
+ boolean errOccur = false;
+ if (tasks.size() > 0 && mRunningStatus == RUNNING_STATUS_RUNNING) {
+ curTask = tasks.get(0);
+ downloader = new DownloadUtil(mDownSize, mContext, this);
+ Log.d(TAG, "CurTask:" + curTask.toString());
+ do {
+ if (mRunningStatus == RUNNING_STATUS_UNSTART) {
+ break;
+ } else if (mRunningStatus == RUNNING_STATUS_PAUSE) {
+ try {
+ Thread.sleep(3000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ } else {
+ if (doDownload(downloader)) {
+ tasks.remove(0);
+ errOccur = false;
+ if (tasks.size() > 0 && mRunningStatus == RUNNING_STATUS_RUNNING) {
+ curTask = tasks.get(0);
+ downloader = new DownloadUtil(mDownSize, mContext, this);
+ }
+ } else {
+ errOccur = true;
+ continue;
+ }
+ }
+ } while (tasks.size() > 0
+ && (mRunningStatus == RUNNING_STATUS_RUNNING || mRunningStatus == RUNNING_STATUS_PAUSE));
+ }
+ if (mRunningStatus == RUNNING_STATUS_RUNNING || mRunningStatus == RUNNING_STATUS_FINISH) {
+ if (tasks.size() == 0 && !errOccur) {
+ mRunningStatus = RUNNING_STATUS_FINISH;
+ mErrorCode = NO_ERROR;
+ mResult = new DownloadResult();
+ if (notifier != null) {
+ notifier.Successnotify();
+ }
+ } else {
+ mRunningStatus = RUNNING_STATUS_FINISH;
+ mErrorCode = ERROR_UNKNOWN;
+ if (notifier != null) {
+ notifier.Failednotify();
+ }
+ }
+ mPrefs.setDownloadPos(0);
+ mProgress = 0;
+ }
+ }
+
+ private boolean doDownload(DownloadUtil download) {
+ int ret = -1;
+ while (mRunningStatus == RUNNING_STATUS_PAUSE) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ try {
+ ret = download.Save2File(curTask.url, curTask.local, curTask.name, curTask.md5);
+ Log.d(TAG, "ret:" + ret);
+ } catch (Exception e) {
+ mRunningStatus = RUNNING_STATUS_FINISH;
+ e.printStackTrace();
+ } finally {
+ if (PrefUtil.DEBUG)
+ Log.d(TAG, "ret is " + ret + " mRunningStatus" + mRunningStatus);
+ if (ret == 0) {
+ dao.delFile(curTask.local);
+ download.delete(curTask.url);
+ return true;
+ } else if (ret == -1) {
+ /*
+ * if(downloader != null && downloader.isdownloading()) {
+ * downloader.pause(); }
+ */
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return false;
+ } else {
+ if (downloader != null && downloader.isdownloading()) {
+ downloader.pause();
+ }
+ return false;
+ }
+ }
+ }
+
+ /**
+ * return path of update file for execute update
+ *
+ * @return set Notifier object to Download work thread.
+ * @param null
+ */
+ public void setNotify(Notifier notifier) {
+ this.notifier = notifier;
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ if (downloader != null && downloader.isdownloading()) {
+ downloader.pause();
+ }
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (downloader != null) {
+ downloader.resume();
+ }
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ if (downloader != null && downloader.isdownloading()) {
+ downloader.stop();
+ }
+ }
+
+ @Override
+ protected Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return super.equals(o);
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ super.finalize();
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return super.toString();
+ }
+
+ public class DownloadSize {
+ /*
+ * private int length; private int TimeoutException = 0;
+ */
+
+ void DownloadSize() {
+ getSavedSize();
+ }
+
+ void getSavedSize() {
+ mProgress = (int) mPrefs.getDownloadPos();
+ }
+ /*
+ * void saveInitSize() { mPrefs.setDownloadPos(length); }
+ */
+
+ public void updateSize(int downSize) {
+ synchronized (this) {
+ mProgress += downSize;
+ mPrefs.setDownloadPos(mProgress);
+ }
+ }
+
+ public void deleteSize(long urlTotalSize) {
+ synchronized (this) {
+ mProgress -= urlTotalSize;
+ mPrefs.setDownloadPos(mProgress);
+ }
+ }
+ /*
+ * int getDownloadSize() { synchronized (this) { return length; } }
+ */
+ }
+
+ /**
+ * @ClassName CheckUpdateResult
+ * @Description inner class of CheckUpdateTask to return Check Result by
+ * getResult()
+ * @see UpdateTasks
+ * @see CheckUpdateResult
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+ public class DownloadResult {
+ /**
+ * return Set of Update Download Files
+ *
+ * @return Set<String> update Files set
+ * @param null
+ */
+ public Set<String> getFilesList() {
+ if (mPrefs != null) {
+ return mPrefs.getDownFileSet();
+ }
+ return null;
+ }
+
+ }
+
+ @Override
+ protected void onReset() {
+ super.onReset();
+ dao.cleardata();
+ mPrefs.resetAll();
+ }
+
+ @Override
+ public long getProgress() {
+ return mPrefs.getDownloadPos();
+ };
+
+ /* interface for file path switch */
+ public interface CheckPathCallBack {
+ public String onExternalPathSwitch(String filePath);
+ }
+}
+PK
+

SourceFile
-
+
+/**
+ * @Package
+ * @Description
+ *
+ * Copyright (c) Inspur Group Co., Ltd. Unpublished
+ *
+ * Inspur Group Co., Ltd.
+ * Proprietary & Confidential
+ *
+ * This source code and the algorithms implemented therein constitute
+ * confidential information and may comprise trade secrets of Inspur
+ * or its associates, and any use thereof is subject to the terms and
+ * conditions of the Non-Disclosure Agreement pursuant to which this
+ * source code was originally received.
+ */
+/**
+ * @ClassName Notifier
+ * @Description
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+public interface Notifier{
+ public void Successnotify();
+ public void Failednotify();
+}PK
+
-SourceFile
+SourceFile
*+
-*
+*
+
-
-
-
-
+
+
+
+
-
-
-update.xml
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-*,+
-
-
-
-
+
+updatename
+
+update.xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+-/.
+
+
+
+
-
-mErrorCodeQ
-SUT
-
-httpClient
-
-
-
-
-
-
-
-
- 
- 
- 
-
-
- 
-
- 
- 
+
+mErrorCodeT
+VXW
+
+httpClient
+
+
+
+
+
+
+
+
+ 
+ 
+ 
+
+
+ 
+
+ 
+ 
disconnect
- 
-U
-
-
+ 
+X
+
+
initrecord
-
-
-
- 
-
-
-3
-6
-update.zipO
-6
-3R ST
-3X YZ
-3d eZ
-storagememk
-
-
-S 
-
-
-
-
-
-domBuilder
-updatename
+
+
+
+ 
+
+
+ 
+6
+9
+update.zipR
+9
+6U VW
+6[ \]
+6g h]
+storagememn
+
+
+
+V 
+
+
+
+
+
+
+domBuilder
nodelist_1
-nodelist_2
-
-
-
-
-
-
-
-SourceFile
+nodelist_2
+
+ 
+6 
+
+startsWith
+
+
+
+
+
+
+
+
+
+SourceFile
-
-
-
-
-
-,
-
-
-
-
-
-K"W*M
-
-[
-
-
-
-
-
- 6
-
- Y6  
-
-ŸW*e
-ŸW*e 
-ŸW*e
-
-
-"W*M*
-
-
-
-
-
-=:
-
-
-
-
-
-
-p6
-r6
-
-
-U
- 
-
-
-
-
-
-
+
+
+
+
+,
++
+
+
+
+
+
+N%W*P
+
+^
+
+
+
+
+
+ 6
+
+ Y6  
+
+ȸW*e
+ȸW*e 
+ȸW*e
+
+
+%W*P*
+
+:6
+
+
+<TW
+Z9:
+
+
+<fW
+
+<TW
+
+oW
+
+*
+{
+
+
+?@A+B4CMDTEmMNOPUVWXZ([1]7^R__atcdefghgijk ln o&pAqNt^ulvwx{|}~?&,5:?DENiu
+l
+
+
+
+
+
+
+
+
+
+
+
+ * @Package com.amlogic.update
+ * @Description Copyright (c) Inspur Group Co., Ltd. Unpublished Inspur Group
+ * Co., Ltd. Proprietary & Confidential This source code and the
+ * algorithms implemented therein constitute confidential
+ * information and may comprise trade secrets of Inspur or its
+ * associates, and any use thereof is subject to the terms and
+ * conditions of the Non-Disclosure Agreement pursuant to which
+ * this source code was originally received.
+ */
+package com.amlogic.update;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.util.EntityUtils;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import com.amlogic.update.util.DownFileDao;
+import com.amlogic.update.util.DownFilesInfo;
+import com.amlogic.update.util.PrefUtil;
+import com.amlogic.update.util.UpdatePositionStage;
+import com.amlogic.update.util.UpgradeInfo;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Handler;
+import android.util.Log;
+
+/**
+ * @ClassName CheckUpdateTask
+ * @Description Check for an new Update version, returns the updated information
+ * @see UpdateTasks
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+public class CheckUpdateTask extends UpdateTasks {
+ private static boolean DEBUG = true || UpgradeInfo.isDebugAble();
+ private static final String TAG = PrefUtil.TAG;
+ private static final boolean CHECK_DEBUG = PrefUtil.DEBUG;
+ public static final int ERROR_UNDISCOVERY_NEW_VERSION = 1;
+ public static final int ERROR_NETWORK_UNAVAIBLE = 2;
+ public static final int ERROR_UNKNOWN = 3;
+ private Context mContext;
+ private PrefUtil mPreferences;
+ private UpgradeInfo mUtil;
+ private DownFileDao dao;
+ private static final int HANDLE_XML_DOWNLOAD_FINISH = 100;
+ private static final int HANDLE_XML_DOWNLOAD_FAIL = 101;
+ private static final int CHECK_TIMEOUT = 20 * 1000;
+ public static String XML_NAME = "ota_update.xml";
+ public static String FILE_NAME = "update.xml";
+ private static String XmlDir = null;
+ private static final String OTA_COMMAND = "update_with_inc_ota";
+ private static final String SCRIPT_COMMAND = "update_with_script";
+ private Notifier notifier = null;
+ private String mCustomData = null;
+ private String updatename = null;
+ // private CheckPathCallBack mcheckTaskCallback;
+ /**
+ * Constructs a object of CheckUpdateTask for Check Update Work Thread
+ *
+ * @param mContext
+ */
+ public CheckUpdateTask(Context mContext) {
+ this.mContext = mContext;
+ XmlDir = mContext.getFilesDir().getAbsolutePath();
+ mPreferences = new PrefUtil(mContext);
+ mUtil = new UpgradeInfo(mContext);
+ dao = new DownFileDao(mContext);
+ mResult = new CheckUpdateResult();
+ }
+
+ /*
+ * public void setCallbacks(CheckPathCallBack callback){ mcheckTaskCallback
+ * = callback; }
+ */
+ @Override
+ protected void onStart() {
+ super.onStart();
+ }
+
+ public void setCustomRequestData(String val) {
+ mCustomData = val;
+ }
+
+ public void setCustomUrl(String url) {
+ if (!url.isEmpty()) {
+ UpgradeInfo.postUrl = url;
+ }
+ }
+
+ @Override
+ protected void onRunning() {
+ super.onRunning();
+ sendPost();
+ }
+
+ private void sendPost() {
+ if (DEBUG)
+ Log.v(TAG, "send post to server");
+ HttpPost post = new HttpPost(UpgradeInfo.postUrl);
+ List<NameValuePair> params = new ArrayList<NameValuePair>();
+ params.add(new BasicNameValuePair("updating_apk_version", UpgradeInfo.updating_apk_version));
+ params.add(new BasicNameValuePair("brand", UpgradeInfo.brand));
+ params.add(new BasicNameValuePair("device", UpgradeInfo.device));
+ params.add(new BasicNameValuePair("board", UpgradeInfo.board));
+ params.add(new BasicNameValuePair("mac", UpgradeInfo.mac));
+ params.add(new BasicNameValuePair("firmware", UpgradeInfo.firmware));
+ params.add(new BasicNameValuePair("android", UpgradeInfo.android));
+ params.add(new BasicNameValuePair("time", UpgradeInfo.time));
+ params.add(new BasicNameValuePair("builder", UpgradeInfo.builder));
+ params.add(new BasicNameValuePair("fingerprint", UpgradeInfo.fingerprint));
+ params.add(new BasicNameValuePair("id", mPreferences.getID() + ""));
+ if (mCustomData != null) {
+ String[] custom = mCustomData.split("&");
+ for (int i = 0; i < custom.length; i++) {
+ String[] data = custom[i].split("=");
+ params.add(new BasicNameValuePair(data[0], data[1]));
+ }
+ }
+ if (DEBUG)
+ Log.d(TAG, params.toString());
+ HttpParams httpParameters = new BasicHttpParams();
+ HttpConnectionParams.setSoTimeout(httpParameters, CHECK_TIMEOUT);
+ HttpClient httpClient = new DefaultHttpClient(httpParameters);
+ try {
+ post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
+ HttpResponse response = httpClient.execute(post);
+ if (DEBUG)
+ Log.i(TAG, "response status: " + response.getStatusLine().getStatusCode());
+ if (response.getStatusLine().getStatusCode() < 400 && response.getStatusLine().getStatusCode() >= 200) {
+ HttpEntity entity = response.getEntity();
+ String msg = EntityUtils.toString(entity);
+ if (DEBUG)
+ Log.i(TAG, "get data: " + msg);
+ String url[] = msg.split("=");
+ Log.i(TAG, "get data: " + url.length + "url:" + url[0]);
+ if (url.length == 2 && url[0].equals("url") && url[1].length() > 10) {
+ if (DEBUG)
+ Log.i(TAG, "xml url:" + url[1]);
+ url[1] = url[1].replace(" ", "");
+ url[1] = url[1].replace("\r\n", "");
+ downloadXML(url[1], XML_NAME);
+ } else {
+ if (DEBUG)
+ Log.i(TAG, "Can'n find new firmware");
+ mErrorCode = ERROR_UNDISCOVERY_NEW_VERSION;
+ }
+ } else {
+ mErrorCode = ERROR_UNKNOWN;
+ }
+ } catch (Exception ex) {
+ mErrorCode = ERROR_UNKNOWN;
+ if (DEBUG) {
+ Log.d(TAG, "download err...." + ex.fillInStackTrace());
+ }
+ }
+ if (DEBUG)
+ Log.v(TAG, "finish send post to server");
+ }
+
+ private void downloadXML(String url, String xmlName) {
+ if (DEBUG)
+ Log.i(TAG, "start download a xml file:" + xmlName + " url:" + url);
+ mPreferences.resetAll();
+ if (XmlDir == null)
+ return;
+ File dir = new File(XmlDir);
+ File file = new File(XmlDir + "/" + xmlName);
+ if (DEBUG)
+ Log.i(TAG, "dir:" + dir.getAbsolutePath() + " exixts:" + dir.exists() + " mkdir:" + dir.mkdirs() + "file:"
+ + file.getAbsolutePath());
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ if (file.exists()) {
+ file.delete();
+ }
+ FileOutputStream xmlfile = null;
+ int filesize = 0;
+ int readSize = 0;
+ try {
+ URL Url = new URL(url);
+ HttpURLConnection cn = (HttpURLConnection) Url.openConnection();
+ InputStream input = cn.getInputStream();
+ filesize = cn.getContentLength();
+ if (filesize <= 0 || input == null) {
+ mErrorCode = ERROR_UNKNOWN;
+ handleDownloadResult(HANDLE_XML_DOWNLOAD_FAIL, null);
+ }
+ xmlfile = new FileOutputStream(file);
+ byte[] buf = new byte[1024];
+ int numread;
+ while ((numread = input.read(buf)) != -1) {
+ xmlfile.write(buf, 0, numread);
+ readSize += numread;
+ }
+ xmlfile.flush();
+ cn.disconnect();
+ } catch (Exception ex) {
+ if (DEBUG) {
+ Log.d(TAG, "download err...." + ex.fillInStackTrace());
+ }
+ } finally {
+ try {
+ if (xmlfile != null) {
+ xmlfile.close();
+ xmlfile = null;
+ }
+ if (filesize == readSize && filesize != 0) {
+ handleDownloadResult(HANDLE_XML_DOWNLOAD_FINISH, xmlName);
+ } else {
+ mErrorCode = ERROR_UNKNOWN;
+ handleDownloadResult(HANDLE_XML_DOWNLOAD_FAIL, null);
+ }
+ } catch (IOException e) {
+ mErrorCode = ERROR_UNKNOWN;
+ if (PrefUtil.DEBUG)
+ Log.d(TAG, "exception", e.fillInStackTrace());
+ handleDownloadResult(HANDLE_XML_DOWNLOAD_FAIL, null);
+ }
+ }
+ }
+
+ private void handleDownloadResult(int msg, Object obj) {
+ switch (msg) {
+ case HANDLE_XML_DOWNLOAD_FINISH:
+ if (DEBUG)
+ Log.i(TAG, "xml " + obj.toString() + " download finish");
+ dao.initrecord();
+ parserXml(XML_NAME);
+ mErrorCode = NO_ERROR;
+ break;
+ case HANDLE_XML_DOWNLOAD_FAIL:
+ if (DEBUG)
+ Log.i(TAG, "xml download fail");
+ mErrorCode = ERROR_NETWORK_UNAVAIBLE;
+ dao.cleardata();
+ break;
+ }
+ }
+
+ /* parser xml command file */
+ private void parserXml(String xML_NAME2) {
+ DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
+ DocumentBuilder domBuilder;
+ String command = null;
+ String storagemem = null;
+ String force = null;
+ String sdcardask = null;
+ String description = null;
+ String country = null;
+ updatename = null;
+ HashMap<String, DownFilesInfo> downlist;
+ if (XmlDir == null)
+ return;
+ try {
+ domBuilder = domfac.newDocumentBuilder();
+ InputStream in = new FileInputStream(XmlDir + "/" + XML_NAME);
+ Document doc = domBuilder.parse(in);
+ Element root = doc.getDocumentElement();
+ NodeList nodelist_1 = root.getChildNodes();
+ dao.cleardata();
+ if (nodelist_1 != null) {
+ for (int i = 0; i < nodelist_1.getLength(); i++) {
+ Node node_1 = nodelist_1.item(i);
+ if (node_1.getNodeName().equals("command")) {
+ command = node_1.getAttributes().getNamedItem("name").getNodeValue();
+ force = node_1.getAttributes().getNamedItem("force").getNodeValue();
+ if (!command.equals(OTA_COMMAND) && !command.equals(SCRIPT_COMMAND)) {
+ mErrorCode = ERROR_UNDISCOVERY_NEW_VERSION;
+ return;
+ } else if (command.equals(SCRIPT_COMMAND)) {
+ sdcardask = "true";
+ } else {
+ sdcardask = "false";
+ }
+ NodeList nodelist_2 = node_1.getChildNodes();
+ String isUpdateZip;
+ if (nodelist_2 != null) {
+ downlist = new HashMap<String, DownFilesInfo>();
+ DownFilesInfo fileinfo;
+ String fileNodeName = null;
+ for (int j = 0; j < nodelist_2.getLength(); j++) {
+ Node node_2 = nodelist_2.item(j);
+ if (node_2.getNodeName().equals("url")) {
+ fileinfo = new DownFilesInfo();
+ fileinfo.name = node_2.getAttributes().getNamedItem("name").getNodeValue();
+ fileNodeName = fileinfo.name;
+ fileinfo.local = node_2.getAttributes().getNamedItem("locattr").getNodeValue();
+
+ /*
+ * if(mcheckTaskCallback!=null){
+ * fileinfo.local =
+ * mcheckTaskCallback.onExternalPathSwitch(
+ * fileinfo.local); }
+ */
+ isUpdateZip = node_2.getAttributes().getNamedItem("updatezip").getNodeValue();
+ fileinfo.url = node_2.getFirstChild().getNodeValue();
+ if (PrefUtil.DEBUG)
+ Log.d(TAG, " afileinfo.local" + fileinfo.local + "fileinfo.name");
+ /*
+ * configure on server local attribute is
+ * NULL,useDefault Directory
+ */
+ if (fileinfo.name.equals(null) || fileinfo.name.equals("")
+ || fileinfo.local.equals(null) || fileinfo.local.equals("")) {
+ fileinfo.name = PrefUtil.DEFAULT_UPDATE_FILENAME;
+ fileinfo.local = XmlDir + "/" + fileinfo.name;
+ }
+ if (isUpdateZip.equals("true")) {
+ updatename = fileinfo.local;
+ }
+ if (CHECK_DEBUG)
+ Log.d(TAG, "fileInfo:" + fileinfo.toString());
+ downlist.put(fileinfo.name, fileinfo);
+ } /* end parse url */
+ if (fileNodeName != null && node_2.getNodeName().equals("md5")) {
+ // int listsize = downlist.size();
+ fileinfo = downlist.get(fileNodeName);
+ Log.d(TAG, "fileInfo md5 fileinfo!=null ?:" + (fileinfo != null));
+ if (fileinfo != null) {
+ if (DEBUG)
+ Log.i(TAG, "get xml md5:" + fileinfo.name + "url :" + fileinfo.url
+ + " local:" + fileinfo.local);
+ if (!fileinfo.name
+ .equals(node_2.getAttributes().getNamedItem("name").getNodeValue())) {
+ downlist.remove(fileinfo.name);
+ continue;
+ }
+ fileinfo.md5 = node_2.getFirstChild().getNodeValue();
+ if (DEBUG)
+ Log.i(TAG, "get xml md5:" + fileinfo.md5);
+ downlist.put(fileinfo.name, fileinfo);
+ }
+ } /* end parse md5 */
+ if (node_2.getNodeName().equals("storagemem")) {
+ storagemem = node_2.getFirstChild().getNodeValue();
+ Log.i(TAG, "get storagemem:" + storagemem);
+ if (sdcardask.equals("false")) {
+ repDirForBigFile(storagemem, downlist);
+ }
+ }
+ if (node_2.getNodeName().equals("description")) {
+ country = node_2.getAttributes().getNamedItem("country").getNodeValue();
+ if (description == null) {
+ if (country.equals(mUtil.country) || country.equals("ELSE"))
+ description = node_2.getFirstChild().getNodeValue();
+ }
+ }
+ }
+ if (DEBUG) {
+ Log.i(TAG, "get xml description:" + description);
+ }
+ mPreferences.setDownFileList(downlist);
+ dao.saveDowntasks(downlist);
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ mErrorCode = ERROR_UNDISCOVERY_NEW_VERSION;
+ return;
+ }
+ mPreferences.setPackageDescriptor(description);
+ Log.i(TAG, "##################" + Long.parseLong(storagemem));
+ mPreferences.setDownloadSize(Long.parseLong(storagemem));
+ mPreferences.setUpdateFile(updatename);
+ if (sdcardask.equals("true")) {
+ mPreferences.setUpdateWithScript(true);
+ }
+ }
+ /**replace storage directory when file size is more than 460M**/
+ private boolean repDirForBigFile(String fileSize, HashMap map) {
+ Long size = Long.valueOf(fileSize);
+
+ if (size < UpdatePositionStage.M400ZIE) {
+ return false;
+ } else {
+ Iterator iter = map.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry entry = (Map.Entry) iter.next();
+ DownFilesInfo val = (DownFilesInfo) entry.getValue();
+ if (val.local.startsWith(XmlDir)) {
+ val.local=val.local.replace(XmlDir,UpdatePositionStage.getDefaultPostion());
+ updatename = val.local;
+ }
+ map.put(entry.getKey(), val);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ }
+
+ public void setNotify(Notifier notifier) {
+ this.notifier = notifier;
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ if (notifier != null) {
+ if (mErrorCode == NO_ERROR && mPreferences != null) {
+ mPreferences.setLastCheckTime(new Date().toString());
+ notifier.Successnotify();
+ } else {
+ notifier.Failednotify();
+ }
+ }
+ }
+
+ /**
+ * @ClassName CheckUpdateResult
+ * @Description inner class of CheckUpdateTask to return Check Result by
+ * getResult()
+ * @see UpdateTasks
+ * @see CheckUpdateResult
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+ public class CheckUpdateResult {
+
+ public CheckUpdateResult() {
+ }
+
+ /**
+ * return description information of new version
+ *
+ * @return new version description
+ * @param null
+ */
+ public String getmUpdateDescript() {
+ return mPreferences.getPackageDescriptor();
+ }
+
+ /**
+ * return path of update file for execute update
+ *
+ * @return path of specified by Online update Server
+ * @param null
+ */
+ public String getmUpdateFileName() {
+ return mPreferences.getUpdatFile();
+ }
+
+ /**
+ * @return whether this update is update_with_ota or update_with_script,
+ * and return true when update is update_with_script
+ * @param null
+ */
+ public boolean ismIsScriptAsk() {
+ return mPreferences.getScriptASK();
+ }
+
+ /**
+ * @return memory needed by all update files
+ *
+ * @param null
+ */
+ public long getMemoryAsk() {
+ return mPreferences.getDownloadSize();
+ }
+ }
+
+ @Override
+ protected void onReset() {
+ super.onReset();
+
+ };
+
+ /* interface for file path switch */
+ /*
+ * public interface CheckPathCallBack{ public String
+ * onExternalPathSwitch(String filePath); }
+ */
+}
+PK
+
SourceFile
*+
*
-
-
+
+

-
+
-
+
onProgress
SourceFile
-
+
update.zip
UPDATE_OTA
mFocusStop
@@ -370,118 +1505,678 @@ mFocusStop
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
getDefault
-
-
-
-
+
+
+
+
+sdkVersion
updateFile
-sdkVersion
Exceptions
-
-
-
+
+
+ 
+
-
-
- 
-
-
-
-
-
-
-&
-)
-)-
-)1 2
-&
-)
-&6 78
-<>=
-B
-&E FG
-IKJ
-O
-
-ikj
-SourceFile
+ 
+
+ !
+
+
+
+
+
+=A
+@
+@D E
+@H I
+=
+@
+=M NO
+SUT
+Y
+=\ ]^
+`ba
+f
+
+
+SourceFile
-
-
-
-,
-, 
-
-
-
-
+
+
+
+,
+,$
+
6 
-  , a7n/j6  
-0 3
-4  5Y6 9;
-:  A D
--
-0 3
-4
-
-
-*
-
-*
-
-
-
-
+  C a7nFj6  
+G J
+K  LY6 PR
+:  X [
+-
+G J
+K
+
+*
+
+*
+
+
+
+
+ * Description:
+ *
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+package com.amlogic.update;
+
+import android.content.Context;
+import android.content.BroadcastReceiver;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Build;
+import android.os.Build.VERSION;
+import android.os.BatteryManager;
+import android.os.Environment;
+import android.os.PowerManager;
+import android.os.RecoverySystem;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.Locale;
+
+import com.amlogic.update.util.MD5;
+import com.amlogic.update.util.PrefUtil;
+import com.amlogic.update.util.UpdatePositionStage;
+import com.amlogic.update.util.UpgradeInfo;
+
+/**
+ * @ClassName OtaUpgradeUtils
+ * @Description Execute Update Operation
+ * @see
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+public class OtaUpgradeUtils {
+ public static final int ERROR_INVALID_UPGRADE_PACKAGE = 0;
+ public static final int ERROR_FILE_DOES_NOT_EXIT = 1;
+ public static final int ERROR_FILE_IO_ERROR = 2;
+ public static final int FAIL_REASON_BATTERY = 1;
+ public static final int FAIL_STOP_FORCE = 2;
+ public static final int FAIL_STOP_COPYERROR = 3;
+ public static final File CHCHE_PARTITION_DIRECOTRY = Environment.getDownloadCacheDirectory();
+ private boolean mCacheFileFlag = true;
+ public static final String DEFAULT_PACKAGE_NAME = "update.zip";
+ public static final int UPDATE_REBOOT = 0;
+ public static final int UPDATE_RECOVERY = 1;
+ public static final int UPDATE_UPDATE = 2;
+ public static final int UPDATE_OTA = 3;
+ private static File RECOVERY_DIR = new File("/cache/recovery");
+ private static File COMMAND_FILE = new File(RECOVERY_DIR, "command");
+ private static File LOG_FILE = new File(RECOVERY_DIR, "log");
+ private Context mContext;
+ private boolean mDeleteSource = false;
+ private boolean mReceiverBattery = false;
+ private boolean mFocusStop = false;
+ private PrefUtil util = null;
+
+ /**
+ * Constructs a OtaUpgradeUtils object,which will perform an update
+ *
+ * @param mContext
+ */
+ public OtaUpgradeUtils(Context context) {
+ mContext = context;
+ util = new PrefUtil(mContext);
+ }
+
+ public void setDeleteSource(boolean setDel) {
+ mDeleteSource = setDel;
+ }
+
+ /**
+ * support Battery monitor during Update process
+ *
+ */
+ public void unregistBattery() {
+ if (mReceiverBattery) {
+ mReceiverBattery = false;
+ mContext.unregisterReceiver(batteryReceiver);
+ }
+ }
+
+ /**
+ * support Battery monitor during Update process
+ *
+ */
+ public void registerBattery() {
+ if (!mReceiverBattery) {
+ mReceiverBattery = true;
+ mContext.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
+ }
+ }
+
+ private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ int level = intent.getIntExtra("level", 0);
+ int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
+ if (level < 20 && status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
+ mFocusStop = true;
+ } else {
+ mFocusStop = false;
+ }
+ }
+ };
+
+ public interface ProgressListener extends RecoverySystem.ProgressListener {
+ @Override
+ public void onProgress(int progress);
+
+ public void onVerifyFailed(int errorCode, Object object);
+
+ public void onCopyProgress(int progress);
+
+ public void onCopyFailed(int errorCode, Object object);
+
+ public void onStopProgress(int reason);
+ }
+
+ /**
+ * Execute OTA update Function
+ *
+ * @param packageFile
+ * is Upgrade file path, progressListener is update process
+ */
+ public boolean upgredeFromOta(File packageFile, ProgressListener progressListener) {
+ return upgrade(packageFile, progressListener, UPDATE_OTA);
+ }
+
+ /**
+ * Execute update Function
+ *
+ * @param packageFile
+ * is Upgrade file path, progressListener is update
+ * process,classfy is Update Category
+ * @see UPDATE_REBOOT
+ * @see UPDATE_OTA
+ * @see UPDATE_RECOVERY
+ * @see UPDATE_UPDATE
+ */
+ public boolean upgrade(File packageFile, ProgressListener progressListener, int classfy) {
+ util.resetAll();
+ if (classfy == UPDATE_OTA) {
+ try {
+ RecoverySystem.verifyPackage(packageFile, progressListener, null);
+ } catch (IOException e) {
+ progressListener.onVerifyFailed(ERROR_FILE_DOES_NOT_EXIT, packageFile.getPath());
+ e.printStackTrace();
+ return false;
+ } catch (GeneralSecurityException e) {
+ progressListener.onVerifyFailed(ERROR_INVALID_UPGRADE_PACKAGE, packageFile.getPath());
+ e.printStackTrace();
+ return false;
+ }
+ }
+ if (mFocusStop) {
+ progressListener.onStopProgress(FAIL_STOP_FORCE);
+ return false;
+ }
+ if (classfy == UPDATE_OTA && !mFocusStop) {
+ String sdkVersion = UpgradeInfo.getString("ro.build.version.sdk");
+ try {
+ int sdkInt = Integer.parseInt(sdkVersion);
+ if (sdkInt >= 24) {
+ String filePath = packageFile.getAbsolutePath();
+ File updateFile ;
+ if (!filePath.contains(UpdatePositionStage.getDefaultPostion())){
+ if (UpdatePositionStage.isBigFile(packageFile)
+ /*&& filePath.contains(UpdatePositionStage.getDefaultPostion())*/) {
+ updateFile = new File(UpdatePositionStage.getDefaultPostion(), DEFAULT_PACKAGE_NAME);
+ } else {
+ updateFile = new File(CHCHE_PARTITION_DIRECOTRY, DEFAULT_PACKAGE_NAME);
+ }
+
+ boolean b = copyFile(packageFile, updateFile, progressListener);
+ if (b && mDeleteSource) {
+ packageFile.delete();
+ }
+ filePath = updateFile.getCanonicalPath();
+ }
+ writeCommand("--update_package=" + filePath, "--locale=" + Locale.getDefault().toString());
+ // writeCommand("--update_package="+packageFile.getCanonicalPath(),"--locale="+Locale.getDefault().toString());
+ bootCommand(mContext, UPDATE_RECOVERY);
+ } else {
+ File updateFile = new File(CHCHE_PARTITION_DIRECOTRY, DEFAULT_PACKAGE_NAME);
+ boolean b = copyFile(packageFile, updateFile, progressListener);
+ if (b && mDeleteSource) {
+ packageFile.delete();
+ }
+ if (b) {
+ installPackage(mContext, updateFile);
+ return true;
+ }
+ }
+ } catch (IOException e) {
+ progressListener.onStopProgress(FAIL_STOP_FORCE);
+ }
+ } else {
+ try {
+ if (!mFocusStop) {
+ bootCommand(mContext, classfy);
+ return true;
+ } else {
+ progressListener.onStopProgress(FAIL_STOP_FORCE);
+ }
+ } catch (IOException e) {
+ }
+ }
+ return false;
+ }
+
+ private void writeCommand(String... args) throws IOException {
+ RECOVERY_DIR.mkdirs(); // In case we need it
+ COMMAND_FILE.delete(); // In case it's not writable
+ LOG_FILE.delete();
+
+ FileWriter command = new FileWriter(COMMAND_FILE);
+ try {
+ for (String arg : args) {
+ command.write(arg);
+ command.write("\n");
+ }
+ } finally {
+ command.close();
+ }
+
+ }
+
+ /**
+ * Execute boot command
+ *
+ * @param classfy
+ * is update Category
+ * @see UPDATE_REBOOT
+ * @see UPDATE_OTA
+ * @see UPDATE_RECOVERY
+ * @see UPDATE_UPDATE
+ */
+ public static void bootCommand(Context context, int classfy) throws IOException {
+
+ PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
+ if (classfy == UPDATE_RECOVERY) {
+ pm.reboot("recovery");
+ }
+ if (classfy == UPDATE_REBOOT) {
+ pm.reboot("normal_reboot");
+ } else if (classfy == UPDATE_UPDATE) {
+ pm.reboot("update");
+ }
+ throw new IOException("Reboot failed (no permissions?)");
+ }
+
+ /**
+ * Execute OTA update
+ *
+ * @param packagePath
+ * is update file path
+ * @see UPDATE_OTA
+ */
+ public boolean upgradeFromOta(String packagePath, ProgressListener progressListener) {
+ return upgredeFromOta(new File(packagePath), progressListener);
+ }
+
+ // public void deleteSource(boolean b) {}
+
+ private boolean copyFile(File src, File dst, ProgressListener listener) {
+ long inSize = src.length();
+ long outSize = 0;
+ int progress = 0;
+ listener.onCopyProgress(progress);
+ try {
+ if (dst.exists()) {
+ dst.delete();
+ dst.createNewFile();
+ }
+ FileInputStream in = new FileInputStream(src);
+ FileOutputStream out = new FileOutputStream(dst);
+ int length = -1;
+ byte[] buf = new byte[1024];
+ while ((length = in.read(buf)) != -1) {
+ out.write(buf, 0, length);
+ outSize += length;
+ int temp = (int) (((float) outSize) / inSize * 100);
+ if (temp != progress) {
+ progress = temp;
+ listener.onCopyProgress(progress);
+ }
+ if (mFocusStop) {
+ listener.onStopProgress(FAIL_STOP_FORCE);
+ out.flush();
+ in.close();
+ out.close();
+ return false;
+ }
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if (outSize != in.available() || MD5.checkMd5Files(src, dst)) {
+ listener.onStopProgress(FAIL_STOP_COPYERROR);
+ }
+ out.flush();
+ in.close();
+ out.close();
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ return false;
+ } catch (IOException e) {
+ e.printStackTrace();
+ return false;
+ }
+ return true;
+ }
+
+ private boolean copyFile(String src, String dst, ProgressListener listener) {
+ return copyFile(new File(src), new File(dst), listener);
+ }
+
+ /**
+ * Execute installPackage Update
+ *
+ * @param packagePath
+ * is update file path
+ *
+ */
+ public static void installPackage(Context context, File packageFile) {
+ try {
+ RecoverySystem.installPackage(context, packageFile);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /*
+ * public static void rebootUpdate(Context context) { try {
+ * bootCommand(context, "update", UPDATE_UPDATE); } catch (IOException e) {
+ * // e.printStackTrace(); } }
+ */
+
+ /**
+ * Execute recovery command
+ *
+ * @param
+ * @see UPDATE_REBOOT
+ */
+ public static void rebootRecovery(Context context) {
+ try {
+ bootCommand(context, UPDATE_RECOVERY);
+ } catch (IOException e) {
+ // e.printStackTrace();
+ }
+ }
+
+ /**
+ * Execute reboot normal command
+ *
+ * @param
+ * @see UPDATE_REBOOT
+ */
+ public static void rebootNormal(Context context) {
+ try {
+ bootCommand(context, UPDATE_REBOOT);
+ } catch (IOException e) {
+ // e.printStackTrace();
+ }
+ }
+
+ /*
+ * public static boolean checkVersion(long newVersion, String product) {
+ * return (Build.TIME <= newVersion * 1000 && (Build.DEVICE .equals(product)
+ * || Build.PRODUCT.equals(product))); }
+ */
+
+ /*
+ * public static boolean checkIncVersion(String fingerprinter, String
+ * product) { return (Build.FINGERPRINT.equals(fingerprinter) &&
+ * (Build.DEVICE .equals(product) || Build.PRODUCT.equals(product))); }
+ */
+
+ /**
+ * setMode to Debug
+ *
+ * @param debug
+ * true:debug mode false: update mode
+ */
+ public static void setDebugMode(boolean debug) {
+ PrefUtil.DEBUG = debug;
+ }
+
+ public void forceStop(boolean val) {
+ mFocusStop = val;
+ }
+}
+PK
+
mErrorCode
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
SourceFile
-
-*
-
-
+
+*
+
+
+ * @Package com.amlogic.update
+ * @Description update function
+ *
+ * Copyright (c) Inspur Group Co., Ltd. Unpublished
+ *
+ * Inspur Group Co., Ltd.
+ * Proprietary & Confidential
+ *
+ * This source code and the algorithms implemented therein constitute
+ * confidential information and may comprise trade secrets of Inspur
+ * or its associates, and any use thereof is subject to the terms and
+ * conditions of the Non-Disclosure Agreement pursuant to which this
+ * source code was originally received.
+ */
+package com.amlogic.update;
+
+import android.util.Log;
+import com.amlogic.update.util.DesUtils;
+import com.amlogic.update.util.UpgradeInfo;
+/**
+ * @ClassName UpdateTasks
+ * @Description Work Thread For Online Update,Known Subclasses is @see CheckUpdateTask and @see DownloadUpdateTask
+ * @Date 2012/12/03
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+public abstract class UpdateTasks implements Runnable {
+ public static final int NO_ERROR = 0;
+ private boolean DEBUG = true||UpgradeInfo.isDebugAble();
+ public static final int RUNNING_STATUS_UNSTART = 0;
+ public static final int RUNNING_STATUS_RUNNING = 1;
+ public static final int RUNNING_STATUS_PAUSE = 2;
+ public static final int RUNNING_STATUS_FINISH = 3;
+ protected Thread mThread;
+ protected long mProgress = 0;
+ protected int mErrorCode = NO_ERROR;
+ protected int mRunningStatus = RUNNING_STATUS_UNSTART;
+ protected Object mResult;
+
+ // ----------------Runtime Method
+ /**
+ * Start work Thread and set status to @see RUNNING_STATUS_RUNNING
+ *
+ * @param null
+ */
+ public void start() {
+ if(DEBUG)android.util.Log.d("Upgrade","Upgrade:start");
+ if (!DesUtils.isAmlogicChip()) {
+ Log.d("warn", "Sorry, just for amlogic cpu!");
+ mRunningStatus = RUNNING_STATUS_FINISH;
+ return;
+ }else if (mRunningStatus != RUNNING_STATUS_RUNNING) {
+ mRunningStatus = RUNNING_STATUS_RUNNING;
+ mThread = new Thread(this);
+ onStart();
+ mThread.start();
+ }
+ }
+
+ protected void onStart() {}
+
+ @Override
+ public void run() {
+ onRunning();
+ stop();
+ }
+
+ protected void onRunning() {}
+ /**
+ * pause work thread and set status to @see RUNNING_STATUS_PAUSE
+ *
+ * @param null
+ */
+ public void pause() {
+ mRunningStatus = RUNNING_STATUS_PAUSE;
+ onPause();
+ }
+
+ protected void onPause() {}
+ /**
+ * resume work thread and set status from @see RUNNING_STATUS_PAUSE to @see RUNNING_STATUS_RUNNING
+ *
+ * @param null
+ */
+ public void resume() {
+ if(mThread!=null){
+ if(DEBUG) android.util.Log.d("Upgrade","Upgrade:resume"+(mThread.isAlive())+" mRunningStatus:"+mRunningStatus);
+ }else{
+ if(DEBUG) android.util.Log.d("Upgrade","Upgrade:resume mThread *= null");
+ }
+ if (mRunningStatus == RUNNING_STATUS_PAUSE){
+ if (mThread != null && mThread.isAlive()) {
+ mRunningStatus = RUNNING_STATUS_RUNNING;
+ onResume();
+ } else {
+ start();
+ }
+ }
+ }
+
+ protected void onResume() {}
+ /**
+ * stop work thread and set status from @see RUNNING_STATUS_RUNNING to @see RUNNING_STATUS_FINISH
+ * @param null
+ */
+ public void stop() {
+ if (mRunningStatus != RUNNING_STATUS_UNSTART) {
+ onStop();
+ mRunningStatus = RUNNING_STATUS_FINISH;
+ }
+ }
+
+ protected void onReset() {}
+ /**
+ * reset work thread and set status to @see RUNNING_STATUS_UNSTART
+ *
+ * @param null
+ */
+ public boolean reset() {
+ if (mRunningStatus == RUNNING_STATUS_FINISH
+ || mRunningStatus == RUNNING_STATUS_PAUSE
+ || mRunningStatus == RUNNING_STATUS_RUNNING) {
+ onReset();
+ mProgress = 0;
+ mRunningStatus = RUNNING_STATUS_UNSTART;
+ return true;
+ }
+ return false;
+ }
+
+ protected void onStop() {}
+
+ // -----------------Public Method
+ public int getErrorCode() {
+ return mErrorCode;
+ }
+
+ public int getRunningStatus() {
+ return mRunningStatus;
+ }
+
+ public long getProgress() {
+ return mProgress;
+ }
+
+ public Object getResult() {
+ return mResult;
+ }
+}
+PK
+
@@ -497,7 +2192,87 @@ SourceFile
-
+
+ * Description:
+ *
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+package com.amlogic.update.util;
+
+public class DownFilesInfo {
+ public String name;
+ public String local;
+ public String md5;
+ public String url;
+ int complete;
+ int filesize;
+
+ DownFilesInfo(String name, String local, String md5, String url) {
+ this.name = name;
+ this.local = local;
+ this.md5 = md5;
+ this.url = url;
+ }
+
+ DownFilesInfo(int filesize, int complete, String url) {
+ this.filesize = filesize;
+ this.complete = complete;
+ this.url = url;
+ }
+
+ public DownFilesInfo() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public String getLocal() {
+ return local;
+ }
+
+ public String getMd5() {
+ return md5;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public int getComplete() {
+ return complete;
+ }
+
+ @Override
+ public String toString() {
+ return "DownloadFilesInfo [name=" + name + ", local=" + local
+ + ", md5=" + md5 + ", url=" + url + ", complete=" + complete
+ + "]";
+ }
+
+ void setName(String name) {
+ this.name = name;
+ }
+
+ public void setLocal(String local) {
+ this.local = local;
+ }
+
+ public void setMd5(String md5) {
+ this.md5 = md5;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public void setComplete(int complete) {
+ this.complete = complete;
+ }
+}
+PK
+
@@ -538,7 +2313,138 @@ SourceFile
*
-
+
+* Description:
+* @Copyright: Copyright (c) 2012
+* @Company: Amlogic
+* @version: 1.0
+*/
+
+package com.amlogic.update.util;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.swing.text.html.HTMLDocument.Iterator;
+
+import android.os.Environment;
+import android.util.Log;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+
+public class DownFileDao {
+
+ private DatabaseHelper dbHelper;
+ private Context mContext;
+
+ public DownFileDao(Context co) {
+ mContext = co;
+ dbHelper = new DatabaseHelper(co);
+ }
+
+ public List<DownFilesInfo> getDowntasks() {
+ List<DownFilesInfo> list = new ArrayList<DownFilesInfo>();
+ SQLiteDatabase database = getConnection();
+ String sql = "select * from " + DatabaseHelper.DOWNTASKTABLE;
+ Cursor cursor = database.rawQuery(sql,null);
+ while (cursor.moveToNext()) {
+ if (PrefUtil.DEBUG)
+ Log.d("db","getDowntasks:1-"+cursor.getString(1)+" 2-"+cursor.getString(2)+" 3-"+cursor.getString(3)+" 4-"+cursor.getString(4));
+
+ DownFilesInfo info = new DownFilesInfo(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
+ list.add(info);
+ }
+ cursor.close();
+ database.close();
+ return list;
+ }
+
+ DownFilesInfo getDownFile(String url) {
+ SQLiteDatabase database = getConnection();
+ DownFilesInfo info = null;
+ Cursor cursor = null;
+ try {
+ String sql = "select * from " + DatabaseHelper.DOWNTASKTABLE + " where url=?";
+ cursor = database.rawQuery(sql, new String[] { url });
+ if(cursor.moveToNext()){
+ info = new DownFilesInfo(cursor.getString(1), cursor.getString(2), cursor.getString(3),
+ cursor.getString(4));
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ if (null != cursor) {
+ cursor.close();
+ }
+ }
+ return info;
+ }
+ synchronized SQLiteDatabase getConnection() {
+ SQLiteDatabase sqliteDatabase = null;
+ try {
+ sqliteDatabase= dbHelper.getReadableDatabase();
+ } catch (Exception e) {
+ }
+ return sqliteDatabase;
+ }
+
+ public void saveDowntasks(List<DownFilesInfo> tasks) {
+ SQLiteDatabase database = dbHelper.getWritableDatabase();
+ //Log.d("db","saveDowntasks:"+tasks.size());
+ for (DownFilesInfo task : tasks) {
+ String sql = "insert into "+DatabaseHelper.DOWNTASKTABLE+"(file_name,file_location,file_md5,url) values (?,?,?,?)";
+ Object[] bindArgs = { task.getName(), task.getLocal(),
+ task.getMd5(),task.getUrl()};
+ database.execSQL(sql, bindArgs);
+ }
+ if (null != database) {
+ database.close();
+ }
+ }
+
+ public void saveDowntasks(HashMap<String,DownFilesInfo> taskMap) {
+ SQLiteDatabase database = dbHelper.getWritableDatabase();
+ for (DownFilesInfo task :taskMap.values()) {
+ String sql = "insert into "+DatabaseHelper.DOWNTASKTABLE+"(file_name,file_location,file_md5,url) values (?,?,?,?)";
+ String name = task.getLocal();
+ Object[] bindArgs = { task.getName(), task.getLocal(),
+ task.getMd5(),task.getUrl()};
+ database.execSQL(sql, bindArgs);
+ }
+ if (null != database) {
+ database.close();
+ }
+ }
+
+ public void delFile(String locate) {
+ SQLiteDatabase database = dbHelper.getWritableDatabase();
+ try {
+ database.delete(DatabaseHelper.DOWNTASKTABLE, "file_location=?", new String[] { locate});
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+ public void cleardata() {
+ dbHelper.cleartable(DatabaseHelper.DOWNTASKTABLE);
+ dbHelper.cleartable(DatabaseHelper.DOWNLOADINGRECORD);
+ }
+ public void initrecord() {
+ dbHelper.cleartable(DatabaseHelper.DOWNLOADINGRECORD);
+ }
+}
+PK
+
@@ -580,7 +2486,192 @@ SourceFile
-
+
+ * Description:
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+
+package com.amlogic.update.util;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import android.util.Log;
+
+class DownloadFile {
+ private File file;
+ private String url;
+ private String fileName;
+ private int startPos;
+ private int endPos;
+ private int completeSize;
+ private int threadNumTotal = 1;
+ private int currentThread = 1;
+ private boolean startDown = false;
+ private HttpURLConnection httpConn = null;
+ static int BUFFER_SIZE = 1024 * 512;
+
+ DownloadFile() {
+ }
+
+ /**
+ * @param int1
+ * @param int2
+ * @param int3
+ * @param int4
+ * @param string
+ */
+ DownloadFile(int thread_id, int start_pos, int end_pos,
+ int compelete_size, String url,boolean startDown) {
+ currentThread = thread_id;
+ startPos = start_pos;
+ endPos = end_pos;
+ startDown = false;
+ completeSize = compelete_size;
+ this.url = url;
+ this.startDown = startDown;
+ }
+
+ File getFile() {
+ return file;
+ }
+
+ void setFile(File file) {
+ this.file = file;
+ }
+
+ String getUrl() {
+ return url;
+ }
+
+ void setUrl(String url) {
+ this.url = url;
+ }
+
+ String getFileName() {
+ return fileName;
+ }
+
+ void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ int getStartPos() {
+ return startPos;
+ }
+
+ void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+
+ int getEndPos() {
+ return endPos;
+ }
+
+ void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+
+ int getThreadNumTotal() {
+ return threadNumTotal;
+ }
+
+ void setThreadNumTotal(int threadNumTotal) {
+ this.threadNumTotal = threadNumTotal;
+ }
+
+ int getCurrentThread() {
+ return currentThread;
+ }
+
+ void setCurrentThread(int currentThread) {
+ this.currentThread = currentThread;
+ }
+
+ static int getBUFFER_SIZE() {
+ return BUFFER_SIZE;
+ }
+
+ static void setBUFFER_SIZE(int bUFFER_SIZE) {
+ BUFFER_SIZE = bUFFER_SIZE;
+ }
+
+ InputStream getInputStreamByPos() {
+ try {
+ if(PrefUtil.DEBUG) Log.d(PrefUtil.TAG,"return InputStream"+this.startPos+" end:"+this.endPos);
+ if (this.url != null && !"".equals(this.url)) {
+
+ if (this.startPos >= 0 && this.endPos >= 0 &&
+ this.completeSize >= 0 && (this.startPos + this.completeSize) < this.endPos) {
+ int mStartPoi = (int) (this.startPos+this.completeSize);
+ URL url = new URL(this.url);
+ httpConn = (HttpURLConnection) url.openConnection();
+ httpConn.setRequestMethod("GET");
+ httpConn.setAllowUserInteraction(false);
+ httpConn.setRequestProperty("Connection","Keep-Alive");
+ httpConn.setConnectTimeout(6000*3);//never time out
+ httpConn.setReadTimeout(0);
+ httpConn.setDefaultUseCaches(false);
+ httpConn.setRequestProperty("RANGE", "bytes=" + mStartPoi + "-" + getEndPos());
+ httpConn.connect();
+ if(httpConn.getResponseCode()!=206 && httpConn.getResponseCode()!=200){
+ return null;
+ }
+ if(PrefUtil.DEBUG) Log.d(PrefUtil.TAG, "getStartPos( ) " + mStartPoi
+ + " getEndPos( ) " + getEndPos());
+ return httpConn.getInputStream();
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ return null;
+ }
+
+
+ public void closeHttpConn(){
+ if(httpConn!=null){
+ httpConn.disconnect();
+ httpConn=null;
+ }
+ startDown = false;
+ }
+
+ public boolean isStart(){
+ return startDown;
+ }
+
+ public void setIsStart(boolean start){
+ startDown = start;
+ }
+
+ @Override
+ public String toString() {
+ return "DownloadFile [file=" + file + ", url=" + url + ", fileName="
+ + fileName + ", startPos=" + startPos + ", endPos=" + endPos
+ + ", completeSize=" + completeSize + ", threadNumTotal="
+ + threadNumTotal + ", currentThread=" + currentThread
+ + ", httpConn=" + httpConn + "]";
+ }
+
+ public int getCompleteSize() {
+ return completeSize;
+ }
+
+ public void setCompleteSize(int completeSize) {
+ this.completeSize = completeSize;
+ }
+
+}
+PK
+
update.zip
check_time
@@ -637,7 +2728,300 @@ SourceFile
-
+
+ * @Package
+ * @Description Copyright (c) Inspur Group Co., Ltd. Unpublished Inspur Group
+ * Co., Ltd. Proprietary & Confidential This source code and the
+ * algorithms implemented therein constitute confidential
+ * information and may comprise trade secrets of Inspur or its
+ * associates, and any use thereof is subject to the terms and
+ * conditions of the Non-Disclosure Agreement pursuant to which
+ * this source code was originally received.
+ */
+/**
+ * @ClassName Utils
+ * @Description TODO
+ * @Date 2013-7-15
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+package com.amlogic.update.util;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.Environment;
+
+public class PrefUtil {
+ public static final String DEFAULT_UPDATE_FILENAME = "update.zip";
+ public static Boolean DEBUG = true;
+ public static final String TAG = "OTA";
+ private Context mContext;
+ // access by download task
+ static final String PREFS_DOWNLOAD_SIZE = "download_size";
+ // access by download task
+ static final String PREFS_DOWNLOAD_POSITION = "download_position";
+ static final String PREFS_DOWNLOAD_UPDATEFILE = "download_updatefile";
+ // access by checking task
+ static final String PREFS_DOWNLOAD_TARGET = "download_target";
+ static final String PREFS_DOWNLOAD_FILELIST = "download_filelist";
+ // access by checking task
+ static final String PREFS_DOWNLOAD_URL = "download_URL";
+ // access by checking task
+ static final String PREFS_PACKAGE_DESCRIPTOR = "package_descriptor";
+ // access by checking task
+ static final String PREFS_PACKAGE_MD5 = "package_md5";
+ static final String PREFS_CHECK_STRING = "check_string";
+ static final String PREFS_UPDATE_STRING = "update_string";
+ // access by loader
+ static final String PREFS_CHECK_TIME = "check_time";
+ static final String PREFS_SCRIPT_ASK = "update_script";
+ static final String PREFS_NOTICE_TRUE = "notice_true";
+ //static final String PREF_START_RESTORE = "retore_start";
+ //private static final String FlagFile = ".wipe_record";
+ private SharedPreferences mPrefs;
+
+ public PrefUtil(Context context) {
+ mPrefs = context.getSharedPreferences("SHARE", Context.MODE_PRIVATE);
+ mContext = context;
+ }
+
+ public void setLastCheckTime(String date) {
+ setString(PREFS_CHECK_STRING, date);
+ }
+
+ String getLastCheckTime() {
+ return mPrefs.getString(PREFS_CHECK_STRING, null);
+ }
+
+ void setLastUpdateTime(String date) {
+ setString(PREFS_UPDATE_STRING, date);
+ }
+
+ String getLastUpdateTime() {
+ return mPrefs.getString(PREFS_UPDATE_STRING, null);
+ }
+
+ private void setString(String key, String Str) {
+ SharedPreferences.Editor mEditor = mPrefs.edit();
+ mEditor.putString(key, Str);
+ mEditor.commit();
+ }
+
+ private void setStringSet(String key, Set<String> downSet) {
+ SharedPreferences.Editor mEditor = mPrefs.edit();
+ mEditor.putStringSet(key, downSet);
+ mEditor.commit();
+ }
+
+ private void setInt(String key, int Int) {
+ SharedPreferences.Editor mEditor = mPrefs.edit();
+ mEditor.putInt(key, Int);
+ mEditor.commit();
+ }
+
+ private void setLong(String key, long Long) {
+ SharedPreferences.Editor mEditor = mPrefs.edit();
+ mEditor.putLong(key, Long);
+ mEditor.commit();
+ }
+
+ public void setUpdateWithScript(boolean bool) {
+ setBoolean(PREFS_SCRIPT_ASK, bool);
+ }
+
+ public boolean getScriptASK() {
+ return mPrefs.getBoolean(PREFS_SCRIPT_ASK, false);
+ }
+
+ void setBoolean(String key, Boolean bool) {
+ SharedPreferences.Editor mEditor = mPrefs.edit();
+ mEditor.putBoolean(key, bool);
+ mEditor.commit();
+ }
+
+ public void setDownloadSize(long size) {
+ setLong(PREFS_DOWNLOAD_SIZE, size);
+ }
+
+ public void setDownFileList(HashMap<String, DownFilesInfo> downlist) {
+
+ HashSet<String> filelist = new HashSet<String>();
+ for (DownFilesInfo task :downlist.values()) {
+ filelist.add(task.local);
+ }
+ if (filelist.size() > 0) {
+ setStringSet(PREFS_DOWNLOAD_FILELIST, filelist);
+ }
+ }
+
+ public void setDownloadPos(long position) {
+ setLong(PREFS_DOWNLOAD_POSITION, position);
+ }
+
+ void setBreakpoint(long size, long position) {
+ setLong(PREFS_DOWNLOAD_SIZE, size);
+ setLong(PREFS_DOWNLOAD_POSITION, position);
+ }
+
+ void setDownloadInfo(String url, String targetFile) {
+ setString(PREFS_DOWNLOAD_URL, url);
+ setString(PREFS_DOWNLOAD_TARGET, targetFile);
+ setBreakpoint(0, 0);
+ }
+
+ void setMd5(String md5) {
+ setString(PREFS_PACKAGE_MD5, md5);
+ }
+
+ String getMd5() {
+ return mPrefs.getString(PREFS_PACKAGE_MD5, null);
+ }
+
+ public void setUpdateFile(String filepath) {
+ setString(PREFS_DOWNLOAD_UPDATEFILE, filepath);
+ }
+
+ public String getUpdatFile() {
+ return mPrefs.getString(PREFS_DOWNLOAD_UPDATEFILE, null);
+ }
+
+ void setCheckTime(long time) {
+ setLong(PREFS_CHECK_TIME, time);
+ }
+
+ public void setPackageDescriptor(String str) {
+ setString(PREFS_PACKAGE_DESCRIPTOR, str);
+ }
+
+ void setDownloadTarget(String target) {
+ setString(PREFS_DOWNLOAD_TARGET, target);
+ }
+
+ void setDownloadURL(String URL) {
+ setString(PREFS_DOWNLOAD_URL, URL);
+ }
+
+ void setNotice(Boolean bool) {
+ setBoolean(PREFS_NOTICE_TRUE, bool);
+ }
+
+ public String getPackageDescriptor() {
+ return mPrefs.getString(PREFS_PACKAGE_DESCRIPTOR, null);
+ }
+
+ public synchronized long getDownloadSize() {
+ return mPrefs.getLong(PREFS_DOWNLOAD_SIZE, 0);
+ }
+
+ public long getDownloadPos() {
+ return mPrefs.getLong(PREFS_DOWNLOAD_POSITION, 0);
+ }
+
+ String getDownloadTarget() {
+ return mPrefs.getString(PREFS_DOWNLOAD_TARGET, null);
+ }
+
+ String getDownloadURL() {
+ return mPrefs.getString(PREFS_DOWNLOAD_URL, null);
+ }
+
+ long getCheckTime() {
+ return mPrefs.getLong(PREFS_CHECK_TIME, 0);
+ }
+
+ boolean getNotice() {
+ return mPrefs.getBoolean(PREFS_NOTICE_TRUE, true);
+ }
+
+ public Set<String> getDownFileSet() {
+ return mPrefs.getStringSet(PREFS_DOWNLOAD_FILELIST, null);
+ }
+
+ void setDownloadInfo(long size, long position, String target, String URL) {
+ setDownloadSize(size);
+ setDownloadPos(position);
+ setDownloadTarget(target);
+ setDownloadURL(URL);
+ }
+
+ public void resetAll() {
+ setDownloadURL("");
+ setMd5("");
+ setUpdateWithScript(false);
+ setString(PREFS_DOWNLOAD_URL, "");
+ setString(PREFS_DOWNLOAD_TARGET, "");
+ setBreakpoint(0, 0);
+ setStringSet(PREFS_DOWNLOAD_FILELIST, null);
+ }
+
+ /**
+ * @return
+ */
+ public int getID() {
+ if (mPrefs.getInt("ID", 1001) == 1001) {
+ int random = (int) (Math.random() * 1000);
+ setInt("ID", random);
+ }
+ if (DEBUG)
+ return 1000;
+ else
+ return mPrefs.getInt("ID", 0);
+ }
+
+ boolean getBooleanVal(String key, boolean def) {
+ return mPrefs.getBoolean(key, def);
+ }
+
+ /* void write2File() {
+ String Mounted = Environment.getExternalStorage2State();
+ if (!Mounted.equals(Environment.MEDIA_MOUNTED)) {
+ return;
+ }
+ File flagFile = new File(Environment.getExternalStorage2Directory(),
+ FlagFile);
+ if (!flagFile.exists()) {
+ try {
+ flagFile.createNewFile();
+ } catch (IOException excep) {
+ }
+ }
+ FileWriter fw = null;
+ try {
+ fw = new FileWriter(flagFile);
+ } catch (IOException excep) {
+ }
+ BufferedWriter output = new BufferedWriter(fw);
+ Set<String> downfiles = mPrefs.getStringSet(PREFS_DOWNLOAD_FILELIST,
+ null);
+ if (downfiles != null && downfiles.size() > 0) {
+ String[] downlist = downfiles.toArray(new String[0]);
+ for (int i = 0; i < downlist.length; i++) {
+ try {
+ output.write(downlist[i]);
+ output.newLine();
+ } catch (IOException ex) {
+ }
+ }
+ }
+ try {
+ output.close();
+ } catch (IOException e) {
+ }
+ }*/
+
+}
+PK
+
randomFile
@@ -687,7 +3071,8 @@ SourceFile
*
*
 ):ILPRZd E`ct'@e,Qlo;VYjy|
-
+
+p<
@@ -804,11 +3189,11 @@ e6 *
 *
-
+
-Y:  …
+Y:  …
-Y:  …
+Y:  …
Ը
@@ -821,7 +3206,505 @@ e6 *
*
-
+
+ * Description:
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+
+package com.amlogic.update.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+import java.io.FileInputStream;
+import java.io.SyncFailedException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.SocketException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.RejectedExecutionException;
+
+import org.apache.http.HttpConnection;
+
+import com.amlogic.update.DownloadUpdateTask;
+import com.amlogic.update.DownloadUpdateTask.DownloadSize;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Environment;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+
+public class DownloadUtil {
+ private boolean DEBUG = (true||UpgradeInfo.isDebugAble());
+ private static final String TAG = PrefUtil.TAG;
+ public static int defaultThread = 3;
+ private int threadNum;
+ static final int MSG_FILE_ZISE = 100;
+ static final int MSG_DOWNLOAD_SIZE = 101;
+ static final int MSG_DOWNLOAD_FINISH = 102;
+ static final int MSG_DOWNLOAD_ERROR = 103;
+ private Context mContext;
+ private static final int INIT = 1;
+ private static final int DOWNLOADING = 2;
+ private static final int PAUSE = 3;
+ private DownloadSize mDownloadSize = null;
+ private int state = INIT;
+ private DownloadUpdateTask downloadTask;
+ ThreadPoolExecutor service;
+ private CountDownLatch countDownLatch = null;
+ private static List<SaveFileThread> workers = new ArrayList<SaveFileThread>();
+
+ public boolean isdownloading() {
+ return state == DOWNLOADING;
+ }
+
+ int getThreadNum() {
+ return threadNum;
+ }
+
+ public DownloadUtil(DownloadSize downloadSize, Context mContext, DownloadUpdateTask downloadThread) {
+ this.mDownloadSize = downloadSize;
+ this.mContext = mContext;
+ this.downloadTask = downloadThread;
+ // defaultThread = getDefaltThread(mContext);
+ service = new ThreadPoolExecutor(defaultThread, defaultThread + 2, 30, TimeUnit.SECONDS,
+ new ArrayBlockingQueue<Runnable>(5), new ThreadPoolExecutor.DiscardOldestPolicy());
+ Dao.getInstance(mContext).resetInfos();
+ }
+
+ boolean isExistFile(String filePath) {
+ File file = new File(filePath);
+ return file.exists();
+ }
+
+ void createDir(String dirPath) {
+ if (dirPath != null || !"".equals(dirPath)) {
+ File file = new File(dirPath);
+ if (!file.isDirectory()) {
+ file.mkdirs();
+ }
+ }
+ }
+
+ private static int getDefaltThread(Context cxt) {
+ int threadDefault = 3;
+ ConnectivityManager connectivityManager = (ConnectivityManager) cxt
+ .getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
+ if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
+ threadDefault = 1;
+ }
+ return threadDefault;
+ }
+
+ /**
+ * param urlstr: Url to download
+ */
+ private boolean isFirst(String urlstr) {
+ boolean ret = Dao.getInstance(mContext).isHasInfors(urlstr);
+ return ret;
+ }
+
+ public boolean isServicePartDownload(int startPoi,long l,String urlStr){
+
+ HttpURLConnection httpConn=null;
+ boolean partDownload =false;
+ try{
+ URL url = new URL(urlStr);
+ httpConn = (HttpURLConnection) url.openConnection();
+ httpConn.setRequestMethod("GET");
+ httpConn.setAllowUserInteraction(false);
+ httpConn.setRequestProperty("Connection","Keep-Alive");
+ httpConn.setConnectTimeout(6000*3);//never time out
+ httpConn.setReadTimeout(0);
+ httpConn.setDefaultUseCaches(false);
+ httpConn.setRequestProperty("RANGE", "bytes=" + startPoi + "-" + l);
+ httpConn.connect();
+ if(httpConn.getResponseCode()==206){
+ partDownload = true;
+ }
+ }catch(IOException ex){
+ ex.printStackTrace();
+ }finally{
+ httpConn.disconnect();
+ }
+ if(DEBUG)
+ Log.d(TAG,"Download update file,may service support partial download: " + partDownload);
+ return partDownload;
+
+ }
+
+ int getFileLength(String url) {
+ URL murl;
+ int len = -1;
+ try {
+ murl = new URL(url);
+ HttpURLConnection httpConn = (HttpURLConnection) murl.openConnection();
+ httpConn.setRequestMethod("GET");
+ httpConn.setRequestProperty("Accept-Encoding", "identity");
+ if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
+ len = httpConn.getContentLength();
+ httpConn.disconnect();
+ if (DEBUG)
+ Log.d(TAG, "getFileLength:" + len);
+ return len;
+ }
+ } catch (MalformedURLException e) {
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_NETWORK_UNAVAIBLE);
+ e.printStackTrace();
+ return -1;
+ } catch (IOException ex) {
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_IOERROR);
+ ex.printStackTrace();
+ return -1;
+ } catch (Exception exp) {
+ exp.printStackTrace();
+ }
+ return -1;
+ }
+
+ public int Save2File(String urlAddress, String saveDir, String fileName, final String md5) throws IOException {
+ if(DEBUG)
+ Log.d(TAG,
+ "Save2File urlAddress :" + urlAddress + "saveDir:" + saveDir + " fileName:" + fileName + " md5:" + md5);
+ state = DOWNLOADING;
+ long urlTotalSize = -1;
+ final File file = new File(saveDir);
+
+ try {
+ List<DownloadFile> downInfo;
+
+ urlTotalSize = getFileLength(urlAddress);
+ if (urlTotalSize <= 0)
+ return -1;
+ if (isFirst(urlAddress)) {
+ if (file.exists()) {
+ file.delete();
+ }
+ downInfo = new ArrayList<DownloadFile>();
+ threadNum = (int) (urlTotalSize / DownloadFile.BUFFER_SIZE) + 1;
+ if (DEBUG)
+ Log.d(TAG, "download target :" + file.getAbsolutePath() + "size:" + urlTotalSize);
+ if (threadNum > defaultThread) {
+ threadNum = defaultThread;
+ }
+ if (!isServicePartDownload(0, urlTotalSize / 2, urlAddress)) {
+ threadNum = 1;
+ }
+ long spanSize = (long) Math.ceil((float) urlTotalSize / threadNum);
+
+ if (DEBUG)
+ Log.d(TAG, "spanSize=" + spanSize + " urlTotalSize=" + urlTotalSize);
+ if (urlTotalSize <= 0)
+ return -1;
+
+ for (int i = 0; i < threadNum; i++) {
+ DownloadFile downloadFile = new DownloadFile();
+ downloadFile.setFile(new File(saveDir));
+ downloadFile.setUrl(urlAddress);
+ downloadFile.setStartPos((int) (i * spanSize));
+ int ends = (int) ((i + 1) * spanSize - 1);
+ if ((threadNum - 1) == i || ends >= urlTotalSize) {
+ downloadFile.setEndPos((int) urlTotalSize - 1);
+ } else {
+ downloadFile.setEndPos(ends);
+ }
+ downloadFile.setCurrentThread(i);
+ downloadFile.setFileName(fileName);
+ downloadFile.setIsStart(false);
+ if(DEBUG) Log.d(TAG, "dump download info:" + downloadFile.toString());
+ downInfo.add(downloadFile);
+ }
+ if (downInfo.size() > 0) {
+ Dao.getInstance(mContext).saveInfos(downInfo);
+ }
+ } else {
+ downInfo = Dao.getInstance(mContext).getInfos(urlAddress);
+ if (downInfo.size() > 0) {
+ threadNum = downInfo.size();
+ if (DEBUG)
+ Log.d("OTA", downInfo.toString());
+ }
+ if (DEBUG)
+ Log.d("OTA", "down Thread target:" + downInfo.size() + " file:" + file.getAbsolutePath());
+ }
+
+ countDownLatch = new CountDownLatch(downInfo.size() );
+ for (int i = 0; i < downInfo.size(); i++) {
+ RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
+ DownloadFile downloadFile = downInfo.get(i);
+ Log.d("OTA", "down Thread target:" + downloadFile.isStart() );
+ if (downloadFile.isStart()) {
+ continue;
+ }
+ try {
+ SaveFileThread work = new SaveFileThread(randomAccessFile, downloadFile, countDownLatch,
+ mDownloadSize);
+ synchronized(workers){
+ workers.add(work);
+ }
+ service.execute(work);
+ } catch (RejectedExecutionException ex) {
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_NETWORK_UNAVAIBLE);
+ ex.printStackTrace();
+ return -1;
+ }
+ }
+ } catch (Exception ex) {
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_UNKNOWN);
+ ex.printStackTrace();
+ throw new IOException();
+ } finally {
+ /*try {
+ if (countDownLatch != null){
+ countDownLatch.await();
+ }
+ if(DEBUG)
+ Log.d("OTA", "await success" );
+ } catch (InterruptedException ex) {
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_UNKNOWN);
+ ex.printStackTrace();
+ //throw new IOException();
+ return -1;
+ }*/
+ while(true){
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }finally{
+ synchronized(workers){
+ if(workers.size()==0){
+ break;
+ }
+ /*boolean stop = true;
+ for (SaveFileThread t : workers) {
+ stop = stop&t.stopFlag;
+ }
+ if(workers.size()==0||stop){
+ break;
+ }*/
+ }
+ }
+ }
+ }
+ if (state == PAUSE) {
+ Log.d(TAG, "loading status is pause:" + state);
+ return -1;
+ }
+ if(DEBUG)
+ Log.d(TAG, "check md5 values of file:" + file.getName() + "path:" + file.getAbsolutePath());
+
+ int retry = 0;
+ while(retry<3){
+ if (state == PAUSE) {
+ Log.d(TAG, "loading status is pause:" + state);
+ return -1;
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }finally{
+ FileInputStream fileIn = new FileInputStream(file);
+ if (fileIn.available() < urlTotalSize) {
+ // if (PrefUtil.DEBUG)
+ Log.d(TAG, "filecheck times:"+retry+"xml size:" + fileIn.available() + "urlTotalSize:" + urlTotalSize);
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_UNKNOWN);
+ fileIn.close();
+ }else{
+ retry=4;
+ break;
+ }
+ retry ++;
+ }
+ }
+ FileInputStream fileIn = new FileInputStream(file);
+ if (fileIn.available() != urlTotalSize) {
+ // if (PrefUtil.DEBUG)
+ Log.d(TAG, "xml size:" + fileIn.available() + "urlTotalSize:" + urlTotalSize);
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_UNKNOWN);
+ fileIn.close();
+ return -1;
+ }
+ if (!MD5.checkMd5(md5, file)) {
+ if(DEBUG)
+ Log.d(TAG, "xml md5 check failed");
+ if (file.exists()) {
+ // file.delete();
+ mDownloadSize.deleteSize(urlTotalSize);
+ downloadTask.setErrorCode(DownloadUpdateTask.ERROR_UNKNOWN);
+ }
+ fileIn.close();
+ return -1;
+ } else {
+ Log.d(TAG, "xml md5 check ok");
+ fileIn.close();
+ return 0;
+ }
+ }
+
+ class SaveFileThread implements Runnable {
+ private RandomAccessFile randomFile;
+ private DownloadFile downloadFile;
+ private CountDownLatch countDownLatch;
+ private DownloadSize mDownloadSize;
+ private boolean stopFlag = false;
+
+ SaveFileThread(RandomAccessFile randomFile, DownloadFile downloadFile, CountDownLatch countDownLatch,
+ DownloadSize downloadSize) {
+ this.randomFile = randomFile;
+ this.downloadFile = downloadFile;
+ this.countDownLatch = countDownLatch;
+ this.mDownloadSize = downloadSize;
+ }
+
+ public void stopSave() {
+ stopFlag = true;
+ //downloadFile.closeHttpConn();
+ }
+
+ public void run() {
+ boolean isExceptionOccur = false;
+ try {
+ InputStream is = null;
+ // try service 3 times wait for 206 response
+ for (int count = 0; count < 3; count++) {
+ is = this.downloadFile.getInputStreamByPos();
+ if (is != null) {
+ break;
+ }
+ }
+ int length = 0;
+ int lastLen = -1;
+ if (is != null) {
+ stopFlag = false;
+ if(DEBUG) Log.d(TAG, "this.downloadFile.getStartPos():" + this.downloadFile.getStartPos() + ":"
+ + this.downloadFile.getCompleteSize()+"Thread:"+Thread.currentThread().getName());
+ long alreayload = this.downloadFile.getStartPos() + this.downloadFile.getCompleteSize();
+ this.randomFile.seek(alreayload);
+ byte[] by = new byte[1024 * 64];
+ Dao.getInstance(mContext).updataInfos(this.downloadFile.getCurrentThread(),
+ this.downloadFile.getCompleteSize(), this.downloadFile.getUrl(), true);
+ int count = 0;
+ while (!stopFlag && (length = is.read(by, 0, by.length)) > 0) {
+
+ downloadFile.setIsStart(true);
+ this.randomFile.write(by, 0, length);
+ int n=64*1024/length;
+ downloadFile.setCompleteSize(downloadFile.getCompleteSize() + length);
+ if(stopFlag)
+ break;
+ if (lastLen != 0 && (count++) % (16*n) == 0) {
+ mDownloadSize.updateSize(lastLen);
+ lastLen = 0;
+ }
+ lastLen += length;
+ if (false) {
+ Log.d(TAG, "download fileSize:" + lastLen + " threadId"
+ + this.downloadFile.getCurrentThread());
+ }
+ }
+ Dao.getInstance(mContext).updataInfos(this.downloadFile.getCurrentThread(),
+ this.downloadFile.getCompleteSize(), this.downloadFile.getUrl(), false);
+ is.close();
+ is = null;
+ downloadFile.setIsStart(false);
+ // this.randomFile.close();
+ // this.downloadFile.closeHttpConn();
+ if (DEBUG)
+ Log.d(TAG, "execute Ok Delete" + state + "Thread:" + Thread.currentThread().getName()
+ + " state:" + state);
+
+ }
+ }catch (IOException ex) {
+ // handler.sendEmptyMessage(MSG_DOWNLOAD_ERROR);
+ isExceptionOccur = true;
+ ex.printStackTrace();
+ if (DEBUG)
+ Log.d(TAG, "download file err...." + this.downloadFile + " " + ex.fillInStackTrace());
+ } catch (Exception e) {
+ e.printStackTrace();
+ isExceptionOccur = true;
+ if (DEBUG)
+ Log.d(TAG, "download err...." + this.downloadFile + " " + e.fillInStackTrace());
+ } finally {
+
+ if(DEBUG) Log.d(TAG,"finally"+Thread.currentThread().getName()+"stopFlag="+stopFlag);
+ if (this.downloadFile.getCompleteSize()+this.downloadFile.getStartPos()==this.downloadFile.getEndPos()) {
+ if(DEBUG) Log.d(TAG,"delete~!"+Thread.currentThread().getName());
+ Dao.getInstance(mContext).delete(downloadFile.getUrl(), downloadFile.getCurrentThread());
+ } else {
+ Dao.getInstance(mContext).updataInfos(this.downloadFile.getCurrentThread(),
+ this.downloadFile.getCompleteSize(), this.downloadFile.getUrl(), false);
+ }
+
+ try {
+ this.randomFile.close();
+ this.downloadFile.closeHttpConn();
+ this.countDownLatch.countDown();
+ synchronized(workers){
+ workers.remove(this);
+ }
+ } catch (Exception exp) {
+ exp.printStackTrace();
+ }
+
+ }
+ // }
+ }
+ }
+
+ public void delete(String urlstr) {
+ Dao.getInstance(mContext).delete(urlstr);
+ }
+
+ public synchronized void pause() {
+ state = PAUSE;
+ synchronized(workers){
+ for (SaveFileThread t : workers) {
+ if(!t.stopFlag){
+ t.stopSave();
+ t.downloadFile.closeHttpConn();
+ }
+ }
+ }
+ }
+
+ void reset() {
+ state = INIT;
+ }
+
+ public synchronized void resume() {
+ state = DOWNLOADING;
+ }
+
+ public synchronized void stop() {
+ state = PAUSE;
+ if (service != null && !service.isShutdown()) {
+ service.shutdown();
+ }
+ }
+}
+PK
+
@@ -857,7 +3740,105 @@ SourceFile
-
+
+ * Description: For varify MD5 values of Download File
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+package com.amlogic.update.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import android.R.string;
+import android.util.Log;
+
+public class MD5 {
+ static String TAG = "MD5";
+
+ private static String createMd5(File file) {
+ MessageDigest mMDigest;
+ FileInputStream Input = null;
+ byte buffer[] = new byte[1024];
+ int len;
+ if (!file.exists())
+ return null;
+ try {
+ mMDigest = MessageDigest.getInstance("MD5");
+ Input = new FileInputStream(file);
+ while ((len = Input.read(buffer, 0, 1024)) != -1) {
+ mMDigest.update(buffer, 0, len);
+ }
+ Input.close();
+ Input=null;
+ } catch (NoSuchAlgorithmException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return null;
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return null;
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ try {
+ Input.close();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ return null;
+ }
+ BigInteger mBInteger = new BigInteger(1, mMDigest.digest());
+ Log.v(TAG, "create_MD5=" + mBInteger.toString(16));
+ return mBInteger.toString(16);
+
+ }
+ public static boolean checkMd5(String Md5,File file){
+ String str = createMd5(file);
+ String mServMd5 = (new BigInteger(Md5,16)).toString(16);
+ if(mServMd5.equalsIgnoreCase(str)){
+ Log.d(TAG,"md5sum = " + str+"Md5="+Md5);
+ return true;
+ }else{
+ Log.d(TAG," not equals md5sum = " + str+"Md5="+Md5);
+ return false;
+ }
+ }
+ public static boolean checkMd5(String Md5, String strfile) {
+
+ File file = new File(strfile);
+ return checkMd5(Md5,file);
+ }
+ public static boolean checkMd5Files(File file1,File file2){
+ String str1 = createMd5(file1);
+ String str2 = createMd5(file2);
+ if(str1.equalsIgnoreCase(str2)){
+ Log.d(TAG,"copy varify md5sum = " + str1+"Md5="+str2);
+ return true;
+ }else{
+ Log.d(TAG," copy varify not equals md5sum = " + str1+"Md5="+str2);
+ return false;
+ }
+ }
+ public static void main(String args[]){
+ String Md5 = "003ad4693194e5012f03f33606220d80";
+ String servMd5 = "3ad4693194e5012f03f33606220d80";
+ BigInteger mBInteger = new BigInteger(Md5,16);
+ System.out.println("BInteger="+(new BigInteger(Md5,16)).toString(16));
+ BigInteger mServ = new BigInteger(servMd5,16);
+ System.out.println("servMd5="+mServ+"?"+(servMd5.equals(mBInteger.toString(16))));
+ }
+}
+PK
+
@@ -902,7 +3883,259 @@ SourceFile

-
+
+* Description:
+* @Copyright: Copyright (c) 2012
+* @Company: Amlogic
+* @author:
+* @version: 1.0
+* @time: 2013-2-17
+*/
+
+package com.amlogic.update.util;
+
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+class Dao {
+
+ private static Dao dao=null;
+ private Context context;
+ private Dao(Context context) {
+ this.context=context;
+ }
+ static Dao getInstance(Context context){
+ if(dao==null){
+ dao=new Dao(context);
+ }
+ return dao;
+ }
+
+ SQLiteDatabase getConnection() {
+ SQLiteDatabase sqliteDatabase = null;
+ try {
+ sqliteDatabase= new DatabaseHelper(context).getReadableDatabase();
+ } catch (Exception e) {
+ }
+ return sqliteDatabase;
+ }
+
+ /**
+ *
+ */
+ synchronized boolean isHasInfors(String urlstr) {
+ SQLiteDatabase database = getConnection();
+ int count = -1;
+ Cursor cursor = null;
+ try {
+ String sql = "select count(*) from "+DatabaseHelper.DOWNLOADINGRECORD+" where url=?";
+ cursor = database.rawQuery(sql, new String[] { urlstr });
+ if (cursor.moveToFirst()) {
+ count = cursor.getInt(0);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ if (null != cursor) {
+ cursor.close();
+ }
+ }
+ return count == 0;
+ }
+
+ /**
+ *
+ */
+ synchronized void saveInfos(List<DownloadFile> infos) {
+ //init
+ SQLiteDatabase database = getConnection();
+ try {
+ for (DownloadFile info : infos) {
+ String sql = "insert into "+DatabaseHelper.DOWNLOADINGRECORD+"(thread_id,start_pos, end_pos,compelete_size,url,is_start) values (?,?,?,?,?,?)";
+ Object[] bindArgs = {info.getCurrentThread(),info.getStartPos(),info.getEndPos(),info.getCompleteSize(),info.getUrl(),0};
+ database.execSQL(sql, bindArgs);
+ }
+ } catch (Exception e) {
+ //e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+
+ /**
+ *
+ */
+ synchronized List<DownloadFile> getInfos(String urlstr) {
+ List<DownloadFile> list = new ArrayList<DownloadFile>();
+ SQLiteDatabase database = getConnection();
+ Cursor cursor = null;
+ try {
+ String sql = "select thread_id, start_pos, end_pos,compelete_size,url,is_start from "+DatabaseHelper.DOWNLOADINGRECORD+" where url=?";
+ cursor = database.rawQuery(sql, new String[] { urlstr });
+ while (cursor.moveToNext()) {
+ int complete_size = cursor.getInt(3);
+ int download_startpos = cursor.getInt(1);
+ int download_endpos = cursor.getInt(2);
+ boolean download_start = (cursor.getInt(4)==1?true:false);
+ DownloadFile info = new DownloadFile(cursor.getInt(0),
+ download_startpos, download_endpos, complete_size,
+ cursor.getString(4),download_start);
+ list.add(info);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ if (null != cursor) {
+ cursor.close();
+ }
+ }
+ return list;
+ }
+
+ /**
+ *
+ */
+ synchronized void updataInfos(int threadId, int compeleteSize, String urlstr, boolean isStart) {
+ SQLiteDatabase database = getConnection();
+ int start = (isStart?1:0);
+ try {
+ String sql = "update "+DatabaseHelper.DOWNLOADINGRECORD+" set compelete_size=?,is_start=? where url=? and thread_id=?";
+ Object[] bindArgs = { compeleteSize,start,urlstr,threadId};
+ database.execSQL(sql, bindArgs);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+
+ /**
+ *
+ */
+ synchronized void resetInfos() {
+ SQLiteDatabase database = getConnection();
+ try {
+ String sql = "update "+DatabaseHelper.DOWNLOADINGRECORD+" set is_start=?";
+ Object[] bindArgs = {0};
+ database.execSQL(sql, bindArgs);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+ /**
+ *
+ */
+ synchronized void delete(String url) {
+ SQLiteDatabase database = getConnection();
+ try {
+ database.delete(DatabaseHelper.DOWNLOADINGRECORD, "url=?", new String[] { url });
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+
+ synchronized void delete(String url,int threadId) {
+ SQLiteDatabase database = getConnection();
+ try {
+ database.delete(DatabaseHelper.DOWNLOADINGRECORD, "url=?", new String[] { url });
+ String sql = "delete from "+DatabaseHelper.DOWNLOADINGRECORD+" where thread_id=? and url=?";
+ Object[] bindArgs = { threadId, url };
+ database.execSQL(sql, bindArgs);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+}
+PK
+
+
+
+
+
+
+
+
+
+SourceFile
+
+*
+
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+import android.util.Log;
+
+public class UpdatePositionStage {
+ //for <n use data;
+ private static final String KK_MEDIA="/cache/";
+ //private static final String N_MEDIA="/storage/emulated/0";
+ private static final String N_MEDIA="/data/droidota";
+ private static final String N_MEDIA_RECOVERY="/data/media/0";
+ public final static int M400ZIE = 460 * 1024 * 1024;
+ static public boolean isBigFile(File file){
+ if(file==null||!file.exists()){
+ return false;
+ }else{
+ try {
+ FileInputStream fin=new FileInputStream(file);
+ long value = fin.available();
+ fin.close();
+ return value>M400ZIE;
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return false;
+ }
+ }
+ }
+ static public String getDefaultPostion(){
+ String sdkStr = UpgradeInfo.getString("ro.build.version.sdk");
+ int sdkInt = Integer.parseInt(sdkStr);
+ if(sdkInt>=24/*for N*/)
+ return N_MEDIA;
+ else return KK_MEDIA;
+ }
+
+ /*static public String getRecoveryDir(){
+ String sdkStr = UpgradeInfo.getString("ro.build.version.sdk");
+ int sdkInt = Integer.parseInt(sdkStr);
+ if(sdkInt>=24for N)
+ return N_MEDIA_RECOVERY;
+ else return KK_MEDIA;
+ }*/
+}
+PK
+
Exceptions
@@ -926,7 +4159,7 @@ CommandRun
-
+
STRING_KEY
@@ -972,7 +4205,184 @@ CommandRun
-
+
+ * @par Copyright:
+ * - Copyright 2012 Amlogic Inc as unpublished work
+ * All Rights Reserved
+ * - The information contained herein is the confidential property
+ * of Amlogic. The use, copying, transfer or disclosure of such information
+ * is prohibited except by express written agreement with Amlogic Inc.
+ * @author tellen
+ * @version 1.0
+ * @date 2012/08/16
+ * @par function description:
+ * - 1 check device is amlogic cpu or not
+ * @warning This class may explode in your face.
+ * @note If you inherit anything from this class, you're doomed.
+ */
+
+package com.amlogic.update.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.Key;
+
+import javax.crypto.Cipher;
+
+import android.util.Log;
+
+public class DesUtils {
+ private static final String STRING_KEY = "gjaoun";
+ private static final String LOG_TAG = "ChipCheck";
+
+ private Cipher encryptCipher = null;
+ private Cipher decryptCipher = null;
+
+ //amlogic encrypt is 7c0f13b6d5986e65
+ //AMLOGIC eccrypt is a6f8b4b74ed1ed75
+ public static boolean isAmlogicChip() {
+ // following code check if chip is amlogic
+ String cupinfo = "7c0f13b6d5986e65";
+ try {
+ DesUtils des = new DesUtils(STRING_KEY);
+ //Log.i(LOG_TAG, "encrypt amlogic: " + des.encrypt("AMLOGIC"));
+ if (des.decrypt(GetCpuInfo(des)).indexOf(des.decrypt(cupinfo)) != -1) {
+ Log.i(LOG_TAG, "matched cpu ");
+ return true;
+ } else {
+ Log.e(LOG_TAG, " Sorry! Your cpu is not Amlogic,u can't run");
+ return false;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return false;
+ }
+
+ static String byteArr2HexStr(byte[] arrB) throws Exception {
+ int iLen = arrB.length;
+ StringBuffer sb = new StringBuffer(iLen * 2);
+
+ for (int i = 0; i < iLen; i++) {
+ int intTmp = arrB[i];
+ while (intTmp < 0) {
+ intTmp = intTmp + 256;
+ }
+ if (intTmp < 16) {
+ sb.append("0");
+ }
+
+ sb.append(Integer.toString(intTmp, 16));
+ }
+ return sb.toString();
+ }
+
+ static byte[] hexStr2ByteArr(String strIn) throws Exception {
+ byte[] arrB = strIn.getBytes();
+ int iLen = arrB.length;
+ byte[] arrOut = new byte[iLen / 2];
+
+ for (int i = 0; i < iLen; i = i + 2) {
+ String strTmp = new String(arrB, i, 2);
+ arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
+ }
+ return arrOut;
+ }
+
+ DesUtils() throws Exception {
+ this(STRING_KEY);
+ }
+
+ DesUtils(String strKey) throws Exception {
+ // Security.addProvider(new com.sun.crypto.provider.SunJCE());
+ Key key = getKey(strKey.getBytes());
+ encryptCipher = Cipher.getInstance("DES");
+ encryptCipher.init(Cipher.ENCRYPT_MODE, key);
+
+ decryptCipher = Cipher.getInstance("DES");
+ decryptCipher.init(Cipher.DECRYPT_MODE, key);
+ }
+
+ byte[] encrypt(byte[] arrB) throws Exception {
+ return encryptCipher.doFinal(arrB);
+ }
+
+ String encrypt(String strIn) throws Exception {
+ return byteArr2HexStr(encrypt(strIn.getBytes()));
+ }
+
+ byte[] decrypt(byte[] arrB) throws Exception {
+ return decryptCipher.doFinal(arrB);
+ }
+
+ String decrypt(String strIn) throws Exception {
+ return new String(decrypt(hexStr2ByteArr(strIn)));
+ }
+
+ private Key getKey(byte[] arrBTmp) throws Exception {
+ byte[] arrB = new byte[8];
+ for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
+ arrB[i] = arrBTmp[i];
+ }
+
+ Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
+ return key;
+ }
+
+ // get cpu info
+ static String GetCpuInfo(DesUtils des) {
+ String result = null;
+ CommandRun cmdexe = new CommandRun();
+ try {
+ String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
+ result = cmdexe.run(args, "/system/bin/");
+ result = result.toLowerCase();
+ try {
+ result = des.encrypt(result);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ // Log.i(LOG_TAG, result);
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ return result;
+ }
+
+ static class CommandRun {
+ public synchronized String run(String[] cmd, String workdirectory)
+ throws IOException {
+ String result = "";
+ try {
+ ProcessBuilder builder = new ProcessBuilder(cmd);
+ InputStream in = null;
+
+ if (workdirectory != null) {
+ builder.directory(new File(workdirectory));
+ builder.redirectErrorStream(true);
+ Process process = builder.start();
+ in = process.getInputStream();
+ byte[] re = new byte[1024];
+ while (in.read(re) != -1)
+ // Log.i(LOG_TAG, new String(re));
+ result = result + new String(re);
+ }
+
+ if (in != null) {
+ in.close();
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ return result;
+ }
+ }
+}
+PK
+
getcountry
@@ -1003,7 +4413,133 @@ SourceFile
-
+
+ * @Package com.amlogic.update
+ * @Description Copyright (c) Inspur Group Co., Ltd. Unpublished Inspur Group
+ * Co., Ltd. Proprietary & Confidential This source code and the
+ * algorithms implemented therein constitute confidential
+ * information and may comprise trade secrets of Inspur or its
+ * associates, and any use thereof is subject to the terms and
+ * conditions of the Non-Disclosure Agreement pursuant to which
+ * this source code was originally received.
+ */
+package com.amlogic.update.util;
+
+import android.app.ActivityManagerNative;
+import android.content.Context;
+import android.net.InterfaceConfiguration;
+import android.os.IBinder;
+import android.os.INetworkManagementService;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.SystemProperties;
+
+/**
+ * @ClassName UpgradeInfo
+ * @Description TODO
+ * @Date 2013-7-15
+ * @Email
+ * @Author
+ * @Version V1.0
+ */
+public class UpgradeInfo {
+ /*
+ * 1---ro.product.otaupdateurl should be defined for different server target
+ * url ex:http://10.18.19.10:8080/otaupdate/update 1---ro.product.firmware
+ * should auto-increasing according to specified specification
+ */
+ static final String UNKNOWN = "unknown";
+ public static String postUrl; // ro.product.otaupdateurl
+ public static String updating_apk_version; // = "1";
+ public static String brand; // = "MID";
+ public static String device; // = "g24ref";
+ public static String board; // = "g24ref";
+ public static String mac; // =
+ // "00.11.22.33.44.55";
+ public static String firmware /* = "00421001" */;
+ public static String android; // = "4.2.1";
+ public static String time; // =
+ // "20120301.092251";
+ public static String builder;
+ public static String fingerprint;
+ public static String country;
+ private Context mContext;
+
+ public UpgradeInfo(Context mContext) {
+ this.mContext = mContext;
+ onInit();
+ }
+
+ private void getcountry() {
+ try {
+ country = ActivityManagerNative.getDefault().getConfiguration().locale
+ .getCountry();
+ } catch (RemoteException e) {
+ }
+ }
+
+ static String makePostString() {
+ return null;
+ }
+
+ public static String getString(String property) {
+ return SystemProperties.get(property, UNKNOWN);
+ }
+ public static boolean isDebugAble(){
+ String debug = getString("rw.update.debug");
+ if(debug.equals(true)){
+ return true;
+ }
+ return false;
+ }
+ private String getMacAddr() {
+ IBinder b = ServiceManager
+ .getService(Context.NETWORKMANAGEMENT_SERVICE);
+ INetworkManagementService networkManagement = INetworkManagementService.Stub
+ .asInterface(b);
+ if (networkManagement != null) {
+ InterfaceConfiguration iconfig = null;
+ try {
+ iconfig = networkManagement.getInterfaceConfig("eth0");
+ } catch (Exception e) {
+ // e.printStackTrace();
+ } finally {
+ return "";
+ }
+ } else {
+ return "";
+ }
+ }
+
+ private String getVersionCode() {
+ String packageName = mContext.getPackageName();
+ int versionCode = 0;
+ try {
+ versionCode = mContext.getPackageManager().getPackageInfo(
+ packageName, 0).versionCode;
+ } catch (Exception e) {
+ }
+ return String.valueOf(versionCode);
+ }
+
+ private void onInit() {
+ getcountry();
+ updating_apk_version = getVersionCode();
+ brand = getString("ro.product.brand");
+ device = getString("ro.product.device");
+ board = getString("ro.product.board");
+ mac = getMacAddr();
+ postUrl = getString("ro.product.otaupdateurl");
+ firmware = getString("ro.product.firmware");
+ android = getString("ro.build.version.release");
+ time = getString("ro.build.date.utc");
+ builder = getString("ro.build.user");
+ fingerprint = getString("ro.build.fingerprint");
+ }
+
+}
+PK
+
@@ -1021,6 +4557,79 @@ SourceFile
+
+ * Description:
+ * @Copyright: Copyright (c) 2012
+ * @Company: Amlogic
+ * @version: 1.0
+ */
+
+package com.amlogic.update.util;
+
+import android.content.Context;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+
+import java.util.List;
+
+class DatabaseHelper extends SQLiteOpenHelper {
+
+ static final String DOWNTASKTABLE = "download_task";
+ static final String DOWNLOADINGRECORD = "record_task";
+
+ /**
+ * @param context
+ * @param name
+ * @param version
+ */
+ DatabaseHelper(Context context, String name, int version) {
+ super(context, name, null, version);
+ }
+
+ /**
+ * @param context
+ * @param name
+ * @param version
+ */
+ DatabaseHelper(Context context) {
+ super(context, "download.db", null, VERSION);
+ }
+
+ private static final int VERSION = 1;
+
+ @Override
+ public void onCreate(SQLiteDatabase db) {
+ db.execSQL("create table " + DOWNTASKTABLE
+ + "(_id integer PRIMARY KEY AUTOINCREMENT, file_name char, "
+ + "file_location char,file_md5 char,url char)");
+ db.execSQL("create table "
+ + DOWNLOADINGRECORD
+ + "(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "
+ + "start_pos integer, end_pos integer, compelete_size integer,url char,is_start integer)");
+ }
+
+ @Override
+ public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
+ }
+
+ DatabaseHelper(Context context, String name) {
+ this(context, name, VERSION);
+ }
+
+ void cleartable(String name) {
+ SQLiteDatabase database = getWritableDatabase();
+ try {
+ database.delete(name, "_id>=?", new String[] { "0" });
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (null != database) {
+ database.close();
+ }
+ }
+ }
+
+}PK
<classpath>
@@ -1047,59 +4656,96 @@ PK
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
-PK
+PK
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
+p<
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml
index 9c569df..0eba563 100644
--- a/res/values-zh-rCN/strings.xml
+++ b/res/values-zh-rCN/strings.xml
@@ -86,7 +86,8 @@
<string name="net_status_change">"当前网络环境发生改变"</string>
<string name="stop_download_first">"请先停止下载!"</string>
<string name="net_error">"查找更新失败,请检查网络连接是否正确"</string>
- <string name="capacty_not_enough">"存储空间不够,可能导致下载失败"</string>
+ <string name="capacty_not_enough">"外部设备存储空间不够,请释放外设空间"</string>
+ <string name="data_not_enough">"设备内存不够,请释放内存空间"</string>
<string name="download_error">"下载失败"</string>
<string name="check_title">"系统更新"</string>
<string name="check_summary">"检测到新版本,点击进入更新"</string>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 9d19a01..152cda2 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -6,7 +6,8 @@
<string name="update_online">Online update</string>
<string name="update_local">Local update</string>
<string name="restart_system">Restart System</string>
- <string name="capacty_not_enough">External Storage Capacity Cannot Support This Update</string>
+ <string name="capacty_not_enough">External Storage Capacity Not Enough,Please Release Memory</string>
+ <string name="data_not_enough">Device Memory Not Enough,Please Release Memory</string>
<string name="backup_title">Backup Your Data</string>
<string name="backup_info">System Will be Reset,Will Backup Your Data</string>
<string name="backup_ok">YES,Backup</string>
diff --git a/src/com/droidlogic/otaupgrade/InstallPackage.java b/src/com/droidlogic/otaupgrade/InstallPackage.java
index 4d24060..571d4c8 100644
--- a/src/com/droidlogic/otaupgrade/InstallPackage.java
+++ b/src/com/droidlogic/otaupgrade/InstallPackage.java
@@ -42,7 +42,7 @@ public class InstallPackage extends LinearLayout implements OtaUpgradeUtils.Prog
private Button mDismiss;
private int mUpdateMode;
private PrefUtils mPref = null;
-
+ private boolean isDelUpdate = false;
public InstallPackage(Context context, AttributeSet attrs) {
super(context, attrs);
mInflater = LayoutInflater.from(context);
@@ -94,6 +94,7 @@ public class InstallPackage extends LinearLayout implements OtaUpgradeUtils.Prog
@Override
public void run() {
mPref.copyBKFile();
+ mUpdateUtils.setDeleteSource(isDelUpdate);
mUpdateUtils.upgrade(new File(mPackagePath),
InstallPackage.this, mUpdateMode);
}
@@ -106,6 +107,10 @@ public class InstallPackage extends LinearLayout implements OtaUpgradeUtils.Prog
mUpdateMode = updateMode;
}
+ public void setDelParam(boolean wipe) {
+ isDelUpdate = wipe;
+ }
+
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!mDismiss.isEnabled() && (keyCode == KeyEvent.KEYCODE_BACK)) {
diff --git a/src/com/droidlogic/otaupgrade/LoaderReceiver.java b/src/com/droidlogic/otaupgrade/LoaderReceiver.java
index a1f5459..a5b6e0b 100644
--- a/src/com/droidlogic/otaupgrade/LoaderReceiver.java
+++ b/src/com/droidlogic/otaupgrade/LoaderReceiver.java
@@ -62,9 +62,11 @@ public class LoaderReceiver extends BroadcastReceiver {
mContext = context;
mPref = new PrefUtils ( mContext );
getBackUpFileName();
- Log.d ( TAG, "action:" + intent.getAction() );
if ( intent.getAction().equals ( Intent.ACTION_BOOT_COMPLETED ) ||
intent.getAction().equals ( RESTOREDATA ) ) {
+ if (intent.getAction().equals ( Intent.ACTION_BOOT_COMPLETED )) {
+ mPref.clearData();
+ }
mPref.setBoolean ( "Boot_Checked", true );
afterReboot();
} else if ( intent.getAction().equals ( BACKUPDATA ) ) {
diff --git a/src/com/droidlogic/otaupgrade/MainActivity.java b/src/com/droidlogic/otaupgrade/MainActivity.java
index 7851e4e..4e63ced 100644
--- a/src/com/droidlogic/otaupgrade/MainActivity.java
+++ b/src/com/droidlogic/otaupgrade/MainActivity.java
@@ -145,8 +145,7 @@ public class MainActivity extends Activity implements OnClickListener {
if (item.getItemId() == R.id.about) {
AlertDialog.Builder builder = new Builder(MainActivity.this);
- if (getResources().getConfiguration().locale.getCountry()
- .equals("CN")) {
+ if (getResources().getConfiguration().locale.getCountry().equals("CN")) {
builder.setMessage(getFromAssets(VERSION_NAME + "_cn"));
} else {
builder.setMessage(getFromAssets(VERSION_NAME));
diff --git a/src/com/droidlogic/otaupgrade/PrefUtils.java b/src/com/droidlogic/otaupgrade/PrefUtils.java
index c30a5f7..46a026a 100644
--- a/src/com/droidlogic/otaupgrade/PrefUtils.java
+++ b/src/com/droidlogic/otaupgrade/PrefUtils.java
@@ -61,6 +61,7 @@ public class PrefUtils implements DownloadUpdateTask.CheckPathCallBack{
public static final String PREF_START_RESTORE = "retore_start";
public static final String PREF_AUTO_CHECK = "auto_check";
static final String FlagFile = ".wipe_record";
+ public static final String DATA_UPDATE = "/data/droidota/update.zip";
private Context mContext;
private SharedPreferences mPrefs;
@@ -91,6 +92,21 @@ public class PrefUtils implements DownloadUpdateTask.CheckPathCallBack{
setString ( PREFS_UPDATE_DESC, desc );
}
+ public void clearData() {
+ String filePath = getUpdatePath();
+ File file = null;
+ if ( filePath != null ) {
+ file = new File(filePath);
+ if (file.exists()) {
+ file.delete();
+ }
+ }
+ file = new File(DATA_UPDATE);
+ if (file.exists()) {
+ file.delete();
+ }
+ }
+
public String getDescri() {
return mPrefs.getString ( PREFS_UPDATE_DESC, "" );
}
@@ -135,7 +151,9 @@ public class PrefUtils implements DownloadUpdateTask.CheckPathCallBack{
public String getUpdatePath() {
String path = mPrefs.getString ( PREFS_UPDATE_FILEPATH, null );
- path = onExternalPathSwitch(path);
+ if (path != null) {
+ path = onExternalPathSwitch(path);
+ }
return path;
}
diff --git a/src/com/droidlogic/otaupgrade/UpdateActivity.java b/src/com/droidlogic/otaupgrade/UpdateActivity.java
index 710e390..6bba832 100755..100644
--- a/src/com/droidlogic/otaupgrade/UpdateActivity.java
+++ b/src/com/droidlogic/otaupgrade/UpdateActivity.java
@@ -96,7 +96,7 @@ public class UpdateActivity extends Activity {
private QueryThread[] mQueryThread = new QueryThread[2];
private PrefUtils mPreference;
private Handler mHandler = new Handler();
- private int mDownSize = 0;
+ private long mDownSize = 0;
private Button mCheckBtn;
private BroadcastReceiver sdcardListener = new BroadcastReceiver() {
@Override
@@ -129,7 +129,7 @@ public class UpdateActivity extends Activity {
Intent extrasIntent = getIntent();
String action = extrasIntent.getAction();
boolean b = mServiceBinder.getTaskRunnningStatus(UpdateService.TASK_ID_DOWNLOAD) == UpdateTasks.RUNNING_STATUS_UNSTART;
- int lastDownSize = mServiceBinder.getTaskProgress(UpdateService.TASK_ID_DOWNLOAD);
+ long lastDownSize = mServiceBinder.getTaskProgress(UpdateService.TASK_ID_DOWNLOAD);
if ((lastDownSize == 0) && b) {
mServiceBinder.startTask(UpdateService.TASK_ID_CHECKING);
@@ -179,7 +179,7 @@ public class UpdateActivity extends Activity {
mServiceBinder.setTaskPause(UpdateService.TASK_ID_DOWNLOAD);
}
}
- }else if ((activeInfo != null) && activeInfo.isConnected()) {
+ }else if ((activeInfo != null) && activeInfo.isConnected()&&Integer.valueOf(R.string.download_resume).equals(mCombineBtn.getTag())) {
mCombineBtn.setText(R.string.download_pause);
mCombineBtn.setTag(Integer
.valueOf(R.string.download_pause));
@@ -291,21 +291,22 @@ public class UpdateActivity extends Activity {
private boolean handleSDcardSituation() {
boolean isScriptAsk = mPreference.getScriptAsk();
- if (isScriptAsk) {
- String filePath = mPreference.getUpdatePath();
- File saveFilePath = new File(filePath).getParentFile();
+ String filePath = mPreference.getUpdatePath();
+ File saveFilePath = null;
+ long freeSpace = 0L;
+ mDownSize = mPreference.getFileSize();
+ if ( filePath == null ) {return false;}
+ if ( isScriptAsk ) {
+ saveFilePath = new File(filePath).getParentFile();
if (saveFilePath.canWrite()) {
- StatFs statFs = new StatFs(saveFilePath.getAbsolutePath());
- int blockSize = statFs.getBlockSize();
- int avaliableBlocks = statFs.getAvailableBlocks();
- int totalBlocks = statFs.getBlockCount();
- mDownSize = (int) mPreference.getFileSize();
+ freeSpace = saveFilePath.getFreeSpace();
if ((mDownSize > 0) &&
- ((mDownSize / blockSize) > avaliableBlocks)) {
+ (mDownSize > freeSpace)) {
Toast.makeText(UpdateActivity.this,
R.string.capacty_not_enough, Toast.LENGTH_LONG).show();
+ return false;
} else {
if (sdcardFlag && isScriptAsk) {
IntentFilter intentFilter = new IntentFilter();
@@ -327,6 +328,16 @@ public class UpdateActivity extends Activity {
return false;
}
+ } else {
+ //data test now
+ saveFilePath = new File(filePath).getParentFile();
+ freeSpace = saveFilePath.getFreeSpace();
+ if ((mDownSize > 0) &&
+ (mDownSize > freeSpace)) {
+ Toast.makeText(UpdateActivity.this,
+ R.string.data_not_enough, Toast.LENGTH_LONG).show();
+ return false;
+ }
}
if (networkFlag) {
@@ -409,6 +420,7 @@ public class UpdateActivity extends Activity {
InstallPackage dlgView = (InstallPackage) inflater.inflate(R.layout.install_ota,
null, false);
dlgView.setPackagePath(mPreference.getUpdatePath());
+ dlgView.setDelParam(true);
dlgView.setParamter(UpdateMode);
dlg.setCancelable(false);
dlg.setContentView(dlgView);
@@ -423,7 +435,7 @@ public class UpdateActivity extends Activity {
}
});
- mDownSize = (int) mPreference.getFileSize();
+ mDownSize = mPreference.getFileSize();
mCancel.setOnClickListener(new OnClickListener() {
@Override
@@ -495,7 +507,7 @@ public class UpdateActivity extends Activity {
if (mDownSize > 0 && lastProgress > 10*1024) {
mProgress.setVisibility(View.VISIBLE);
- mProgress.setMax((int) mDownSize);
+ mProgress.setMax((int)(mDownSize/1024));
mPercent.setVisibility(View.VISIBLE);
if (lastProgress < mDownSize) {
@@ -513,7 +525,7 @@ public class UpdateActivity extends Activity {
R.string.scan_tip));
}
- mProgress.setProgress((int) lastProgress);
+ mProgress.setProgress((int)(lastProgress/1024));
}
});
}
diff --git a/src/com/droidlogic/otaupgrade/UpdateService.java b/src/com/droidlogic/otaupgrade/UpdateService.java
index 07ce20b..05e038b 100644
--- a/src/com/droidlogic/otaupgrade/UpdateService.java
+++ b/src/com/droidlogic/otaupgrade/UpdateService.java
@@ -236,8 +236,8 @@ public class UpdateService extends Service {
return errorCode;
}
- public int getTaskProgress(int taskId) {
- int progress = -1;
+ public long getTaskProgress(int taskId) {
+ long progress = -1;
switch (taskId) {
case TASK_ID_CHECKING: