From 86a7939643a5336c46d72bc0be4c10bf024dfeb6 Mon Sep 17 00:00:00 2001 From: gdpancheng Date: Fri, 13 Jun 2014 11:16:21 +0800 Subject: [PATCH] =?UTF-8?q?1=20=E6=B3=A8=E8=A7=A3=E5=86=85=E9=83=A8?= =?UTF-8?q?=E8=B0=83=E6=95=B4=202=20=E5=9B=BE=E7=89=87=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E8=B0=83=E6=95=B4=203=20=E4=B8=8B=E8=BD=BD=E7=A6=BB=E7=BA=BF?= =?UTF-8?q?=E7=BC=93=E5=AD=98=EF=BC=88=E7=AE=80=E5=8D=95=E7=BC=93=E5=AD=98?= =?UTF-8?q?=20=E8=87=AA=E5=B7=B1=E4=BF=AE=E6=94=B9=EF=BC=89=204=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E4=B8=80=E4=B8=AA=E5=AE=9E=E4=BE=8B?= =?UTF-8?q?=E9=A1=B9=E7=9B=AEdemo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lint.xml | 4 + .../android/pc/ioc/a/demo/FifthActivity.java | 16 +- .../android/pc/ioc/a/demo/MainActivity.java | 3 + .../android/pc/ioc/a/demo/MeApplication.java | 2 +- .../android/pc/ioc/a/demo/SecondFragment.java | 9 +- .../android/pc/ioc/a/demo/ThirdFragment.java | 13 +- .../android/pc/ioc/a/demo/ViewManager.java | 2 +- src/com/android/pc/ioc/app/Ioc.java | 1 - src/com/android/pc/ioc/image/ImageCache.java | 4 +- .../android/pc/ioc/image/ImageDownloader.java | 24 +- .../android/pc/ioc/image/ImageResizer.java | 245 -------------- src/com/android/pc/ioc/image/ImageWorker.java | 302 ++++++++++++++++-- src/com/android/pc/ioc/internet/FastHttp.java | 252 ++++++++++----- .../pc/ioc/internet/FastHttpHander.java | 56 ++-- .../android/pc/ioc/internet/HttpCache.java | 45 +++ .../pc/ioc/internet/InternetConfig.java | 89 ++---- .../pc/ioc/internet/ResponseEntity.java | 48 +-- src/com/android/pc/ioc/util/ContextUtils.java | 31 +- .../AnnotationToRuleConverter.java | 15 +- .../ioc/verification/annotation/Password.java | 3 + src/com/android/pc/util/Handler_File.java | 97 ++++++ src/com/android/pc/util/Handler_Time.java | 5 + src/com/android/pc/util/Handler_Ui.java | 106 +++--- src/com/android/pc/util/MD5.java | 28 ++ ...6\344\276\213\351\241\271\347\233\256.zip" | Bin 0 -> 10604162 bytes 25 files changed, 812 insertions(+), 588 deletions(-) create mode 100644 lint.xml delete mode 100644 src/com/android/pc/ioc/image/ImageResizer.java create mode 100644 src/com/android/pc/ioc/internet/HttpCache.java create mode 100644 src/com/android/pc/util/MD5.java create mode 100644 "\345\256\236\344\276\213\351\241\271\347\233\256.zip" diff --git a/lint.xml b/lint.xml new file mode 100644 index 0000000..45d4a46 --- /dev/null +++ b/lint.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/com/android/pc/ioc/a/demo/FifthActivity.java b/src/com/android/pc/ioc/a/demo/FifthActivity.java index 8ada32b..dc5316f 100644 --- a/src/com/android/pc/ioc/a/demo/FifthActivity.java +++ b/src/com/android/pc/ioc/a/demo/FifthActivity.java @@ -1,23 +1,9 @@ package com.android.pc.ioc.a.demo; -import java.util.ArrayList; +import com.wash.activity.R; import android.app.Activity; -import android.content.Context; import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -import com.android.pc.ioc.a.demo.ImageListAdapter.ViewHolder; -import com.android.pc.ioc.inject.InjectBinder; -import com.android.pc.ioc.inject.InjectView; -import com.android.pc.ioc.view.listener.OnClick; -import com.android.pc.util.Handler_Inject; -import com.wash.activity.R; /** diff --git a/src/com/android/pc/ioc/a/demo/MainActivity.java b/src/com/android/pc/ioc/a/demo/MainActivity.java index 9d03711..528e229 100644 --- a/src/com/android/pc/ioc/a/demo/MainActivity.java +++ b/src/com/android/pc/ioc/a/demo/MainActivity.java @@ -40,6 +40,9 @@ public class MainActivity extends BaseActivity { String action_settings; @InjectResource Drawable ic_launcher; + + + // -------------------------------------------------------------------------------------- // 第二种写法(内部类 全局定义点击事件) @InjectAll(@InjectBinder(method = "click", listeners = { OnClick.class })) diff --git a/src/com/android/pc/ioc/a/demo/MeApplication.java b/src/com/android/pc/ioc/a/demo/MeApplication.java index 67c5ae6..a2c6c0b 100644 --- a/src/com/android/pc/ioc/a/demo/MeApplication.java +++ b/src/com/android/pc/ioc/a/demo/MeApplication.java @@ -24,7 +24,7 @@ public void onCreate() { ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(this, "images"); cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory ImageLoadManager.instance().addImageCache(cacheParams); -// ImageLoadManager.instance().setCoding(coding); + ImageLoadManager.instance().setCoding(coding); } /** diff --git a/src/com/android/pc/ioc/a/demo/SecondFragment.java b/src/com/android/pc/ioc/a/demo/SecondFragment.java index 941bc6b..82feb67 100644 --- a/src/com/android/pc/ioc/a/demo/SecondFragment.java +++ b/src/com/android/pc/ioc/a/demo/SecondFragment.java @@ -38,9 +38,6 @@ public class SecondFragment extends BaseFragment { @InjectBefore void test() { - // @InjectView(isasy=true)表示这个listview里面有网络图片下载,并且需要实现滑动停止才加载的功能 - // @InjectView(isasy=true)框架会给listview自动注入OnScrollListener,如果你自己也要滚动监听 - // 那么请在此配置,如下 System.out.println("before"); } @@ -52,14 +49,13 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa Handler_Inject.injectFragment(this, rootView); return rootView; } - + @InjectInit private void init() { // The ImageFetcher takes care of loading images into our ImageView children asynchronously mImageFetcher = new ImageDownloader(getActivity(),300); mImageFetcher.setLoadingImage(R.drawable.ic_launcher); - for (int i = 0; i < 1000; i++) { image.add("http://bcs.duapp.com/question-image/201212310556374291.jpg?b=a" + i); } @@ -83,7 +79,7 @@ public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleI } }); } - + @InjectMethod(@InjectListener(ids = { R.id.next }, listeners = { OnClick.class })) private void click(View v) { EventBus eventBus = EventBus.getDefault(); @@ -97,6 +93,5 @@ private void call(int type) { PullToRefreshManager.getInstance().onFooterRefreshComplete(); //完成 刷新 PullToRefreshManager.getInstance().onHeaderRefreshComplete(); - } } diff --git a/src/com/android/pc/ioc/a/demo/ThirdFragment.java b/src/com/android/pc/ioc/a/demo/ThirdFragment.java index 36a2b8d..0d155cf 100644 --- a/src/com/android/pc/ioc/a/demo/ThirdFragment.java +++ b/src/com/android/pc/ioc/a/demo/ThirdFragment.java @@ -1,6 +1,7 @@ package com.android.pc.ioc.a.demo; -import android.app.ProgressDialog; +import java.util.LinkedHashMap; + import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; @@ -53,11 +54,16 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa */ @InjectInit private void init() { - FastHttpHander.ajaxGet("http://211.152.52.1119:8080/app/api.php?act=category", this); + + FastHttpHander.ajaxGet("http://211.152.52.119:8080/app/api.php?act=category", this); InternetConfig config = new InternetConfig(); + //是否保存数据 默认不保存 当没网络的时候 获取数据的时候 然后就会从之前存储的离线拿出数据 + config.setSave(true); config.setKey(1); - FastHttpHander.ajaxGet("http://211.152.52.119:8080/app/api.php?act=category", config, this); + LinkedHashMap paHashMap = new LinkedHashMap(); + paHashMap.put("test", "haha"); + FastHttpHander.ajaxGet("http://211.152.52.119:8080/app/api.php?act=category",paHashMap, config, this); InternetConfig config2 = new InternetConfig(); config2.setKey(2); @@ -87,6 +93,7 @@ private void result(ResponseEntity r) { @InjectHttpOk(1) private void resultOk(ResponseEntity r) { + System.out.println(r); v.result.append("我是resultOk 当前key为:" + r.getKey() + "回调了\n"); v.result.setVisibility(View.VISIBLE); v.progress.setVisibility(View.GONE); diff --git a/src/com/android/pc/ioc/a/demo/ViewManager.java b/src/com/android/pc/ioc/a/demo/ViewManager.java index c0cc267..b58f2b0 100644 --- a/src/com/android/pc/ioc/a/demo/ViewManager.java +++ b/src/com/android/pc/ioc/a/demo/ViewManager.java @@ -31,6 +31,6 @@ public View getView() { } private void click(){ - Toast.makeText(MeApplication.app, "这个注解 不是在acitivity中哦", Toast.LENGTH_SHORT).show(); + Toast.makeText(MeApplication.app, "这个注解 不是在acitivity中", Toast.LENGTH_SHORT).show(); } } diff --git a/src/com/android/pc/ioc/app/Ioc.java b/src/com/android/pc/ioc/app/Ioc.java index c3661a8..78c571e 100644 --- a/src/com/android/pc/ioc/app/Ioc.java +++ b/src/com/android/pc/ioc/app/Ioc.java @@ -9,7 +9,6 @@ import android.app.Activity; import android.app.Application; -import android.util.Log; import android.view.View; import com.android.pc.ioc.core.kernel.KernelObject; diff --git a/src/com/android/pc/ioc/image/ImageCache.java b/src/com/android/pc/ioc/image/ImageCache.java index b0fde7c..572da4d 100644 --- a/src/com/android/pc/ioc/image/ImageCache.java +++ b/src/com/android/pc/ioc/image/ImageCache.java @@ -231,7 +231,7 @@ public BitmapDrawable getBitmapFromMemCache(String data) { * Unique identifier for which item to get * @return The bitmap if found in cache, null otherwise */ - public Bitmap getBitmapFromDiskCache(String data, int w, int h) { + public Bitmap getBitmapFromDiskCache(String data, int w, int h,ImageWorker imWorker) { final String key = hashKeyForDisk(data); synchronized (mDiskCacheLock) { @@ -244,7 +244,7 @@ public Bitmap getBitmapFromDiskCache(String data, int w, int h) { File file = getFromFileCache(key); Bitmap bitmap = null; if (file != null && file.exists()) { - bitmap = ImageResizer.decodeSampledBitmapFromFile(file.getPath(), w, h, this); + bitmap = imWorker.decodeSampledBitmapFromFile(data,file.getPath(), w, h, this); } return bitmap; } diff --git a/src/com/android/pc/ioc/image/ImageDownloader.java b/src/com/android/pc/ioc/image/ImageDownloader.java index 3dfa22a..50257a0 100644 --- a/src/com/android/pc/ioc/image/ImageDownloader.java +++ b/src/com/android/pc/ioc/image/ImageDownloader.java @@ -10,19 +10,17 @@ import android.content.Context; import android.graphics.Bitmap; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; import android.os.Build; import android.widget.ImageView; -import android.widget.Toast; import com.android.pc.ioc.app.Ioc; +import com.android.pc.util.Handler_Network; import com.android.pc.util.Handler_System; /** * 图片下载类 可以设置图片高度宽度 */ -public class ImageDownloader extends ImageResizer { +public class ImageDownloader extends ImageWorker { /** * 限定高度宽度的 @@ -70,12 +68,9 @@ private void init(Context context) { * @param context */ private void checkConnection(Context context) { - final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); - if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) { - Toast.makeText(context, "无法连接到网络", Toast.LENGTH_LONG).show(); + if (!Handler_Network.isNetworkAvailable(context)) { Ioc.getIoc().getLogger().e("网络连接失败"); - } + } } /** @@ -93,7 +88,7 @@ private Bitmap processBitmap(String data,ImageView imageView) { if (data.startsWith("http")) { final String key = ImageCache.hashKeyForDisk(data); file = ImageCache.getFromFileCache(key); - start(imageView); + start(imageView,lister); downloadUrlToStream(data, file,imageView); }else { file = new File(data); @@ -101,12 +96,7 @@ private Bitmap processBitmap(String data,ImageView imageView) { Bitmap bitmap = null; if (file != null && file.exists()) { - bitmap = decodeSampledBitmapFromFile(file.getPath(), mImageWidth, mImageHeight, getImageCache()); - } - if (bitmap==null) { - fail(imageView); - }else { - finish(bitmap, imageView); + bitmap = decodeSampledBitmapFromFile(data,file.getPath(), mImageWidth, mImageHeight, getImageCache()); } return bitmap; } @@ -155,7 +145,7 @@ public boolean downloadUrlToStream(String urlString, File file,ImageView imageVi n = n + count; if (length>0) { int percent = (int) (n * 100 / length); - process(percent,imageView); + process(percent,imageView,lister); } } return true; diff --git a/src/com/android/pc/ioc/image/ImageResizer.java b/src/com/android/pc/ioc/image/ImageResizer.java deleted file mode 100644 index facc466..0000000 --- a/src/com/android/pc/ioc/image/ImageResizer.java +++ /dev/null @@ -1,245 +0,0 @@ -package com.android.pc.ioc.image; - -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.HashMap; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.os.Build; -import android.widget.ImageView; - -import com.android.pc.ioc.app.Ioc; -import com.android.pc.ioc.image.ImageLoadManager.Coding; -import com.android.pc.util.Handler_System; - -/** - * 其中实现了一系列图片加载的方法

