diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 846025d05..570a897a9 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -17,7 +17,7 @@ + android:versionName="0.5.0" > 2 - + @string/update_server_google @string/update_server_qiniu - @string/update_server_gokuai 0 1 - 2 diff --git a/src/com/hippo/ehviewer/AppContext.java b/src/com/hippo/ehviewer/AppContext.java index ce015e1e3..972348d83 100644 --- a/src/com/hippo/ehviewer/AppContext.java +++ b/src/com/hippo/ehviewer/AppContext.java @@ -33,7 +33,6 @@ import com.hippo.ehviewer.util.Config; import com.hippo.ehviewer.util.Crash; import com.hippo.ehviewer.util.Download; import com.hippo.ehviewer.util.Favorite; -import com.hippo.ehviewer.util.ThreadPool; import com.hippo.ehviewer.util.Ui; import com.hippo.ehviewer.widget.MaterialToast; @@ -46,8 +45,6 @@ public class AppContext extends Application implements UncaughtExceptionHandler private Thread.UncaughtExceptionHandler mDefaultHandler; - private ThreadPool mNetworkThreadPool; - private static AppContext sInstance; public static AppContext getInstance() { @@ -63,7 +60,6 @@ public class AppContext extends Application implements UncaughtExceptionHandler super.onCreate(); // Init everything - mNetworkThreadPool = new ThreadPool(2, 4); Config.init(this); Ui.init(this); Crash.init(this); @@ -89,10 +85,6 @@ public class AppContext extends Application implements UncaughtExceptionHandler } } - public ThreadPool getNetworkThreadPool() { - return mNetworkThreadPool; - } - /** * {@inheritDoc} */ diff --git a/src/com/hippo/ehviewer/UpdateHelper.java b/src/com/hippo/ehviewer/UpdateHelper.java index 919e4e749..e4f13a0f7 100644 --- a/src/com/hippo/ehviewer/UpdateHelper.java +++ b/src/com/hippo/ehviewer/UpdateHelper.java @@ -28,197 +28,180 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; -import android.os.Handler; -import android.os.Message; +import android.os.Process; import android.support.v4.app.NotificationCompat; -import com.hippo.ehviewer.network.Downloader; import com.hippo.ehviewer.network.HttpHelper; import com.hippo.ehviewer.util.Config; -import com.hippo.ehviewer.util.Future; -import com.hippo.ehviewer.util.FutureListener; -import com.hippo.ehviewer.util.ThreadPool; import com.hippo.ehviewer.util.Utils; -import com.hippo.ehviewer.util.ThreadPool.Job; -import com.hippo.ehviewer.util.ThreadPool.JobContext; // TODO return onFailure when downloading update or check update // TODO add disable to achieve -public class UpdateHelper { +public class UpdateHelper implements Runnable { @SuppressWarnings("unused") private static final String TAG = "UpdateHelper"; - + private static final String UPDATE_API = "http://www.ehviewer.com/API"; private static final String HEADER = "Ehviewer-"; private static final String FOOTER = ".apk"; - - - private AppContext mAppContext; + + + private final AppContext mAppContext; private OnCheckUpdateListener mListener; - + private static boolean mEnabled = true; - + public interface OnCheckUpdateListener { public void onSuccess(String version, long size, String url, String fileName, String info); public void onNoUpdate(); public void onFailure(String eMsg); } - + public UpdateHelper(AppContext appContext) { mAppContext = appContext; } - + public UpdateHelper SetOnCheckUpdateListener(OnCheckUpdateListener listener) { this.mListener = listener; return this; } - + public void autoCheckUpdate() { if (Config.getUpdateDate() < Utils.getDate()) checkUpdate(); } - + public static void setEnabled(boolean enabled) { mEnabled = enabled; } - - + + class CheckUpdatePackage { public OnCheckUpdateListener listener; - public AppContext appContext; - public String pageContext; - public HttpHelper hp; + public String body; + public String emesg; } - - public void checkUpdate() { + + private void send(CheckUpdatePackage _package) { + AppHandler.getInstance().post(new Respond(_package)); + } + + @Override + public void run() { + CheckUpdatePackage _package = new CheckUpdatePackage(); + _package.listener = mListener; final HttpHelper hp = new HttpHelper(mAppContext); - ThreadPool threadPool = mAppContext.getNetworkThreadPool(); - threadPool.submit(new Job() { - @Override - public String run(JobContext jc) { - if (!mEnabled) { - return "working"; - } - - mEnabled = false; - - PackageManager pm = mAppContext.getPackageManager(); - PackageInfo pi = null; - try { - pi = pm.getPackageInfo(mAppContext.getPackageName(), PackageManager.GET_ACTIVITIES); - - JSONObject jo = new JSONObject(); - jo.put("method", "update"); - - JSONObject detailJO = new JSONObject(); - detailJO.put("version", pi.versionName); - detailJO.put("server", Config.getUpdateServer()); - - jo.put("detail", detailJO); - - return hp.postJson(UPDATE_API, jo); - } catch (NameNotFoundException e) { - e.printStackTrace(); - return "NameNotFound"; - } catch (JSONException e) { - e.printStackTrace(); - return "JSONException"; - } - } - }, new FutureListener() { - @Override - public void onFutureDone(Future future) { - String pageContext = future.get(); - CheckUpdatePackage checkUpdatePackage = new CheckUpdatePackage(); - checkUpdatePackage.appContext = mAppContext; - checkUpdatePackage.listener = mListener; - checkUpdatePackage.pageContext = pageContext; - checkUpdatePackage.hp = hp; - Message msg = new Message(); - msg.obj = checkUpdatePackage; - - mHandler.sendMessage(msg); - } - }); + if (!mEnabled) { + _package.body = "working"; + send(_package); + return; + } + + mEnabled = false; + + PackageManager pm = mAppContext.getPackageManager(); + PackageInfo pi = null; + try { + pi = pm.getPackageInfo(mAppContext.getPackageName(), PackageManager.GET_ACTIVITIES); + + JSONObject jo = new JSONObject(); + jo.put("method", "update"); + + JSONObject detailJO = new JSONObject(); + detailJO.put("version", pi.versionName); + detailJO.put("server", Config.getUpdateServer()); + + jo.put("detail", detailJO); + + _package.body = hp.postJson(UPDATE_API, jo); + _package.emesg = hp.getEMsg(); + send(_package); + } catch (NameNotFoundException e) { + e.printStackTrace(); + _package.body = "NameNotFound"; + send(_package); + } catch (JSONException e) { + e.printStackTrace(); + _package.body = "JSONException"; + send(_package); + } } - - // TODO move dialog into listener - private static Handler mHandler = new Handler() { + + public void checkUpdate() { + Thread thread = new Thread(this); + thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND); + thread.start(); + } + + private class Respond implements Runnable { + + CheckUpdatePackage mPackage; + + public Respond(CheckUpdatePackage _package) { + mPackage = _package; + } + @Override - public void handleMessage(Message msg) { - CheckUpdatePackage checkUpdatePackage = (CheckUpdatePackage)msg.obj; - OnCheckUpdateListener listener = checkUpdatePackage.listener; - AppContext appContext = checkUpdatePackage.appContext; - String pageContext = checkUpdatePackage.pageContext; - - if (pageContext != null) { + public void run() { + OnCheckUpdateListener listener = mPackage.listener; + String body = mPackage.body; + if (body != null) { Config.setUpdateDate(); - - if (pageContext.equals("working")) { - if (listener != null) - listener.onFailure("正在检查更新或者下载更新"); // TODO - } - else if (pageContext.equals("NameNotFound")) { - if (listener != null) - listener.onFailure("NameNotFound"); // TODO - - } else if (pageContext.equals("JSONException")) { - if (listener != null) - listener.onFailure("JSONException"); // TODO - + + if (listener == null) + return; + + if (body.equals("working")) { + listener.onFailure("正在检查更新或者下载更新"); // TODO + } else if (body.equals("NameNotFound")) { + listener.onFailure("NameNotFound"); // TODO + } else if (body.equals("JSONException")) { + listener.onFailure("JSONException"); // TODO } else { try { - - JSONObject jo = new JSONObject(pageContext); + JSONObject jo = new JSONObject(body); JSONObject updateJO = jo.getJSONObject("update"); - + if (updateJO.has("error")) { - if (listener != null) - listener.onFailure(updateJO.getString("error")); + listener.onFailure(updateJO.getString("error")); } else { String version = updateJO.getString("version"); if (version.equals("none")) { - if (listener != null) - listener.onNoUpdate(); + listener.onNoUpdate(); } else { long size = updateJO.getLong("size"); String url = updateJO.getString("url"); String info = updateJO.getString("info"); - - if (listener != null) - listener.onSuccess(version, size, url, HEADER + version + FOOTER, info); + + listener.onSuccess(version, size, url, HEADER + version + FOOTER, info); } } } catch (JSONException e) { e.printStackTrace(); - if (listener != null) - listener.onFailure(appContext.getString(R.string.em_host_error)); + listener.onFailure("JSONException"); } } - } else { - if (listener != null) - listener.onFailure(checkUpdatePackage.hp.getEMsg()); } } - }; - - public static class UpdateListener implements Downloader.OnDownloadListener { - private Context mContext; - private String mFileName; - - private NotificationManager mNotifyManager; - + } + + public static class UpdateListener implements HttpHelper.OnDownloadListener { + private final Context mContext; + private final String mFileName; + + private final NotificationManager mNotifyManager; + public UpdateListener(Context context, String fileName) { mContext = context; mFileName = fileName; mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); } - + @Override public void onDownloadStartConnect() { - NotificationCompat.Builder builder = + NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext) .setSmallIcon(android.R.drawable.stat_sys_download) .setContentTitle(mContext.getString(R.string.start_update)) @@ -227,10 +210,10 @@ public class UpdateHelper { .setTicker(mContext.getString(R.string.start_update)); mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build()); } - + @Override public void onDownloadStartDownload(int totalSize) { - NotificationCompat.Builder builder = + NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext) .setSmallIcon(android.R.drawable.stat_sys_download) .setContentTitle(mContext.getString(R.string.download_update)) @@ -239,10 +222,11 @@ public class UpdateHelper { .setOngoing(true); mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build()); } + @Override public void onDownloadStatusUpdate( int downloadSize, int totalSize) { - NotificationCompat.Builder builder = + NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext) .setSmallIcon(android.R.drawable.stat_sys_download) .setContentTitle(mContext.getString(R.string.download_update)) @@ -250,11 +234,11 @@ public class UpdateHelper { .setProgress(totalSize, downloadSize, false) .setOngoing(true); mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build()); - } + @Override public void onDownloadOver(int status, String eMsg) { - if (status == Downloader.COMPLETED) { + if (status == HttpHelper.DOWNLOAD_OK_CODE) { mNotifyManager.cancel(NotificationId.UPDATE_ID); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(Config.getDownloadPath(), mFileName)), @@ -262,7 +246,7 @@ public class UpdateHelper { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } else { - NotificationCompat.Builder builder = + NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext) .setSmallIcon(android.R.drawable.stat_sys_warning) .setContentTitle(mContext.getString(R.string.update_failed)) diff --git a/src/com/hippo/ehviewer/ehclient/EhClient.java b/src/com/hippo/ehviewer/ehclient/EhClient.java index 3298d3664..9ef297d62 100644 --- a/src/com/hippo/ehviewer/ehclient/EhClient.java +++ b/src/com/hippo/ehviewer/ehclient/EhClient.java @@ -30,7 +30,6 @@ import org.json.JSONObject; import android.graphics.Bitmap; import android.os.Handler; -import android.os.Message; import android.os.Process; import com.hippo.ehviewer.Analytics; @@ -46,16 +45,11 @@ import com.hippo.ehviewer.data.LofiGalleryDetail; import com.hippo.ehviewer.data.PreviewList; import com.hippo.ehviewer.network.HttpHelper; import com.hippo.ehviewer.util.Config; -import com.hippo.ehviewer.util.Future; -import com.hippo.ehviewer.util.FutureListener; -import com.hippo.ehviewer.util.ThreadPool; -import com.hippo.ehviewer.util.ThreadPool.Job; -import com.hippo.ehviewer.util.ThreadPool.JobContext; import com.hippo.ehviewer.util.Utils; public class EhClient { - - private static final String TAG = "EhClient"; + @SuppressWarnings("unused") + private static final String TAG = EhClient.class.getSimpleName(); public static final int FAVORITE_SLOT_NUM = 10; @@ -83,7 +77,6 @@ public class EhClient { public static final int NO_AVATAR = 0x2; private final AppContext mAppContext; - private final ThreadPool mThreadPool; private final Handler mHandler; private final EhInfo mInfo; @@ -99,7 +92,6 @@ public class EhClient { private EhClient(AppContext appContext) { mAppContext = appContext; - mThreadPool = mAppContext.getNetworkThreadPool(); mHandler = AppHandler.getInstance(); mInfo = EhInfo.getInstance(appContext); } @@ -275,26 +267,6 @@ public class EhClient { return mInfo.getAvatar(); } - private static final int GET_MANGA_URL = 0x6; - - private static Handler mHandler1 = new Handler() { - @Override - public void handleMessage(Message msg) { - - switch (msg.what) { - - case GET_MANGA_URL: - GetMangaUrlPackage getMangaUrlPackage = (GetMangaUrlPackage) msg.obj; - OnGetMangaUrlListener listener7 = getMangaUrlPackage.listener; - if (getMangaUrlPackage.strs != null) - listener7.onSuccess(getMangaUrlPackage.checkFlag, getMangaUrlPackage.strs); - else - listener7.onFailure(getMangaUrlPackage.checkFlag, getMangaUrlPackage.eMsg); - break; - } - }; - }; - public interface OnLoginListener { public void onSuccess(); public void onGetAvatar(int code); @@ -901,80 +873,6 @@ public class EhClient { thread.start(); } - // Get Manga url and next page - private class GetMangaUrlPackage { - public Object checkFlag; - public String[] strs; - public OnGetMangaUrlListener listener; - public String eMsg; - - public GetMangaUrlPackage(Object checkFlag, String[] strs, OnGetMangaUrlListener listener, - String eMsg) { - this.checkFlag = checkFlag; - this.strs = strs; - this.listener = listener; - this.eMsg = eMsg; - } - } - - private class GetMangaUrlRunnable implements Runnable { - private final String url; - - public String[] strs; - public String eMsg; - - public GetMangaUrlRunnable(String url) { - this.url = url; - } - - @Override - public void run() { - strs = null; - - HttpHelper hp = new HttpHelper(mAppContext); - String pageContent = hp.get(url); - if (pageContent != null) { - Pattern p = Pattern.compile("]*id=\"prev\"[^<>]*href=\"([^<>\"]+)\">]*/>.+]id=\"next\"[^<>]*href=\"([^<>\"]+)\">]*/>.+]*src=\"([^<>\"]+?)\"[^<>]*style=\"[^<>\"]*\"[^<>]*/>"); - //.compile("]*href=\"([^<>\"]+?)\"[^<>]*>]*src=\"([^<>\"]+?)\"[^<>]*style=\"[^<>\"]*\"[^<>]*/>"); - Matcher m = p.matcher(pageContent); - if (m.find() && m.groupCount() == 3) { - strs = new String[3]; - if (url.equals(m.group(1))) - strs[0] = "first"; - else - strs[0] = m.group(1); - if (url.equals(m.group(2))) - strs[1] = "last"; - else - strs[1] = m.group(2); - strs[2] = Utils.unescapeXml(m.group(3)); - } else - eMsg = mAppContext.getString(R.string.em_parser_error); - } else - eMsg = hp.getEMsg(); - } - } - - public void getMangaUrl(String url, final Object checkFlag, final OnGetMangaUrlListener listener) { - - final GetMangaUrlRunnable task = new GetMangaUrlRunnable(url); - mThreadPool.submit(new Job() { - @Override - public Object run(JobContext jc) { - task.run(); - return null; - } - }, new FutureListener() { - @Override - public void onFutureDone(Future future) { - Message msg = new Message(); - msg.what = GET_MANGA_URL; - msg.obj = new GetMangaUrlPackage(checkFlag, task.strs, listener, task.eMsg); - mHandler1.sendMessage(msg); - } - }); - } - // Post comment public interface OnCommentListener { void onSuccess(List comments); diff --git a/src/com/hippo/ehviewer/gallery/GalleryView.java b/src/com/hippo/ehviewer/gallery/GalleryView.java index 054622abf..f7ed48a59 100644 --- a/src/com/hippo/ehviewer/gallery/GalleryView.java +++ b/src/com/hippo/ehviewer/gallery/GalleryView.java @@ -24,6 +24,7 @@ import android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import android.view.animation.AccelerateDecelerateInterpolator; +import android.view.animation.OvershootInterpolator; import com.hippo.ehviewer.AppHandler; import com.hippo.ehviewer.R; @@ -1002,7 +1003,7 @@ public class GalleryView extends GLView public MyGestureListener() { mDoubleTapRunner.setDuration(Constants.ANIMATE_TIME); - //mDoubleTapRunner.setInterpolator(new OvershootInterpolator()); + mDoubleTapRunner.setInterpolator(new OvershootInterpolator()); } @Override diff --git a/src/com/hippo/ehviewer/network/Downloader.java b/src/com/hippo/ehviewer/network/Downloader.java deleted file mode 100644 index 185d79f96..000000000 --- a/src/com/hippo/ehviewer/network/Downloader.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (C) 2014 Hippo Seven - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.hippo.ehviewer.network; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.UnknownHostException; - -import org.apache.http.conn.ConnectTimeoutException; - -import android.content.Context; - -import com.hippo.ehviewer.R; -import com.hippo.ehviewer.exception.FileException; -import com.hippo.ehviewer.exception.NoSdCardException; -import com.hippo.ehviewer.exception.StopRequestException; -import com.hippo.ehviewer.util.Constants; -import com.hippo.ehviewer.util.Log; -import com.hippo.ehviewer.util.Utils; - -// TODO 添加检查次磁盘空间 - -/** - * Thread unsafe - * - * @author Hippo - * - */ -public class Downloader implements Runnable { - private static final String TAG = "Downloader"; - - public static final int NONE = 0x0; - public static final int READY = 0x1; - public static final int CONNECTING = 0x2; - public static final int DOWNLOADING = 0x3; - public static final int FAILED = 0x4; - public static final int COMPLETED = 0x5; - public static final int STOPED = 0x6; - - private static final int MAX_RETRY = 3; - - private final Context mContext; - - private File mFile; - private File mFolder; - private String mPath; - private String mFileName; - private URL mUrl; - private final Controlor mContorlor; - - private int mTotalSize; - // If support Content-Range, start from it - private int mDownloadSize = 0; - private int mRedirectionCount = 0; - - private int status = NONE; - private OnDownloadListener mListener; - - private Exception mException; - - public interface OnDownloadListener { - public void onDownloadStartConnect(); - public void onDownloadStartDownload(int totalSize); - public void onDownloadStatusUpdate(int downloadSize, int totalSize); - /** - * FAILED or COMPLETED or STOPED - * @param status - */ - public void onDownloadOver(int status, String eMsg); - } - - public class Controlor { - private boolean mStop = false; - - public synchronized void stop() { - mStop = true; - } - - public synchronized void reset() { - mStop = false; - } - - public synchronized boolean isStop() { - return mStop; - } - } - - public Controlor resetData(String path, String fileName, String urlStr) throws MalformedURLException { - mPath = path; - mFileName = fileName; - mUrl = new URL(urlStr); - mException = null; - - mDownloadSize = 0; - mRedirectionCount = 0; - status = READY; - - mContorlor.reset(); - return mContorlor; - } - - public void setOnDownloadListener(OnDownloadListener listener) { - mListener = listener; - } - - public Downloader(Context context) { - mContext = context; - mContorlor = new Controlor(); - } - - - public String getEMsg() { - if (mException == null) - return mContext.getString(R.string.em_unknown_error); - - else if (mException instanceof MalformedURLException) - return mContext.getString(R.string.em_url_format_error); - - else if (mException instanceof ConnectTimeoutException || - mException instanceof SocketTimeoutException) - return mContext.getString(R.string.em_timeout); - - else if (mException instanceof UnknownHostException) - return mContext.getString(R.string.em_unknown_host); - - else if (mException instanceof SocketException) - return "SocketException : " + mException.getMessage(); - - else if (mException instanceof NoSdCardException) - return mContext.getString(R.string.em_no_sdcard); - - else if (mException instanceof FileException) - return ((FileException)mException).getMessage(); - - else - return mException.getMessage(); - } - - @Override - public void run() { - int retryTimes = 0; - if (true) { - - boolean checkFolder = false; - - try { - initFolder(); - checkFolder = true; - } catch (Exception e) { - mException = e; - e.printStackTrace(); - } - - while(checkFolder) { - try { - if (mContorlor.isStop()) - throw new StopRequestException(); - mRedirectionCount = 0; - status = READY; - executeDownload(); - status = COMPLETED; - break; - } catch (Exception e) { - mException = e; - e.printStackTrace(); - if (mContorlor.isStop() || retryTimes > MAX_RETRY) { - status = FAILED; - break; - } - retryTimes++; - } - } - } else - mException = new NoSdCardException(); - - if (mContorlor.isStop()) - status = STOPED; - - if (status != COMPLETED && mFile != null) - mFile.delete(); - - if (mListener != null) - mListener.onDownloadOver(status, getEMsg()); - } - - public int getStatus() { - return status; - } - - private void initFolder() throws Exception { - mFolder = new File(mPath); - - if (!mFolder.exists()) { - if (!mFolder.mkdirs()) - throw new FileException(FileException.MKDIR_ERROR); - } else if (!mFolder.isDirectory()){ - throw new FileException(FileException.NOT_DIR); - } - - if (!mFolder.canWrite()) - throw new FileException(FileException.CANNOT_WRITE); - } - - private void executeDownload() throws Exception { - while (mRedirectionCount++ < Constants.MAX_REDIRECTS) { - HttpURLConnection conn = null; - try { - Log.d(TAG, "Get file " + mUrl.toString()); - - status = CONNECTING; - if (mListener != null) - mListener.onDownloadStartConnect(); - - conn = (HttpURLConnection)mUrl.openConnection(); - conn.setInstanceFollowRedirects(false); - conn.addRequestProperty("Range", "bytes=" + mDownloadSize + "-"); - conn.setConnectTimeout(Constants.DEFAULT_TIMEOUT); - conn.setReadTimeout(Constants.DEFAULT_TIMEOUT); - conn.connect(); - final int responseCode = conn.getResponseCode(); - switch (responseCode) { - case HttpURLConnection.HTTP_OK: - case HttpURLConnection.HTTP_PARTIAL: - processResponseHeaders(conn); - status = DOWNLOADING; - if (mListener != null) - mListener.onDownloadStartDownload(mTotalSize); - transferData(conn); - return; - - case HttpURLConnection.HTTP_MOVED_PERM: - case HttpURLConnection.HTTP_MOVED_TEMP: - case HttpURLConnection.HTTP_SEE_OTHER: - case Constants.HTTP_TEMP_REDIRECT: - final String location = conn.getHeaderField("Location"); - mUrl = new URL(mUrl, location); - continue; - - default: - //throw new ResponseCodeException(responseCode); - } - } catch (Exception e) { - throw e; - } finally { - if (conn != null) - conn.disconnect(); - } - } - //throw new RedirectionException(); - } - - /** - * Get Response Headers Info - * - * @param conn - */ - private void processResponseHeaders(HttpURLConnection conn) { - mTotalSize = conn.getContentLength(); - - // - String range; - if ((range = conn.getHeaderField("Content-Range")) != null) { // Support Content-Range - boolean newNum = true; - int numIndex = 0; - int num = 0; - int length = range.length(); - char ch; - for (int i = 0; i < length; i++) { - ch = range.charAt(i); - if (ch >= '0' && ch <= '9') { - if (newNum) { - newNum = false; - num = ch - '0'; - } else - num = num * 10 + ch - '0'; - } else { - if (!newNum) { - newNum = true; - if (numIndex == 0) - mDownloadSize = num; - else if (numIndex == 2) - mTotalSize = num; - numIndex++; - } - } - } - if (numIndex == 2) - mTotalSize = num; - } else { // Do not support Content-Range, restart download - mDownloadSize = 0; - } - } - - /** - * Transfer data from the given connection to the destination file. - */ - private void transferData(HttpURLConnection conn) throws Exception { - InputStream in = null; - RandomAccessFile raf = null; - - if (mContorlor.isStop()) - throw new StopRequestException(); - - try { - try { - in = conn.getInputStream(); - } catch (IOException e) { - throw e; // TODO - } - - try { - mFile = new File(mPath, mFileName); - raf = new RandomAccessFile(mFile, "rw"); - raf.seek(mDownloadSize); - } catch (IOException e) { - throw new FileException(FileException.CREATE_FILE_ERROR); - } - - // Start streaming data, periodically watch for pause/cancel - // commands and checking disk space as needed. - transferData(in, raf); - } finally { - if (in != null) - Utils.closeQuietly(in); - if (raf != null) - try { - raf.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - /** - * Transfer as much data as possible from the HTTP response to the - * destination file. - */ - @SuppressWarnings("unused") - private void transferData(InputStream in, OutputStream out) - throws Exception { - final byte data[] = new byte[Constants.BUFFER_SIZE]; - while (true) { - - if (mContorlor.isStop()) - throw new StopRequestException(); - - int bytesRead = readFromResponse(data, in); - if (bytesRead == -1) { // success, end of stream already reached - return; - } - - writeDataToDestination(data, bytesRead, out); - mDownloadSize += bytesRead; - if (mListener != null) - mListener.onDownloadStatusUpdate(mDownloadSize, mTotalSize); - - } - } - - /** - * Transfer as much data as possible from the HTTP response to the - * destination file. - */ - private void transferData(InputStream in, RandomAccessFile raf) - throws Exception { - final byte data[] = new byte[Constants.BUFFER_SIZE]; - while (true) { - if (mContorlor.isStop()) - throw new StopRequestException(); - - int bytesRead = readFromResponse(data, in); - if (bytesRead == -1) { // success, end of stream already reached - return; - } - - writeDataToDestination(data, bytesRead, raf); - mDownloadSize += bytesRead; - if (mListener != null) - mListener.onDownloadStatusUpdate(mDownloadSize, mTotalSize); - } - } - - /** - * Read some data from the HTTP response stream, handling I/O errors. - * @param data buffer to use to read data - * @param entityStream stream for reading the HTTP response entity - * @return the number of bytes actually read or -1 if the end of the stream has been reached - */ - private int readFromResponse(byte[] data, InputStream entityStream) - throws Exception { - try { - return entityStream.read(data); - } catch (IOException e) { - // TODO: handle stream errors the same as other retries - throw e; - } - } - - - /** - * Write a data buffer to the destination file. - * @param data buffer containing the data to write - * @param bytesRead how many bytes to write from the buffer - */ - private void writeDataToDestination(byte[] data, int bytesRead, OutputStream out) - throws Exception { - try { - out.write(data, 0, bytesRead); - return; - } catch (IOException e) { - // TODO: better differentiate between DRM and disk failures - // TODO: check disk is full - throw e; - } - } - - /** - * Write a data buffer to the destination file. - * @param data buffer containing the data to write - * @param bytesRead how many bytes to write from the buffer - */ - private void writeDataToDestination(byte[] data, int bytesRead, RandomAccessFile raf) - throws Exception { - try { - raf.write(data, 0, bytesRead); - return; - } catch (IOException e) { - // TODO: better differentiate between DRM and disk failures - // TODO: check disk is full - throw e; - } - } -} diff --git a/src/com/hippo/ehviewer/network/HttpHelper.java b/src/com/hippo/ehviewer/network/HttpHelper.java index f48c228a6..d07411f8d 100644 --- a/src/com/hippo/ehviewer/network/HttpHelper.java +++ b/src/com/hippo/ehviewer/network/HttpHelper.java @@ -44,6 +44,7 @@ import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Message; +import android.os.Process; import com.hippo.ehviewer.AppHandler; import com.hippo.ehviewer.R; @@ -893,6 +894,19 @@ public class HttpHelper { controlor, listener)); } + public void downloadInThread(final String url, final File dir, + final String file, final boolean isProxy, + final DownloadControlor controlor, final OnDownloadListener listener) { + Thread thread = new Thread() { + @Override + public void run() { + download(url, dir, file, isProxy, controlor, listener); + } + }; + thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND); + thread.start(); + } + /** Exceptions **/ public class SadPandaException extends Exception { diff --git a/src/com/hippo/ehviewer/ui/GalleryListActivity.java b/src/com/hippo/ehviewer/ui/GalleryListActivity.java index 848b9b4e4..e9a818bae 100644 --- a/src/com/hippo/ehviewer/ui/GalleryListActivity.java +++ b/src/com/hippo/ehviewer/ui/GalleryListActivity.java @@ -18,7 +18,6 @@ package com.hippo.ehviewer.ui; import java.io.File; import java.lang.reflect.Field; -import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -76,7 +75,7 @@ import com.hippo.ehviewer.data.GalleryInfo; import com.hippo.ehviewer.data.ListUrls; import com.hippo.ehviewer.data.Tag; import com.hippo.ehviewer.ehclient.EhClient; -import com.hippo.ehviewer.network.Downloader; +import com.hippo.ehviewer.network.HttpHelper; import com.hippo.ehviewer.service.DownloadService; import com.hippo.ehviewer.service.DownloadServiceConnection; import com.hippo.ehviewer.tile.TileSalon; @@ -1430,17 +1429,9 @@ public class GalleryListActivity extends AbstractGalleryActivity @Override public void onClick(View v) { ((AlertButton)v).dialog.dismiss(); - // TODO - try { - Downloader downloader = new Downloader(GalleryListActivity.this); - downloader.resetData(Config.getDownloadPath(), fileName, url); - downloader.setOnDownloadListener( - new UpdateHelper.UpdateListener(GalleryListActivity.this, - fileName)); - new Thread(downloader).start(); - } catch (MalformedURLException e) { - UpdateHelper.setEnabled(true); - } + HttpHelper hh = new HttpHelper(GalleryListActivity.this); + hh.downloadInThread(url, new File(Config.getDownloadPath()), fileName, false, null, + new UpdateHelper.UpdateListener(GalleryListActivity.this, fileName)); } }); if (!GalleryListActivity.this.isFinishing()) diff --git a/src/com/hippo/ehviewer/ui/SettingsActivity.java b/src/com/hippo/ehviewer/ui/SettingsActivity.java index 7d009a2b4..b728247ca 100644 --- a/src/com/hippo/ehviewer/ui/SettingsActivity.java +++ b/src/com/hippo/ehviewer/ui/SettingsActivity.java @@ -19,7 +19,6 @@ package com.hippo.ehviewer.ui; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.MalformedURLException; import java.util.LinkedList; import java.util.List; @@ -54,7 +53,7 @@ import com.hippo.ehviewer.AppContext; import com.hippo.ehviewer.R; import com.hippo.ehviewer.UpdateHelper; import com.hippo.ehviewer.ehclient.EhInfo; -import com.hippo.ehviewer.network.Downloader; +import com.hippo.ehviewer.network.HttpHelper; import com.hippo.ehviewer.preference.AutoListPreference; import com.hippo.ehviewer.util.Config; import com.hippo.ehviewer.util.Favorite; @@ -682,17 +681,9 @@ public class SettingsActivity extends AbstractPreferenceActivity { public void onClick(View v) { ((AlertButton)v).dialog.dismiss(); // TODO - try { - Downloader downloader = new Downloader(mActivity); - downloader.resetData(Config.getDownloadPath(), fileName, url); - downloader.setOnDownloadListener( - new UpdateHelper.UpdateListener(mActivity, - fileName)); - new Thread(downloader).start(); - } catch (MalformedURLException e) { - mCheckUpdate.setSummary(R.string.em_url_format_error); - UpdateHelper.setEnabled(true); - } + HttpHelper hh = new HttpHelper(mActivity); + hh.downloadInThread(url, new File(Config.getDownloadPath()), fileName, false, null, + new UpdateHelper.UpdateListener(mActivity, fileName)); mCheckUpdate.setEnabled(true); } }); diff --git a/src/com/hippo/ehviewer/util/Config.java b/src/com/hippo/ehviewer/util/Config.java index c4b3e394a..b28525274 100644 --- a/src/com/hippo/ehviewer/util/Config.java +++ b/src/com/hippo/ehviewer/util/Config.java @@ -245,8 +245,6 @@ public class Config { switch (value) { case 1: return "qiniu"; - case 2: - return "gokuai"; case 0: default: return "google";