第一条

实现了设置高宽的方法

第二条

实现了从本地文件或者从draw文件夹加载图片的犯法 - */ -public class ImageResizer extends ImageWorker { - protected int mImageWidth; - protected int mImageHeight; - - /** - * 初始化的时候 需要设置大小 - * - * @param context - * @param imageWidth - * @param imageHeight - */ - public ImageResizer(Context context, int imageWidth, int imageHeight) { - super(context); - setImageSize(imageWidth, imageHeight); - } - - /** - * 初始化的时候 需要设置大小 - * - * @param context - * @param imageSize - */ - public ImageResizer(Context context, int imageSize) { - super(context); - setImageSize(imageSize); - } - - /** - * Set the target image width and height. - * - * @param width - * @param height - */ - public void setImageSize(int width, int height) { - HashMap data = Handler_System.getDisplayMetrics(); - if (width == 0) { - width = data.get(Handler_System.systemWidth); - } - if (height == 0) { - height = data.get(Handler_System.systemHeight); - } - mImageWidth = width; - mImageHeight = height; - } - - /** - * 设置图片的高宽 高宽一样 - * - * @param size - */ - public void setImageSize(int size) { - setImageSize(size, size); - } - - /** - * 图片解析的主方法
- * 参数为资源ID - * - * @param resId - * @return - */ - private Bitmap processBitmap(int resId) { - Ioc.getIoc().getLogger().d("图片下载开始 - " + resId); - return decodeSampledBitmapFromResource(mResources, resId, mImageWidth, mImageHeight, getImageCache()); - } - - @Override - protected Bitmap processBitmap(Object data, ImageView imageView) { - return processBitmap(Integer.parseInt(String.valueOf(data))); - } - - /** - * 从资源文件加载图片 - * - * @author gdpancheng@gmail.com 2014-5-19 下午2:14:13 - * @param res - * @param resId - * @param reqWidth - * @param reqHeight - * @param cache - * @return Bitmap - */ - public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight, ImageCache cache) { - - final BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeResource(res, resId, options); - - options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); - - if (Utils.hasHoneycomb()) { - addInBitmapOptions(options, cache); - } - - options.inJustDecodeBounds = false; - return BitmapFactory.decodeResource(res, resId, options); - } - - /** - * 从本地文件加载图片 - * - * @author gdpancheng@gmail.com 2014-5-19 下午2:15:23 - * @param filename - * @param reqWidth - * @param reqHeight - * @param cache - * @return Bitmap - */ - public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight, ImageCache cache) { - - final BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - - Coding coding = ImageLoadManager.instance().getCoding(); - if (coding == null) { - BitmapFactory.decodeFile(filename, options); - }else { - try { - InputStream in = new FileInputStream(filename); - byte[] buffer = coding.decodeJPG(in.available(), in); - in.close(); - BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options); - buffer = null; - } catch (Exception e) { - e.printStackTrace(); - } - } - - options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); - - if (Utils.hasHoneycomb()) { - addInBitmapOptions(options, cache); - } - - options.inJustDecodeBounds = false; - - if (coding == null) { - return BitmapFactory.decodeFile(filename, options); - } - try { - InputStream in = new FileInputStream(filename); - byte[] buffer = coding.decodeJPG(in.available(), in); - in.close(); - return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { - final BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); - - options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); - options.inJustDecodeBounds = false; - - if (Utils.hasHoneycomb()) { - addInBitmapOptions(options, cache); - } - - return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { - options.inMutable = true; - - if (cache != null) { - Bitmap inBitmap = cache.getBitmapFromReusableSet(options); - - if (inBitmap != null) { - options.inBitmap = inBitmap; - } - } - } - - /** - * 根据需要的高宽,对图片进行缩放 TODO(这里用一句话描述这个方法的作用) - * - * @author gdpancheng@gmail.com 2014-5-19 下午2:19:56 - * @param options - * @param reqWidth - * @param reqHeight - * @return int - */ - public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { - final int height = options.outHeight; - final int width = options.outWidth; - int inSampleSize = 1; - - if (height > reqHeight || width > reqWidth) { - - final int halfHeight = height / 2; - final int halfWidth = width / 2; - - while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { - inSampleSize *= 2; - } - - long totalPixels = width * height / inSampleSize; - - final long totalReqPixelsCap = reqWidth * reqHeight * 2; - - while (totalPixels > totalReqPixelsCap) { - inSampleSize *= 2; - totalPixels /= 2; - } - } - return inSampleSize; - } - - @Override - protected int getW() { - return mImageWidth; - } - - @Override - protected int getH() { - return mImageHeight; - } -} diff --git a/src/com/android/pc/ioc/image/ImageWorker.java b/src/com/android/pc/ioc/image/ImageWorker.java index ab4f991..62d2d86 100644 --- a/src/com/android/pc/ioc/image/ImageWorker.java +++ b/src/com/android/pc/ioc/image/ImageWorker.java @@ -1,7 +1,12 @@ package com.android.pc.ioc.image; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.InputStream; import java.lang.ref.WeakReference; +import java.util.HashMap; +import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; @@ -10,16 +15,19 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; +import android.os.Build; import android.os.Handler; import android.os.Message; import android.widget.ImageView; import com.android.pc.ioc.app.Ioc; +import com.android.pc.ioc.image.ImageLoadManager.Coding; +import com.android.pc.util.Handler_System; /** * 图片下载工具类 */ -public abstract class ImageWorker { +public class ImageWorker { private static final int FADE_IN_TIME = 200; private static final int start = 0; @@ -33,13 +41,47 @@ public abstract class ImageWorker { private boolean mExitTasksEarly = false; protected boolean mPauseWork = false; private final Object mPauseWorkLock = new Object(); - protected Resources mResources; protected DisplayerLister lister; + private boolean isDecode = false; protected ImageWorker(Context context) { mResources = context.getResources(); } + + protected int mImageWidth; + protected int mImageHeight; + + /** + * 初始化的时候 需要设置大小 + * + * @param context + * @param imageWidth + * @param imageHeight + */ + public ImageWorker(Context context, int imageWidth, int imageHeight) { + setImageSize(imageWidth, imageHeight); + mResources = context.getResources(); + } + + /** + * 初始化的时候 需要设置大小 + * + * @param context + * @param imageSize + */ + public ImageWorker(Context context, int imageSize) { + setImageSize(imageSize); + mResources = context.getResources(); + } + + public void useDecode(boolean isDecode){ + this.isDecode = isDecode; + } + + public boolean isDecode(){ + return isDecode; + } /** * 加载网络图片到ImageView上(当然也可以重写{@link ImageWorker#processBitmap(Object)}来实现图片获取过程)
@@ -69,10 +111,12 @@ public void loadImage(Object data, ImageView imageView) { // 如果图片为空 if (value != null) { // 如果图片不为空 则直接设置 - finish(value.getBitmap(), imageView); + if (value.getBitmap()!=null) { + finish(value.getBitmap(), imageView, lister); + } imageView.setImageDrawable(value); } else if (cancelPotentialWork(data, imageView)) { - final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView); + final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView, lister); final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task); imageView.setImageDrawable(asyncDrawable); // 通过线程池执行下载进程 @@ -115,18 +159,6 @@ public void setExitTasksEarly(boolean exitTasksEarly) { setPauseWork(false); } - /** - * - * 自定义图片下载类 继承此类以后,需要实现这个方法
- * 它的目的是生成最终位图
- * 它本身运行在后台,且是异步的
- * 你可以在此加载本地的大图,或者从网络下载图片 - * - * @param data - * 图片来源 由 {@link ImageWorker#loadImage(Object, android.widget.ImageView)}提供 - * @return 返回处理好的图片 - */ - protected abstract Bitmap processBitmap(Object data, ImageView imageView); private class Entity { public int process; @@ -135,7 +167,7 @@ private class Entity { public DisplayerLister lister; } - protected void process(int process, ImageView imageView) { + protected void process(int process, ImageView imageView, DisplayerLister lister) { if (lister == null) { return; } @@ -145,11 +177,11 @@ protected void process(int process, ImageView imageView) { entity.imageView = imageView; entity.lister = lister; msg.obj = entity; - msg.what = this.process; - handler.sendMessage(msg); + msg.what = process; + msg.sendToTarget(); }; - protected void finish(Bitmap bitmap, ImageView imageView) { + protected void finish(Bitmap bitmap, ImageView imageView, DisplayerLister lister) { if (lister == null) { return; } @@ -160,10 +192,10 @@ protected void finish(Bitmap bitmap, ImageView imageView) { entity.lister = lister; msg.obj = entity; msg.what = finish; - handler.sendMessage(msg); + msg.sendToTarget(); }; - protected void fail(ImageView imageView) { + protected void fail(ImageView imageView, DisplayerLister lister) { if (lister == null) { return; } @@ -173,10 +205,10 @@ protected void fail(ImageView imageView) { entity.lister = lister; msg.obj = entity; msg.what = fail; - handler.sendMessage(msg); + msg.sendToTarget(); }; - protected void start(ImageView imageView) { + protected void start(ImageView imageView, DisplayerLister lister) { if (lister == null) { return; } @@ -186,10 +218,10 @@ protected void start(ImageView imageView) { entity.lister = lister; msg.obj = entity; msg.what = start; - handler.sendMessage(msg); + msg.sendToTarget(); }; - static Handler handler = new Handler() { + Handler handler = new Handler() { public void handleMessage(Message msg) { Entity entity = (Entity) msg.obj; switch (msg.what) { @@ -278,10 +310,12 @@ private class BitmapWorkerTask extends AsyncTask { private Object mData; // 弱引用 存储了视图 private final WeakReference imageViewReference; + protected final DisplayerLister lister; - public BitmapWorkerTask(Object data, ImageView imageView) { + public BitmapWorkerTask(Object data, ImageView imageView, DisplayerLister lister) { mData = data; imageViewReference = new WeakReference(imageView); + this.lister = lister; } /** @@ -307,11 +341,8 @@ protected BitmapDrawable doInBackground(Void... params) { // 如果缓存不为空 没有被取消 当前显示的imageview不为空 则去从本地缓存中获取 if (mImageCache != null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { - bitmap = mImageCache.getBitmapFromDiskCache(dataString, getW(), getH()); + bitmap = mImageCache.getBitmapFromDiskCache(dataString, getW(), getH(),ImageWorker.this); } - if (bitmap != null) { - finish(bitmap, imageViewReference.get()); - } // 下载图片 通过自定义下载模块 if (bitmap == null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { bitmap = processBitmap(mData, imageViewReference.get()); @@ -350,9 +381,15 @@ protected void onPostExecute(BitmapDrawable value) { final ImageView imageView = getAttachedImageView(); if (value != null && imageView != null) { + if (value.getBitmap()!=null) { + finish(value.getBitmap(), imageView, lister); + } Ioc.getIoc().getLogger().d("onPostExecute - setting bitmap"); setImageDrawable(imageView, value); } + if (value == null) { + fail(imageView, lister); + } } @Override @@ -430,7 +467,206 @@ public void setPauseWork(boolean pauseWork) { } } - protected abstract int getW(); + /** + * Set the target image width and height. + * + * @param width + * @param height + */ + public void setImageSize(int width, int height) { + HashMap data = Handler_System.getDisplayMetrics(); + if (width == 0) { + width = data.get(Handler_System.systemWidth); + } + if (height == 0) { + height = data.get(Handler_System.systemHeight); + } + mImageWidth = width; + mImageHeight = height; + } + + /** + * 设置图片的高宽 高宽一样 + * + * @param size + */ + public void setImageSize(int size) { + setImageSize(size, size); + } + + /** + * 图片解析的主方法
+ * 参数为资源ID + * + * @param resId + * @return + */ + private Bitmap processBitmap(int resId) { + Ioc.getIoc().getLogger().d("图片下载开始 - " + resId); + return decodeSampledBitmapFromResource(mResources, resId, mImageWidth, mImageHeight, getImageCache()); + } + + protected Bitmap processBitmap(Object data, ImageView imageView) { + return processBitmap(Integer.parseInt(String.valueOf(data))); + } + + /** + * 从资源文件加载图片 + * + * @author gdpancheng@gmail.com 2014-5-19 下午2:14:13 + * @param res + * @param resId + * @param reqWidth + * @param reqHeight + * @param cache + * @return Bitmap + */ + public Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight, ImageCache cache) { + + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeResource(res, resId, options); + + options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); + + if (Utils.hasHoneycomb()) { + addInBitmapOptions(options, cache); + } + + options.inJustDecodeBounds = false; + return BitmapFactory.decodeResource(res, resId, options); + } + + /** + * 从本地文件加载图片 + * + * @author gdpancheng@gmail.com 2014-5-19 下午2:15:23 + * @param filename + * @param reqWidth + * @param reqHeight + * @param cache + * @return Bitmap + */ + public Bitmap decodeSampledBitmapFromFile(String url,String filename, int reqWidth, int reqHeight, ImageCache cache) { + + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + Coding coding = ImageLoadManager.instance().getCoding(); + if (coding == null||isDecode == false) { + BitmapFactory.decodeFile(filename, options); + }else if (isDecode&&coding!=null) { + try { + InputStream in = new FileInputStream(filename); + byte[] buffer; + if (url.toLowerCase().indexOf(".jpg")!=-1) { + buffer= coding.decodeJPG(in.available(), in); + }else { + buffer= coding.decodePNG(in.available(), in); + } + in.close(); + BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options); + buffer = null; + } catch (Exception e) { + e.printStackTrace(); + } + } + + options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); + + if (Utils.hasHoneycomb()) { + addInBitmapOptions(options, cache); + } + + options.inJustDecodeBounds = false; + + if (coding == null||isDecode == false) { + return BitmapFactory.decodeFile(filename, options); + }else if(isDecode && coding!=null) { + try { + InputStream in = new FileInputStream(filename); + byte[] buffer; + if (url.toLowerCase().indexOf(".jpg")!=-1) { + buffer= coding.decodeJPG(in.available(), in); + }else { + buffer= coding.decodePNG(in.available(), in); + } + in.close(); + return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options); + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + + public Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); + + options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); + options.inJustDecodeBounds = false; - protected abstract int getH(); + if (Utils.hasHoneycomb()) { + addInBitmapOptions(options, cache); + } + + return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + private void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { + options.inMutable = true; + + if (cache != null) { + Bitmap inBitmap = cache.getBitmapFromReusableSet(options); + + if (inBitmap != null) { + options.inBitmap = inBitmap; + } + } + } + + /** + * 根据需要的高宽,对图片进行缩放 TODO(这里用一句话描述这个方法的作用) + * + * @author gdpancheng@gmail.com 2014-5-19 下午2:19:56 + * @param options + * @param reqWidth + * @param reqHeight + * @return int + */ + public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { + final int height = options.outHeight; + final int width = options.outWidth; + int inSampleSize = 1; + + if (height > reqHeight || width > reqWidth) { + + final int halfHeight = height / 2; + final int halfWidth = width / 2; + + while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { + inSampleSize *= 2; + } + + long totalPixels = width * height / inSampleSize; + + final long totalReqPixelsCap = reqWidth * reqHeight * 2; + + while (totalPixels > totalReqPixelsCap) { + inSampleSize *= 2; + totalPixels /= 2; + } + } + return inSampleSize; + } + + protected int getW() { + return mImageWidth; + } + + protected int getH() { + return mImageHeight; + } } diff --git a/src/com/android/pc/ioc/internet/FastHttp.java b/src/com/android/pc/ioc/internet/FastHttp.java index 512d185..e064def 100644 --- a/src/com/android/pc/ioc/internet/FastHttp.java +++ b/src/com/android/pc/ioc/internet/FastHttp.java @@ -15,6 +15,7 @@ import java.net.ProtocolException; import java.net.URL; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -31,6 +32,7 @@ import android.util.Xml; import com.android.pc.ioc.app.Ioc; +import com.android.pc.util.Handler_Network; /** * ----------------------同步----------------------
@@ -111,7 +113,7 @@ public static ResponseEntity get(String url, InternetConfig config) { * 请求的参数 * @return ResponseEntity 返回的数据 */ - public static ResponseEntity get(String url, HashMap params) { + public static ResponseEntity get(String url, LinkedHashMap params) { return get(url, params, InternetConfig.defaultConfig()); } @@ -127,10 +129,14 @@ public static ResponseEntity get(String url, HashMap params) { * 配置 * @return ResponseEntity 返回结果 */ - public static ResponseEntity get(String url, HashMap params, InternetConfig config) { + public static ResponseEntity get(String url, LinkedHashMap params, InternetConfig config) { config.setRequest_type(InternetConfig.request_get); if (params != null) { - url = url + "?"; + if (url.indexOf("\\?")!=-1) { + url = url + "?"; + }else { + url = url + "&"; + } for (Map.Entry entry : params.entrySet()) { url = url + entry.getKey() + "=" + entry.getValue() + "&"; } @@ -138,19 +144,34 @@ public static ResponseEntity get(String url, HashMap params, Int } ResponseEntity responseEntity = new ResponseEntity(); responseEntity.setUrl(url); + responseEntity.setParams(params); responseEntity.setKey(config.getKey()); + + // 判断是否需要离线 + if (config.isSave()) { + if (!Handler_Network.isNetworkAvailable(Ioc.getIoc().getApplication())) { + Ioc.getIoc().getLogger().e("无法连接到网络 将获取离线数据"); + String result = HttpCache.getUrlCache(url, params); + if (result != null) { + responseEntity.setContent(result, false); + responseEntity.setStatus(result_ok); + return responseEntity; + } + } + } + try { HttpURLConnection conn = getDefaultHttpClient(url, config); InputStream inStream = conn.getInputStream(); getCookies(config, responseEntity, conn); - responseEntity.setContent(inputStreamToString(inStream, config.getCharset())); + responseEntity.setContent(inputStreamToString(inStream, config.getCharset()), config.isSave()); conn.disconnect(); responseEntity.setStatus(result_ok); if (responseEntity.getContentAsString().length() == 0) { responseEntity.setStatus(result_net_err); } return responseEntity; - }catch (Exception e) { + } catch (Exception e) { responseEntity.setStatus(result_net_err); e.printStackTrace(); } @@ -179,7 +200,7 @@ public static ResponseEntity post(String url) { * 请求的参数 * @return ResponseEntity 返回的数据 */ - public static ResponseEntity post(String url, HashMap params) { + public static ResponseEntity post(String url, LinkedHashMap params) { return post(url, params, InternetConfig.defaultConfig()); } @@ -195,12 +216,26 @@ public static ResponseEntity post(String url, HashMap params) { * 下载配置 * @return ResponseEntity 返回值 */ - public static ResponseEntity post(String url, HashMap params, InternetConfig config) { + public static ResponseEntity post(String url, LinkedHashMap params, InternetConfig config) { config.setRequest_type(InternetConfig.request_post); ResponseEntity responseEntity = new ResponseEntity(); responseEntity.setUrl(url); responseEntity.setParams(params); responseEntity.setKey(config.getKey()); + + // 判断是否需要离线 + if (config.isSave()) { + if (!Handler_Network.isNetworkAvailable(Ioc.getIoc().getApplication())) { + Ioc.getIoc().getLogger().e("无法连接到网络 将获取离线数据"); + String result = HttpCache.getUrlCache(url, params); + if (result != null) { + responseEntity.setContent(result, false); + responseEntity.setStatus(result_ok); + return responseEntity; + } + } + } + try { HttpURLConnection conn = getDefaultHttpClient(url, config); conn.setDoOutput(true); @@ -221,7 +256,7 @@ public static ResponseEntity post(String url, HashMap params, In getCookies(config, responseEntity, conn); - responseEntity.setContent(inputStreamToString(inStream, config.getCharset())); + responseEntity.setContent(inputStreamToString(inStream, config.getCharset()), config.isSave()); conn.disconnect(); responseEntity.setStatus(result_ok); if (responseEntity.getContentAsString().length() == 0) { @@ -261,7 +296,7 @@ public static ResponseEntity postString(String url, String params, InternetConfi } } } - responseEntity.setContent(inputStreamToString(inStream, config.getCharset())); + responseEntity.setContent(inputStreamToString(inStream, config.getCharset()), config.isSave()); conn.disconnect(); responseEntity.setStatus(result_ok); if (responseEntity.getContentAsString().length() == 0) { @@ -297,7 +332,7 @@ public static ResponseEntity form(String url) { * 请求的参数 * @return ResponseEntity 返回的数据 */ - public static ResponseEntity form(String url, HashMap params) { + public static ResponseEntity form(String url, LinkedHashMap params) { return form(url, params, null, InternetConfig.defaultConfig()); } @@ -314,7 +349,7 @@ public static ResponseEntity form(String url, HashMap params) { * @return * @return ResponseEntity */ - public static ResponseEntity form(String url, HashMap params, HashMap files) { + public static ResponseEntity form(String url, LinkedHashMap params, HashMap files) { return form(url, params, files, InternetConfig.defaultConfig()); } @@ -332,13 +367,27 @@ public static ResponseEntity form(String url, HashMap params, Ha * @return * @return ResponseEntity */ - public static ResponseEntity form(String url, HashMap params, HashMap files, InternetConfig config) { - params = params == null ? new HashMap() : params; + public static ResponseEntity form(String url, LinkedHashMap params, HashMap files, InternetConfig config) { + params = params == null ? new LinkedHashMap() : params; config.setRequest_type(InternetConfig.request_form); ResponseEntity responseEntity = new ResponseEntity(); responseEntity.setUrl(url); responseEntity.setParams(params); + responseEntity.setKey(config.getKey()); + + // 判断是否需要离线 + if (config.isSave()) { + if (!Handler_Network.isNetworkAvailable(Ioc.getIoc().getApplication())) { + Ioc.getIoc().getLogger().e("无法连接到网络 将获取离线数据"); + String result = HttpCache.getUrlCache(url, params); + if (result != null) { + responseEntity.setContent(result, false); + responseEntity.setStatus(result_ok); + return responseEntity; + } + } + } try { HttpURLConnection conn = getDefaultHttpClient(url, config); @@ -370,9 +419,9 @@ public static ResponseEntity form(String url, HashMap params, Ha for (Map.Entry file : files.entrySet()) { if (!file.getValue().exists()) { - continue; - } - + continue; + } + StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); @@ -404,7 +453,7 @@ public static ResponseEntity form(String url, HashMap params, Ha // if (res == 200) { in = conn.getInputStream(); getCookies(config, responseEntity, conn); - responseEntity.setContent(inputStreamToString(in, config.getCharset())); + responseEntity.setContent(inputStreamToString(in, config.getCharset()), config.isSave()); responseEntity.setKey(config.getKey()); outStream.close(); conn.disconnect(); @@ -414,7 +463,7 @@ public static ResponseEntity form(String url, HashMap params, Ha } } else { InputStream inStream = conn.getInputStream(); - responseEntity.setContent(inputStreamToString(inStream, config.getCharset())); + responseEntity.setContent(inputStreamToString(inStream, config.getCharset()), config.isSave()); conn.disconnect(); responseEntity.setStatus(result_ok); if (responseEntity.getContentAsString().length() == 0) { @@ -432,26 +481,39 @@ public interface Progress { public void progress(int progress); } - public static ResponseEntity formProgress(String url, HashMap params, HashMap files, InternetConfig config, Progress progress) { - params = params == null ? new HashMap() : params; + public static ResponseEntity formProgress(String url, LinkedHashMap params, HashMap files, InternetConfig config, Progress progress) { + params = params == null ? new LinkedHashMap() : params; config.setRequest_type(InternetConfig.request_form); ResponseEntity responseEntity = new ResponseEntity(); responseEntity.setUrl(url); responseEntity.setParams(params); + responseEntity.setKey(config.getKey()); + + // 判断是否需要离线 + if (config.isSave()) { + if (!Handler_Network.isNetworkAvailable(Ioc.getIoc().getApplication())) { + Ioc.getIoc().getLogger().e("无法连接到网络 将获取离线数据"); + String result = HttpCache.getUrlCache(url, params); + if (result != null) { + responseEntity.setContent(result, false); + responseEntity.setStatus(result_ok); + return responseEntity; + } + } + } try { - long all_count =getOrtherLength(params,files,config); + long all_count = getOrtherLength(params, files, config); long read_count = 0; - + config.setAll_length(all_count); HttpURLConnection conn = getDefaultHttpClient(url, config); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 不允许使用缓存 - StringBuilder sb = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { sb.append(PREFIX); @@ -464,13 +526,13 @@ public static ResponseEntity formProgress(String url, HashMap pa sb.append(entry.getValue()); sb.append(LINEND); } - + BufferedOutputStream outStream = new BufferedOutputStream(conn.getOutputStream()); if (sb.length() > 0) { outStream.write(sb.toString().getBytes()); - + if (progress != null) { - read_count = read_count+ sb.toString().getBytes().length; + read_count = read_count + sb.toString().getBytes().length; progress.progress((int) (read_count * 100 / all_count)); } } @@ -480,6 +542,10 @@ public static ResponseEntity formProgress(String url, HashMap pa if (files != null) { for (Map.Entry file : files.entrySet()) { + if (!file.getValue().exists()) { + continue; + } + StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); @@ -490,10 +556,10 @@ public static ResponseEntity formProgress(String url, HashMap pa outStream.write(sb1.toString().getBytes()); if (progress != null) { - read_count = read_count+ sb1.toString().getBytes().length; + read_count = read_count + sb1.toString().getBytes().length; progress.progress((int) (read_count * 100 / all_count)); } - + InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; @@ -508,7 +574,7 @@ public static ResponseEntity formProgress(String url, HashMap pa is.close(); outStream.write(LINEND.getBytes()); if (progress != null) { - read_count = read_count+ LINEND.getBytes().length; + read_count = read_count + LINEND.getBytes().length; progress.progress((int) (read_count * 100 / all_count)); } } @@ -518,7 +584,7 @@ public static ResponseEntity formProgress(String url, HashMap pa outStream.write(end_data); outStream.flush(); if (progress != null) { - read_count = read_count+ end_data.length; + read_count = read_count + end_data.length; progress.progress((int) (read_count * 100 / all_count)); } // 得到响应码 @@ -526,7 +592,7 @@ public static ResponseEntity formProgress(String url, HashMap pa // if (res == 200) { in = conn.getInputStream(); getCookies(config, responseEntity, conn); - responseEntity.setContent(inputStreamToString(in, config.getCharset())); + responseEntity.setContent(inputStreamToString(in, config.getCharset()), config.isSave()); responseEntity.setKey(config.getKey()); outStream.close(); conn.disconnect(); @@ -536,14 +602,14 @@ public static ResponseEntity formProgress(String url, HashMap pa } } else { InputStream inStream = conn.getInputStream(); - responseEntity.setContent(inputStreamToString(inStream, config.getCharset())); + responseEntity.setContent(inputStreamToString(inStream, config.getCharset()), config.isSave()); conn.disconnect(); responseEntity.setStatus(result_ok); if (responseEntity.getContentAsString().length() == 0) { responseEntity.setStatus(result_net_err); } } - }catch (Exception e) { + } catch (Exception e) { responseEntity.setStatus(result_net_err); e.printStackTrace(); } @@ -584,7 +650,7 @@ public static void ajaxForm(String url, InternetConfig config, AjaxCallBack call * @param callBack * @return void */ - public static void ajaxForm(String url, HashMap params, AjaxCallBack callBack) { + public static void ajaxForm(String url, LinkedHashMap params, AjaxCallBack callBack) { ajaxForm(url, params, null, InternetConfig.defaultConfig(), callBack); } @@ -598,7 +664,7 @@ public static void ajaxForm(String url, HashMap params, AjaxCall * @param callBack * @return void */ - public static void ajaxForm(String url, HashMap params, HashMap files, AjaxCallBack callBack) { + public static void ajaxForm(String url, LinkedHashMap params, HashMap files, AjaxCallBack callBack) { ajaxForm(url, params, files, InternetConfig.defaultConfig(), callBack); } @@ -613,7 +679,7 @@ public static void ajaxForm(String url, HashMap params, HashMap< * @param callBack * @return void */ - public static void ajaxForm(String url, HashMap params, HashMap files, InternetConfig config, AjaxCallBack callBack) { + public static void ajaxForm(String url, LinkedHashMap params, HashMap files, InternetConfig config, AjaxCallBack callBack) { config.setRequest_type(InternetConfig.request_form); config.setFiles(files); new Thread(new AjaxTask(url, params, config, callBack)).start(); @@ -661,7 +727,7 @@ public static void ajax(String url, InternetConfig config, AjaxCallBack callBack * 回调函数 * @return void */ - public static void ajax(String url, HashMap params, AjaxCallBack callBack) { + public static void ajax(String url, LinkedHashMap params, AjaxCallBack callBack) { ajax(url, params, InternetConfig.defaultConfig(), callBack); } @@ -679,7 +745,7 @@ public static void ajax(String url, HashMap params, AjaxCallBack * 回调函数 * @return void */ - public static void ajax(String url, HashMap params, InternetConfig config, AjaxCallBack callBack) { + public static void ajax(String url, LinkedHashMap params, InternetConfig config, AjaxCallBack callBack) { config.setRequest_type(InternetConfig.request_post); new Thread(new AjaxTask(url, params, config, callBack)).start(); } @@ -707,7 +773,7 @@ public static void ajax(String url, AjaxTimeCallBack callBack) { * @param callBack * @return void */ - public static void ajax(String url, HashMap params, AjaxTimeCallBack callBack) { + public static void ajax(String url, LinkedHashMap params, AjaxTimeCallBack callBack) { InternetConfig config = InternetConfig.defaultConfig(); config.setRequest_type(InternetConfig.request_post); ajax(url, params, config, callBack); @@ -727,7 +793,7 @@ public static void ajax(String url, HashMap params, AjaxTimeCall * 回调函数 * @return void */ - public static void ajax(String url, HashMap params, InternetConfig config, AjaxTimeCallBack callBack) { + public static void ajax(String url, LinkedHashMap params, InternetConfig config, AjaxTimeCallBack callBack) { config.setRequest_type(InternetConfig.request_post); new Thread(new TimeTask(url, params, config, callBack)).start(); } @@ -771,7 +837,7 @@ public static ResponseEntity webServer(String url, InternetConfig config, String * 请求的参数 * @return T 返回的数据 */ - public static ResponseEntity webServer(String url, HashMap params, String method) { + public static ResponseEntity webServer(String url, LinkedHashMap params, String method) { return webServer(url, params, InternetConfig.defaultConfig(), method); } @@ -787,12 +853,26 @@ public static ResponseEntity webServer(String url, HashMap param * 下载的配置 * @return T 返回的数据 */ - public static ResponseEntity webServer(String url, HashMap params, InternetConfig config, String method) { + public static ResponseEntity webServer(String url, LinkedHashMap params, InternetConfig config, String method) { config.setRequest_type(InternetConfig.request_webserver); ResponseEntity responseEntity = new ResponseEntity(); responseEntity.setUrl(url); responseEntity.setParams(params); responseEntity.setKey(config.getKey()); + + // 判断是否需要离线 + if (config.isSave()) { + if (!Handler_Network.isNetworkAvailable(Ioc.getIoc().getApplication())) { + Ioc.getIoc().getLogger().e("无法连接到网络 将获取离线数据"); + String result = HttpCache.getUrlCache(url, params); + if (result != null) { + responseEntity.setContent(result, false); + responseEntity.setStatus(result_ok); + return responseEntity; + } + } + } + try { config.setMethod(method); HttpURLConnection conn = getDefaultHttpClient(url, config); @@ -802,7 +882,7 @@ public static ResponseEntity webServer(String url, HashMap param OutputStream out = conn.getOutputStream(); String content = ""; if (params == null) { - params = new HashMap(); + params = new LinkedHashMap(); } content = getXml(params, method, config.getName_space()); content = content.replace(" standalone='yes' ", ""); @@ -811,7 +891,7 @@ public static ResponseEntity webServer(String url, HashMap param out.close(); InputStream inStream = conn.getInputStream(); getCookies(config, responseEntity, conn); - responseEntity.setContent(XMLtoJsonUtil.XMLtoJson(inputStreamToString(inStream, config.getCharset()), method, config.getCharset())); + responseEntity.setContent(XMLtoJsonUtil.XMLtoJson(inputStreamToString(inStream, config.getCharset()), method, config.getCharset()), config.isSave()); responseEntity.setKey(config.getKey()); conn.disconnect(); responseEntity.setStatus(result_ok); @@ -871,7 +951,7 @@ public static void ajaxWebServer(String url, String method, InternetConfig confi * 回调函数 * @return void */ - public static void ajaxWebServer(String url, String method, HashMap params, AjaxCallBack callBack) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, AjaxCallBack callBack) { InternetConfig config = InternetConfig.defaultConfig(); config.setMethod(method); config.setRequest_type(InternetConfig.request_webserver); @@ -892,7 +972,7 @@ public static void ajaxWebServer(String url, String method, HashMap params, InternetConfig config, AjaxCallBack callBack) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, InternetConfig config, AjaxCallBack callBack) { if (config == null) { config = InternetConfig.defaultConfig(); } @@ -915,7 +995,7 @@ public static void ajaxWebServer(String url, String method, HashMap params, AjaxTimeCallBack callBack) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, AjaxTimeCallBack callBack) { InternetConfig config = InternetConfig.defaultConfig(); config.setMethod(method); config.setRequest_type(InternetConfig.request_webserver); @@ -936,7 +1016,7 @@ public static void ajaxWebServer(String url, String method, HashMap params, InternetConfig config, AjaxTimeCallBack callBack) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, InternetConfig config, AjaxTimeCallBack callBack) { if (config == null) { config = InternetConfig.defaultConfig(); } @@ -987,7 +1067,7 @@ public static void ajaxGet(String url, InternetConfig config, AjaxCallBack callB * 回调函数 * @return void */ - public static void ajaxGet(String url, HashMap params, AjaxCallBack callBack) { + public static void ajaxGet(String url, LinkedHashMap params, AjaxCallBack callBack) { ajaxGet(url, params, InternetConfig.defaultConfig(), callBack); } @@ -1005,7 +1085,7 @@ public static void ajaxGet(String url, HashMap params, AjaxCallB * 回调函数 * @return void */ - public static void ajaxGet(String url, HashMap params, InternetConfig config, AjaxCallBack callBack) { + public static void ajaxGet(String url, LinkedHashMap params, InternetConfig config, AjaxCallBack callBack) { if (config == null) { config = InternetConfig.defaultConfig(); } @@ -1027,7 +1107,7 @@ public static void ajaxGet(String url, HashMap params, InternetC * 回调函数 * @return void */ - public static void ajaxGet(String url, HashMap params, InternetConfig config, AjaxTimeCallBack callBack) { + public static void ajaxGet(String url, LinkedHashMap params, InternetConfig config, AjaxTimeCallBack callBack) { if (config == null) { config = InternetConfig.defaultConfig(); } @@ -1037,8 +1117,8 @@ public static void ajaxGet(String url, HashMap params, InternetC @SuppressLint("HandlerLeak") static class AjaxTask extends basicRunable implements Runnable { - private AjaxCallBack mCallBack; - private Handler mHandler = new Handler() { + private AjaxCallBack mCallBack; + private Handler mHandler = new Handler() { public void handleMessage(Message msg) { if (mCallBack.stop()) { return; @@ -1047,7 +1127,7 @@ public void handleMessage(Message msg) { } }; - public AjaxTask(String url, HashMap params, InternetConfig internetConfig, AjaxCallBack callBack) { + public AjaxTask(String url, LinkedHashMap params, InternetConfig internetConfig, AjaxCallBack callBack) { this.mCallBack = callBack; this.internetConfig = internetConfig; this.url = url; @@ -1069,11 +1149,11 @@ public void run() { msg.obj = webServer(url, params, internetConfig, internetConfig.getMethod()); break; case InternetConfig.request_form: - if (internetConfig.getProgress()!=null) { - msg.obj = formProgress(url, params, internetConfig.getFiles(), internetConfig,internetConfig.getProgress()); - }else { - msg.obj = form(url, params, internetConfig.getFiles(), internetConfig); - } + // if (internetConfig.getProgress()!=null) { + msg.obj = formProgress(url, params, internetConfig.getFiles(), internetConfig, internetConfig.getProgress()); + // }else { + // msg.obj = form(url, params, internetConfig.getFiles(), internetConfig); + // } break; default: break; @@ -1085,20 +1165,20 @@ public void run() { static class basicRunable { InternetConfig internetConfig; String url; - HashMap params; + LinkedHashMap params; } @SuppressLint("HandlerLeak") static class TimeTask extends basicRunable implements Runnable { - private AjaxTimeCallBack mCallBack; + private AjaxTimeCallBack mCallBack; - private Handler mHandler = new Handler() { + private Handler mHandler = new Handler() { public void handleMessage(Message msg) { mCallBack.callBack((ResponseEntity) msg.obj); } }; - public TimeTask(String url, HashMap params, InternetConfig internetConfig, AjaxTimeCallBack callBack) { + public TimeTask(String url, LinkedHashMap params, InternetConfig internetConfig, AjaxTimeCallBack callBack) { this.mCallBack = callBack; this.internetConfig = internetConfig; this.url = url; @@ -1149,11 +1229,12 @@ private static HttpURLConnection getDefaultHttpClient(String urls, InternetConfi // HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpsURLConnection.setDefaultHostnameVerifier(hnv); } + System.out.println(urls); URL url = new URL(urls); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - if (config.getFiles()!=null) { - conn.setFixedLengthStreamingMode((int)config.getAll_length()); - } + if (config.getFiles() != null) { + conn.setFixedLengthStreamingMode((int) config.getAll_length()); + } conn.setConnectTimeout(config.getTimeout()); String method = "POST"; if (config.getRequest_type() == InternetConfig.request_get) { @@ -1208,7 +1289,7 @@ public static String inputStreamToString(InputStream in, String charset) throws return out.toString(); } - private static String getXml(HashMap data, String method, String name_space) { + private static String getXml(LinkedHashMap data, String method, String name_space) { XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); try { @@ -1274,8 +1355,8 @@ private static void getCookies(InternetConfig config, ResponseEntity responseEnt } } } - - private static int getOrtherLength(HashMap params, HashMap files,InternetConfig config){ + + private static int getOrtherLength(LinkedHashMap params, HashMap files, InternetConfig config) { long count = 0; StringBuilder sb = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { @@ -1289,26 +1370,27 @@ private static int getOrtherLength(HashMap params, HashMap file : files.entrySet()) { + if (!file.getValue().exists()) { + continue; } + count = count + file.getValue().length(); + StringBuilder sb1 = new StringBuilder(); + sb1.append(PREFIX); + sb1.append(BOUNDARY); + sb1.append(LINEND); + sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); + sb1.append("Content-Type: image/pjpeg; " + LINEND); + sb1.append(LINEND); + count = count + sb1.toString().getBytes().length; + count = count + LINEND.getBytes().length; } byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); count = count + end_data.length; - } + } return (int) count; } } diff --git a/src/com/android/pc/ioc/internet/FastHttpHander.java b/src/com/android/pc/ioc/internet/FastHttpHander.java index 01db639..7a4715a 100644 --- a/src/com/android/pc/ioc/internet/FastHttpHander.java +++ b/src/com/android/pc/ioc/internet/FastHttpHander.java @@ -4,6 +4,7 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import android.app.Activity; @@ -57,7 +58,7 @@ public static void ajax(String url, InternetConfig config, Object object) { * 回调函数 * @return void */ - public static void ajax(String url, HashMap params, Object object) { + public static void ajax(String url, LinkedHashMap params, Object object) { ajax(url, params, InternetConfig.defaultConfig(), object); } @@ -75,7 +76,7 @@ public static void ajax(String url, HashMap params, Object objec * 回调函数 * @return void */ - public static void ajax(String url, HashMap params, final InternetConfig config, final Object object) { + public static void ajax(String url, LinkedHashMap params, final InternetConfig config, final Object object) { config.setRequest_type(InternetConfig.request_post); AjaxCallBack callBack = new AjaxCallBack() { @Override @@ -114,7 +115,7 @@ public static void ajax(String url, AjaxTimeCallBack object) { * @param object * @return void */ - public static void ajax(String url, HashMap params, AjaxTimeCallBack object) { + public static void ajax(String url, LinkedHashMap params, AjaxTimeCallBack object) { InternetConfig config = InternetConfig.defaultConfig(); config.setRequest_type(InternetConfig.request_post); ajax(url, params, config, object); @@ -134,7 +135,7 @@ public static void ajax(String url, HashMap params, AjaxTimeCall * 回调函数 * @return void */ - public static void ajax(String url, HashMap params, InternetConfig config, AjaxTimeCallBack object) { + public static void ajax(String url, LinkedHashMap params, InternetConfig config, AjaxTimeCallBack object) { config.setRequest_type(InternetConfig.request_post); new Thread(new TimeTask(url, params, config, object)).start(); } @@ -173,7 +174,7 @@ public static void ajaxForm(String url, InternetConfig config, Object object) { * @param object * @return void */ - public static void ajaxForm(String url, HashMap params, Object object) { + public static void ajaxForm(String url, LinkedHashMap params, Object object) { ajaxForm(url, params, null, InternetConfig.defaultConfig(), object); } @@ -187,11 +188,11 @@ public static void ajaxForm(String url, HashMap params, Object o * @param object * @return void */ - public static void ajaxForm(String url, HashMap params, HashMap files, Object object) { + public static void ajaxForm(String url, LinkedHashMap params, HashMap files, Object object) { ajaxForm(url, params, files, InternetConfig.defaultConfig(), object); } - - public static void ajaxForm(String url, HashMap params, HashMap files, Object object,Progress progress) { + + public static void ajaxForm(String url, LinkedHashMap params, HashMap files, Object object, Progress progress) { ajaxForm(url, params, files, InternetConfig.defaultConfig(), object); } @@ -206,7 +207,7 @@ public static void ajaxForm(String url, HashMap params, HashMap< * @param object * @return void */ - public static void ajaxForm(String url, HashMap params, HashMap files, final InternetConfig config, final Object object) { + public static void ajaxForm(String url, LinkedHashMap params, HashMap files, final InternetConfig config, final Object object) { config.setRequest_type(InternetConfig.request_form); config.setFiles(files); AjaxCallBack callBack = new AjaxCallBack() { @@ -265,7 +266,7 @@ public static void ajaxGet(String url, InternetConfig config, Object object) { * 回调函数 * @return void */ - public static void ajaxGet(String url, HashMap params, Object object) { + public static void ajaxGet(String url, LinkedHashMap params, Object object) { ajaxGet(url, params, InternetConfig.defaultConfig(), object); } @@ -283,7 +284,7 @@ public static void ajaxGet(String url, HashMap params, Object ob * 回调函数 * @return void */ - public static void ajaxGet(String url, HashMap params, final InternetConfig config, final Object object) { + public static void ajaxGet(String url, LinkedHashMap params, final InternetConfig config, final Object object) { if (config == null) { Ioc.getIoc().getLogger().e(object.getClass().getSimpleName() + " 的网络请求配置不能为空\n"); return; @@ -318,7 +319,7 @@ public boolean stop() { * 回调函数 * @return void */ - public static void ajaxGet(String url, HashMap params, InternetConfig config, AjaxTimeCallBack object) { + public static void ajaxGet(String url, LinkedHashMap params, InternetConfig config, AjaxTimeCallBack object) { if (config == null) { config = InternetConfig.defaultConfig(); } @@ -371,7 +372,7 @@ public static void ajaxWebServer(String url, String method, InternetConfig confi * 回调函数 * @return void */ - public static void ajaxWebServer(String url, String method, HashMap params, Object object) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, Object object) { InternetConfig config = InternetConfig.defaultConfig(); config.setMethod(method); config.setRequest_type(InternetConfig.request_webserver); @@ -392,7 +393,7 @@ public static void ajaxWebServer(String url, String method, HashMap params, final InternetConfig config, final Object object) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, final InternetConfig config, final Object object) { if (config == null) { Ioc.getIoc().getLogger().e(object.getClass().getSimpleName() + " 的网络请求配置不能为空\n"); return; @@ -427,7 +428,7 @@ public boolean stop() { * 回调函数 * @return void */ - public static void ajaxWebServer(String url, String method, HashMap params, AjaxTimeCallBack object) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, AjaxTimeCallBack object) { InternetConfig config = InternetConfig.defaultConfig(); config.setMethod(method); config.setRequest_type(InternetConfig.request_webserver); @@ -448,7 +449,7 @@ public static void ajaxWebServer(String url, String method, HashMap params, InternetConfig config, AjaxTimeCallBack object) { + public static void ajaxWebServer(String url, String method, LinkedHashMap params, InternetConfig config, AjaxTimeCallBack object) { if (config == null) { config = InternetConfig.defaultConfig(); } @@ -473,7 +474,7 @@ private static void http_inject(ResponseEntity entity, Object object, InternetCo if (entity.getStatus() == FastHttp.result_ok) { if (ok == null && arrayList == null) { - Ioc.getIoc().getLogger().e(object.getClass().getSimpleName() + " 的网络请求"+entity.getUrl()+"\nkey为"+entity.getKey()+"没有增加回调方法注释 请检查\n"); + Ioc.getIoc().getLogger().e(object.getClass().getSimpleName() + " 的网络请求" + entity.getUrl() + "\nkey为" + entity.getKey() + "没有增加回调方法注释 请检查\n"); return; } if (ok == null) { @@ -489,7 +490,7 @@ private static void http_inject(ResponseEntity entity, Object object, InternetCo } } else { if (err == null && arrayList == null) { - Ioc.getIoc().getLogger().e(object.getClass().getSimpleName() + " 的网络请求"+entity.getUrl()+"\nkey为"+entity.getKey()+"没有增加回调方法注释 请检查\n"); + Ioc.getIoc().getLogger().e(object.getClass().getSimpleName() + " 的网络请求" + entity.getUrl() + "\nkey为" + entity.getKey() + "没有增加回调方法注释 请检查\n"); return; } if (err == null) { @@ -511,16 +512,15 @@ private static boolean isDestory(Object object) { return ((Activity) object).isFinishing() || !((Activity) object).hasWindowFocus(); } try { - Class clazz = Class.forName("android.support.v4.app.Fragment"); - Class clazz2 = Class.forName("android.app.Fragment"); - if (clazz.isAssignableFrom(object.getClass())||clazz2.isAssignableFrom(object.getClass())) { - Method isDetached = object.getClass().getMethod("isDetached", null); - Method isRemoving = object.getClass().getMethod("isRemoving", null); - return Boolean.valueOf(isDetached.invoke(object).toString())&&Boolean.valueOf(isRemoving.invoke(object).toString()); - } - } catch (Exception e) { - } - + Class clazz = Class.forName("android.support.v4.app.Fragment"); + Class clazz2 = Class.forName("android.app.Fragment"); + if (clazz.isAssignableFrom(object.getClass()) || clazz2.isAssignableFrom(object.getClass())) { + Method isDetached = object.getClass().getMethod("isDetached", null); + Method isRemoving = object.getClass().getMethod("isRemoving", null); + return Boolean.valueOf(isDetached.invoke(object).toString()) && Boolean.valueOf(isRemoving.invoke(object).toString()); + } + } catch (Exception e) { + } return false; } } diff --git a/src/com/android/pc/ioc/internet/HttpCache.java b/src/com/android/pc/ioc/internet/HttpCache.java new file mode 100644 index 0000000..c84aaf3 --- /dev/null +++ b/src/com/android/pc/ioc/internet/HttpCache.java @@ -0,0 +1,45 @@ +package com.android.pc.ioc.internet; + +import java.io.File; +import java.util.LinkedHashMap; + +import com.android.pc.ioc.app.Ioc; +import com.android.pc.util.Handler_File; +import com.android.pc.util.MD5; + +public class HttpCache { + + public static String getUrlCache(String url,LinkedHashMap params) { + if (url == null) { + return null; + } + for (String key : params.keySet()) { + url = url+key+params.get(key); + } + int time = InternetConfig.defaultConfig().getSaveDate(); + + String result = null; + File file = new File(Ioc.getIoc().getApplication().getCacheDir(), getCacheDecodeString(url)); + if (file.exists() && file.isFile()) { + long expiredTime = System.currentTimeMillis() - file.lastModified(); + Ioc.getIoc().getLogger().d("缓存了:" + expiredTime / 60000 + "分钟"); + if (time!=-1&&expiredTime>time) { + file.delete(); + return null; + } + result = Handler_File.getAsString(file); + } + return result; + } + + public static void setUrlCache(String data, String url) { + File file = new File(Ioc.getIoc().getApplication().getCacheDir(), getCacheDecodeString(url)); + // 创建缓存数据到磁盘,就是创建文件 + Handler_File.write(file, data); + } + + private static String getCacheDecodeString(String url) { + // 1. 处理特殊字符 + return MD5.Md5(url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+")); + } +} diff --git a/src/com/android/pc/ioc/internet/InternetConfig.java b/src/com/android/pc/ioc/internet/InternetConfig.java index c206600..0111753 100644 --- a/src/com/android/pc/ioc/internet/InternetConfig.java +++ b/src/com/android/pc/ioc/internet/InternetConfig.java @@ -31,7 +31,6 @@ public class InternetConfig { final public static String content_type_json = "application/json;charset=utf-8"; final public static String content_type_xml = "text/xml; charset=utf-8"; - private int result_type = result_String; /** * 协议 */ @@ -44,10 +43,6 @@ public class InternetConfig { * webservers 也就是.net服务器的接口 必须要设置这个 */ private String method; - //目前未使用 - private boolean instanceFollowRedirects = false; - //目前未使用 - private boolean useCache = false; /** * 字符串的编码 以及服务器的编码 */ @@ -56,8 +51,6 @@ public class InternetConfig { * 定时请求的时间间隔 */ private int time; - //目前未使用 - private String webServerUrl; /** * 请求方式 post get webservers fom等 */ @@ -86,21 +79,29 @@ public class InternetConfig { * 这个用来标记请求 可以让多个请求公用同一个callback */ private int key; + + private long all_length = 0; + /** + * 表单上传进度 + */ + private Progress progress; /** - * 当此参数为true的时候 则表示callback运行在主线程 可以直接更新Ui - * 否则 运行在后台进程 需要用handler来更新Ui + * 是否支持离线 */ - private boolean front = true; + private boolean isSave = false; - private long all_length = 0; + /** + * 缓存的时间(分钟) + */ + private int saveDate = -1; - private Progress progress; + private static InternetConfig defaultConfig = new InternetConfig(){{ + setCharset("utf-8"); + setTime(30 * 1000); + setRequest_type(request_post); + }}; public static InternetConfig defaultConfig() { - InternetConfig defaultConfig = new InternetConfig(); - defaultConfig.charset = "utf-8"; - defaultConfig.time = 30 * 1000; - defaultConfig.request_type = request_post; return defaultConfig; } @@ -142,14 +143,6 @@ public void setTime(int time) { this.time = time * 1000; } - public String getWebServerUrl() { - return webServerUrl; - } - - public void setWebServerUrl(String webServerUrl) { - this.webServerUrl = webServerUrl; - } - public int getRequest_type() { return request_type; } @@ -174,22 +167,6 @@ public void setTimeout(int timeout) { this.timeout = timeout; } - public boolean isInstanceFollowRedirects() { - return instanceFollowRedirects; - } - - public void setInstanceFollowRedirects(boolean instanceFollowRedirects) { - this.instanceFollowRedirects = instanceFollowRedirects; - } - - public boolean isUseCache() { - return useCache; - } - - public void setUseCache(boolean useCache) { - this.useCache = useCache; - } - public String getMethod() { return method; } @@ -208,7 +185,7 @@ public void setContent_type_web(String content_type_web) { @Override public String toString() { - return "InternetConfig [content_type_web=" + content_type_web + ", isHttps=" + isHttps + ", method=" + method + ", instanceFollowRedirects=" + instanceFollowRedirects + ", useCache=" + useCache + ", charset=" + charset + ", time=" + time + ", webServerUrl=" + webServerUrl + ", request_type=" + request_type + ", name_space=" + name_space + ", timeout=" + timeout + ", files=" + files + ", isCookies=" + isCookies + ", key=" + key + "]"; + return "InternetConfig [content_type_web=" + content_type_web + ", isHttps=" + isHttps + ", method=" + method + ", charset=" + charset + ", time=" + time + ", request_type=" + request_type + ", name_space=" + name_space + ", timeout=" + timeout + ", files=" + files + ", isCookies=" + isCookies + ", key=" + key + "]"; } public HashMap getFiles() { @@ -235,20 +212,6 @@ public int getKey() { public void setKey(int key) { this.key = key; } - public boolean isFront() { - return front; - } - - public void setFront(boolean front) { - this.front = front; - } - public int getResult_type() { - return result_type; - } - - public void setResult_type(int result_type) { - this.result_type = result_type; - } public Progress getProgress() { return progress; @@ -265,4 +228,20 @@ public long getAll_length() { public void setAll_length(long all_length) { this.all_length = all_length; } + + public boolean isSave() { + return isSave; + } + + public void setSave(boolean isSave) { + this.isSave = isSave; + } + + public int getSaveDate() { + return saveDate; + } + + public void setSaveDate(int saveDate) { + this.saveDate = saveDate; + } } diff --git a/src/com/android/pc/ioc/internet/ResponseEntity.java b/src/com/android/pc/ioc/internet/ResponseEntity.java index c156724..8fec392 100644 --- a/src/com/android/pc/ioc/internet/ResponseEntity.java +++ b/src/com/android/pc/ioc/internet/ResponseEntity.java @@ -11,22 +11,10 @@ public class ResponseEntity implements Serializable { private int status = -1; private String url; private String content; - private Map headers; private Map cookies; private Map params; - private Object data; - private String fileName; - private int percent; private int key; - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - public int getStatus() { return status; } @@ -48,17 +36,15 @@ public String getContentAsString() { return content; } - public void setContent(String content) { + public void setContent(String content,boolean isSave) { this.content = content; - } - - public Map getHeaders() { - return headers; - } - - public ResponseEntity setHeaders(Map headers) { - this.headers = headers; - return this; + if (isSave) { + //缓存数据 + for (String key : params.keySet()) { + url = url+key+params.get(key); + } + HttpCache.setUrlCache(content, url); + } } public Map getCookies() { @@ -106,17 +92,9 @@ public String makeCookie() { return sb.toString(); } - public int getPercent() { - return percent; - } - - public void setPercent(int percent) { - this.percent = percent; - } - @Override public String toString() { - return "ResponseEntity [status=" + status + ", url=" + url + ", content=" + content + ", headers=" + headers + ", cookies=" + cookies + ", params=" + params + ", fileName=" + fileName + ", percent=" + percent + ", key=" + key + "]"; + return "ResponseEntity [status=" + status + ", url=" + url + ", content=" + content + ", cookies=" + cookies + ", params=" + params + ", key=" + key + "]"; } public int getKey() { @@ -126,12 +104,4 @@ public int getKey() { public void setKey(int key) { this.key = key; } - - public T getData() { - return (T) data; - } - - public void setData(Object data) { - this.data = data; - } } diff --git a/src/com/android/pc/ioc/util/ContextUtils.java b/src/com/android/pc/ioc/util/ContextUtils.java index 0257114..dcaf9e7 100644 --- a/src/com/android/pc/ioc/util/ContextUtils.java +++ b/src/com/android/pc/ioc/util/ContextUtils.java @@ -65,7 +65,8 @@ public class ContextUtils { private static final Map, HashMap>> http_InjectInvokes = new HashMap, HashMap>>(); private static final Map, HashMap>> http_InjectInvokes_OK = new HashMap, HashMap>>(); private static final Map, HashMap>> http_InjectInvokes_Err = new HashMap, HashMap>>(); - + private static final Map, Boolean> inject_status = new HashMap, Boolean>(); + private static HashSet> classes = new HashSet>() { private static final long serialVersionUID = -2816879839908314497L; { @@ -238,8 +239,8 @@ public static ArrayList getViewInvokers(final Class clazz, fin ArrayList orther_list = new ArrayList(); // ---------------------------------------------------------------------------------------------------------- Class template = clazz; - if (all_inject_layers.containsKey(clazz) && orther_inject_invokes.containsKey(clazz)) { - while (template != null && template != Object.class && template != superClass) { + if (all_inject_layers.containsKey(clazz) && orther_inject_invokes.containsKey(clazz)&&checkInjectStatus(clazz)) { + while (template != null && template != Object.class && template != superClass&&inject_status.containsKey(template)) { if (all_inject_layers.containsKey(template) && Activity.class.isAssignableFrom(template)) { layers_list.add(0, all_inject_layers.get(template)); } @@ -472,21 +473,6 @@ public static ArrayList getViewInvokers(final Class clazz, fin return all_list; } - public static void getAdapterViewInvokers(final Class clazz, final Object obj, final Class superClass) { - ArrayList all_list = new ArrayList(); - Class template = clazz; - if (all_inject_views.containsKey(template) && Activity.class.isAssignableFrom(template)) { - all_list.addAll(all_inject_views.get(template)); - } - if (orther_inject_invokes.containsKey(template) && Activity.class.isAssignableFrom(template)) { - all_list.addAll(orther_inject_invokes.get(template)); - } - template = template.getSuperclass(); - if (all_list.size() > 0) { - } - ArrayList views_list = new ArrayList(); - } - public static void getFactoryProvider() { PackageManager pManager = Ioc.getIoc().getApplication().getPackageManager(); @@ -512,8 +498,17 @@ public static void getFactoryProvider() { for (int i = 0; i < classes.length; i++) { Class clazz = classes[i]; + inject_status.put(clazz, true); ContextUtils.getCreateInvokers(clazz); ContextUtils.getViewInvokers(clazz, null, Activity.class); + inject_status.remove(clazz); } } + + public static boolean checkInjectStatus(Class clazz) { + if (inject_status.containsKey(clazz)) { + return false; + } + return true; + } } diff --git a/src/com/android/pc/ioc/verification/AnnotationToRuleConverter.java b/src/com/android/pc/ioc/verification/AnnotationToRuleConverter.java index d9b26b1..dcf19d1 100644 --- a/src/com/android/pc/ioc/verification/AnnotationToRuleConverter.java +++ b/src/com/android/pc/ioc/verification/AnnotationToRuleConverter.java @@ -218,7 +218,7 @@ private static Rule getNumberRule(Field field, View view, NumberRule numbe return Rules.and(message, ruleArray); } - private static Rule getPasswordRule(Field field, View view, Password password) { + private static Rule getPasswordRule(Field field, View view, Password password) { if (!TextView.class.isAssignableFrom(view.getClass())) { Log.w(TAG, String.format(WARN_TEXT, field.getName(), Password.class.getSimpleName())); return null; @@ -227,7 +227,18 @@ private static Rule getPasswordRule(Field field, View view, Password p int messageResId = password.messageResId(); String message = messageResId != 0 ? view.getContext().getString(messageResId) : password.message(); - return Rules.required(message, false); + List> rules = new ArrayList>(); + if (password.minLength() > 0) { + rules.add(Rules.minLength(null, password.minLength(), password.trim())); + } + if (password.maxLength() != Integer.MAX_VALUE) { + rules.add(Rules.maxLength(null, password.maxLength(), password.trim())); + } + + Rule[] ruleArray = new Rule[rules.size()]; + rules.toArray(ruleArray); + + return Rules.and(message, ruleArray); } private static Rule getConfirmPasswordRule(Field field, View view, ConfirmPassword confirmPassword, TextView passwordTextView) { diff --git a/src/com/android/pc/ioc/verification/annotation/Password.java b/src/com/android/pc/ioc/verification/annotation/Password.java index d4ac275..0eebf50 100644 --- a/src/com/android/pc/ioc/verification/annotation/Password.java +++ b/src/com/android/pc/ioc/verification/annotation/Password.java @@ -28,6 +28,9 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Password { public int order(); + public int minLength() default 0; + public int maxLength() default Integer.MAX_VALUE; + public boolean trim() default true; public String message() default "Password is required"; public int messageResId() default 0; } diff --git a/src/com/android/pc/util/Handler_File.java b/src/com/android/pc/util/Handler_File.java index c4e55ab..65f1dd5 100644 --- a/src/com/android/pc/util/Handler_File.java +++ b/src/com/android/pc/util/Handler_File.java @@ -3,6 +3,7 @@ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -11,7 +12,10 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.io.OutputStream; +import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -19,6 +23,8 @@ import android.os.Environment; import android.util.Log; +import com.android.pc.ioc.app.Ioc; + /** * File Utils *