├── .gitignore ├── .idea ├── .name ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── dictionaries │ └── nn.xml ├── encodings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── scopes │ └── scope_settings.xml └── vcs.xml ├── BitherBitmapSample.iml ├── LICENSE ├── README.md ├── REASON.md ├── app ├── .gitignore ├── app.iml ├── build.gradle ├── native-libs │ └── armeabi │ │ ├── libbitherjni.so │ │ └── libjpegbither.so ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── image │ │ └── net │ │ └── bither │ │ └── bitherimage │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── net │ │ └── bither │ │ ├── image │ │ ├── BitherApplication.java │ │ ├── DisplayImagaUtil.java │ │ ├── MainActivity.java │ │ ├── PicDetailActivity.java │ │ ├── Top.java │ │ ├── adapter │ │ │ └── PiTopAdapter.java │ │ ├── cache │ │ │ ├── AsyncTask.java │ │ │ ├── BitmapCallback.java │ │ │ ├── DiskLruCache.java │ │ │ ├── FetcherHolder.java │ │ │ ├── FileDowloadProgressListener.java │ │ │ ├── ImageCache.java │ │ │ ├── ImageFetcher.java │ │ │ ├── ImageManageUtil.java │ │ │ ├── ImageResizer.java │ │ │ ├── ImageWorker.java │ │ │ └── Utils.java │ │ ├── exception │ │ │ ├── Http400Exception.java │ │ │ ├── Http404Exception.java │ │ │ └── HttpException.java │ │ ├── http │ │ │ ├── BaseHttpResponse.java │ │ │ ├── GetChannelApi.java │ │ │ ├── HttpGetResponse.java │ │ │ └── HttpSetting.java │ │ ├── runnable │ │ │ ├── BaseRunnable.java │ │ │ ├── GetChannelRunnable.java │ │ │ └── HandlerMessage.java │ │ └── ui │ │ │ └── base │ │ │ ├── ImageProgressView.java │ │ │ ├── PicDetailClickListener.java │ │ │ └── TopAnimHandler.java │ │ └── util │ │ └── NativeUtil.java │ └── res │ ├── anim │ ├── slide_in_bottom.xml │ ├── slide_in_right.xml │ ├── slide_in_top.xml │ ├── slide_out_bottom_left.xml │ ├── slide_out_right.xml │ └── slide_out_top.xml │ ├── drawable-hdpi │ ├── button_small_green.9.png │ ├── button_small_green_pressed.9.png │ ├── ic_launcher.png │ ├── tab_divider.9.png │ └── ui_topnav_titlebar_background.9.png │ ├── drawable-mdpi │ ├── grid_cell_background.9.png │ ├── grid_cell_overlay.9.png │ ├── grid_photo_overlay.9.png │ ├── ic_launcher.png │ ├── photo_bg_default.9.png │ ├── photo_bg_pressed.9.png │ ├── photo_delete.png │ └── photo_delete_pressed.png │ ├── drawable-xhdpi │ ├── ic_launcher.png │ └── title_bar_light_back.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── drawable │ ├── button_small_green_bg.xml │ ├── image_progress_view_background.xml │ ├── image_progress_view_progress_drawable.xml │ ├── photo_bg_selector.xml │ ├── photo_touchable_foreground.xml │ ├── post_share_at_user_list_item_bg.xml │ ├── progress_horizontal.xml │ ├── selectable_background.xml │ ├── tab_button_background.xml │ ├── top_amt_background.xml │ ├── top_amt_background_small.xml │ ├── transparent.xml │ ├── ui_touchable_bg.xml │ ├── user_level_progress_background.xml │ └── user_level_progress_drawable.xml │ ├── layout │ ├── activity_main.xml │ ├── activity_pic_detail.xml │ ├── image_progress_view_progress_bar.xml │ ├── list_item_top.xml │ └── list_item_top_grid_item.xml │ ├── menu │ └── main.xml │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── bither-bitmap-sample.iml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | 19 | # Local configuration file (sdk path, etc) 20 | local.properties 21 | 22 | # Proguard folder generated by Eclipse 23 | proguard/ 24 | 25 | # Log Files 26 | *.log 27 | 28 | .gradle 29 | /local.properties 30 | /.idea/workspace.xml 31 | /.idea/libraries 32 | .DS_Store 33 | /build 34 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | bitherImage -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/dictionaries/nn.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | Abstraction issues 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | JDK 30 | 31 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/scopes/scope_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BitherBitmapSample.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The reason of this project : [REASON.md](https://github.com/bither/bither-bitmap-sample/blob/master/REASON.md) 2 | bither-bitmap-sample 3 | ==================== 4 | 5 | Bither Team's Bitmap Sample! 6 | -------------------------------------------------------------------------------- /REASON.md: -------------------------------------------------------------------------------- 1 | # Android, Bitmap and OOM (Out Of Memory) 2 | 3 | A month ago, I wrote an article ["Why the image quality of iPhone is much better than Android?"] (https://github.com/bither/bither-android-lib/blob/master/REASON.md). After reading that article, you may understand the importance of the `optimize_coding` parameter. In fact, there are more confusions made by Google, not only in image quality. 4 | 5 | Today, I want to tell you something about the Bitmap object on Android platform. 6 | 7 | We all know that the Bitmap object consumes memory. For example, if you want to show a square image with 612 pixels (both height and width), the related Bitmap object may need `612*612*4=1498176 bytes` of memory, nearly `1.5MB`. For a desktop application, that is not a problem, we can get as many available memory as we need. But for a mobile App, it is too much, mobile OS (iOS or Android) strictly limit the memory usage for each App. If your App exceed the limit, then there will be an OOM (Out Of Memory) exception, and the OS will kill your App to protect the whole system and other normal running Apps. 8 | 9 | The OOM exception is a headache problem for almost every developers. (What? You haven't faced OOM yet? Are you really a developer?) 10 | 11 | After searching on the Internet, we may find many "funny" solutions: 12 | 13 | 1. Reduce the display size of the image, instead of using` ARGB_8888` (32 bits), use `ARGB_4444` (16 bits) or even `RGB_565` (8 bits). Yes, smaller and worse quality may use less amount of memory, but is that really a good idea? 14 | 15 | 2. Explicit(manually) recycle the memory of the Bitmap object. It seems to be a good solution, but when you use this method on a listview scrolling to display so many images, you may have to face another exception `trying to use a recycled bitmap`. 16 | 17 | 3. Set the Bitmap object as soft reference, frequently calling GC (Garbage Collection) manually. It may lower the probability of OOM a little, but the exception still happens. 18 | 19 | We had tried all these "solutions", and also we used DDMS to monitor the memory usage. We even tried to analyse the possible memory leak reasons with the MAT (Memory Analyzer Tool). 20 | 21 | For simplicity, we ran a clean project to trace the problem, BitmapFun (developed by Google for training purpose). But still helpless, when scrolling the listview of the BitmapFun, the memory usage are increased raplidly, and if scrolled faster, the BitmapFun will throw OOM exception too. WTF! 22 | 23 | Finally, after deeply digging, we found the solution. It's also a simple option : `inPurgeable` (and related `inInputShareable`). 24 | 25 | You can find [more detailed description of BitmapFactory.options.inPurgeable on Google's website] (http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inPurgeable). 26 | 27 | 28 | > If this is set to true, then the resulting bitmap will allocate its pixels such that they can be purged if the system needs to reclaim memory. In that instance, when the pixels need to be accessed again (e.g. the bitmap is drawn, getPixels() is called), they will be automatically re-decoded. 29 | 30 | This is the ultimate solution for OOM exception. Because the image displayed in an App often comes from jpg or png format, in contrast to the Bitmap object's memory usage (e.g. : nearly 1.5MB), jpg or png are much smaller (e.g. : 50KB). With reserving the reference to the source (InputStream or ByteArray), we only need much smaller amount of memory, and when we need to redisplay the image, the re-decode consumptions are even not a problem for modern computing devices. Needing re-decode, but no OOM exception, what an important option it is! 31 | 32 | Now you can set inPurgeable to true (also set InputShareable to true), and use DDMS to monitor the memory usage. You may find that no matter how fast you scrolling the listview or displaying the full size image, the memory usage will remain low and stable. You will never face the OOM (caused by Bitmap) again! 33 | 34 | The inPurgeable options is very important, but the Google's advice is "avoid using". How funny is this? 35 | 36 | After the discussion of the memory usage of the Bitmap object, here I want to tell you some principles on resolving the memory issue on Android platform: 37 | 38 | 1. OOM happens on any place (normally not on the problem line), the only thing we can do is to analyze the memory leak. 39 | 40 | 2. Android GC is trustable, and we don't need to recycle manually, we don't need to frequently calling the `gc()`. After the lifecycle of an object, just remove the reference is enough, the Android GC will finish its work. 41 | 42 | 3. Always use `ARGB_8888`. 43 | 44 | 4. All memory leak problems are related to reference issue, normally DDMS+reviewing code is enough to solve these problems. 45 | 46 | 5. We may find that OOM in this year are not as severe as before. Thanks for the hardware industry, now we have 3GB memory mobile phones, :) 47 | 48 | In conclusion, no matter for `optimize_coding` or `inPurgeable`, Google are confused, but Apple really understand these. The iOS developers are so lucky! 49 | 50 | [Source code](https://github.com/bither/bither-bitmap-sample) 51 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 20 5 | buildToolsVersion "19.1.0" 6 | 7 | defaultConfig { 8 | applicationId "net.bither.image" 9 | minSdkVersion 9 10 | targetSdkVersion 20 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | runProguard false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile 'com.android.support:appcompat-v7:20.0.0' 25 | } 26 | -------------------------------------------------------------------------------- /app/native-libs/armeabi/libbitherjni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/native-libs/armeabi/libbitherjni.so -------------------------------------------------------------------------------- /app/native-libs/armeabi/libjpegbither.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/native-libs/armeabi/libjpegbither.so -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/nn/Documents/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/image/net/bither/bitherimage/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package image.net.bither.bitherimage; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 41 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/BitherApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image; 18 | 19 | import android.app.Application; 20 | import android.content.Context; 21 | 22 | public class BitherApplication extends Application { 23 | public static Context mContext; 24 | 25 | public static final String PIC_PASS_VALUE_TAG = "pic_pass_value"; 26 | 27 | @Override 28 | public void onCreate() { 29 | super.onCreate(); 30 | mContext = getApplicationContext(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/DisplayImagaUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image; 18 | 19 | import android.widget.ImageView; 20 | 21 | import net.bither.image.cache.FetcherHolder; 22 | import net.bither.image.cache.ImageManageUtil; 23 | 24 | import java.util.Locale; 25 | 26 | public class DisplayImagaUtil { 27 | 28 | public static void showSmallImage(String fileName, 29 | ImageView iv, boolean isAddMemoryCache) { 30 | String url = "http://pic.getcai.com/pic/%d/%s.jpg/"; 31 | url = String.format(Locale.US, url, ImageManageUtil.SMALL_IMAGE_WIDTH, fileName); 32 | FetcherHolder.getSmallImageFetcher().loadImage( 33 | url, iv, isAddMemoryCache); 34 | } 35 | 36 | public static void showLargeImage(String fileName, 37 | ImageView iv, boolean isAddMemoryCache) { 38 | String url = "http://pic.getcai.com/pic/%d/%s.jpg/"; 39 | url = String.format(Locale.US, url, ImageManageUtil.IMAGE_WIDTH, fileName); 40 | FetcherHolder.getLargeImageFetcher().loadImage( 41 | url, iv, isAddMemoryCache); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image; 18 | 19 | import android.app.Activity; 20 | import android.os.Handler; 21 | import android.os.Message; 22 | import android.support.v7.app.ActionBarActivity; 23 | import android.os.Bundle; 24 | import android.view.Menu; 25 | import android.view.MenuItem; 26 | import android.widget.AbsListView; 27 | import android.widget.ListView; 28 | 29 | import net.bither.image.adapter.PiTopAdapter; 30 | import net.bither.image.runnable.GetChannelRunnable; 31 | import net.bither.image.runnable.HandlerMessage; 32 | 33 | import java.util.ArrayList; 34 | import java.util.List; 35 | 36 | 37 | public class MainActivity extends Activity { 38 | private ListView lv; 39 | private List mTops = new ArrayList(); 40 | private PiTopAdapter mAdapter; 41 | private boolean isLoading = false; 42 | private boolean noMore = false; 43 | private long lastTopId = -1; 44 | 45 | @Override 46 | protected void onCreate(Bundle savedInstanceState) { 47 | super.onCreate(savedInstanceState); 48 | setContentView(R.layout.activity_main); 49 | initView(); 50 | } 51 | 52 | private void initView() { 53 | 54 | lv = (ListView) findViewById(R.id.lv_top); 55 | lv.setOnScrollListener(onScrollListener); 56 | 57 | mAdapter = new PiTopAdapter(MainActivity.this, mTops); 58 | lv.setAdapter(mAdapter); 59 | getTops(); 60 | 61 | } 62 | 63 | @Override 64 | public boolean onCreateOptionsMenu(Menu menu) { 65 | // Inflate the menu; this adds items to the action bar if it is present. 66 | getMenuInflater().inflate(R.menu.main, menu); 67 | return true; 68 | } 69 | 70 | @Override 71 | public boolean onOptionsItemSelected(MenuItem item) { 72 | // Handle action bar item clicks here. The action bar will 73 | // automatically handle clicks on the Home/Up button, so long 74 | // as you specify a parent activity in AndroidManifest.xml. 75 | int id = item.getItemId(); 76 | if (id == R.id.action_settings) { 77 | return true; 78 | } 79 | return super.onOptionsItemSelected(item); 80 | } 81 | 82 | private AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() { 83 | private int lastFirstVisibleItem; 84 | 85 | public void onScrollStateChanged(AbsListView view, int scrollState) { 86 | 87 | } 88 | 89 | public void onScroll(AbsListView view, int firstVisibleItem, 90 | int visibleItemCount, int totalItemCount) { 91 | if (firstVisibleItem + visibleItemCount >= totalItemCount - 2 92 | && !noMore && mTops.size() > 0 && !isLoading 93 | && lastFirstVisibleItem < firstVisibleItem) { 94 | getTops(); 95 | } 96 | lastFirstVisibleItem = firstVisibleItem; 97 | } 98 | }; 99 | 100 | private void getTops() { 101 | isLoading = true; 102 | GetChannelRunnable getTopRunnable = new GetChannelRunnable( 103 | lastTopId); 104 | getTopRunnable.setHandler(getTopHandler); 105 | new Thread(getTopRunnable).start(); 106 | } 107 | 108 | private Handler getTopHandler = new Handler() { 109 | @Override 110 | public void dispatchMessage(Message msg) { 111 | switch (msg.what) { 112 | case HandlerMessage.MSG_PREPARE: 113 | 114 | break; 115 | case HandlerMessage.MSG_SUCCESS: 116 | 117 | @SuppressWarnings("unchecked") 118 | List tempList = (List) msg.obj; 119 | if (lastTopId <= 0) { 120 | 121 | mTops.clear(); 122 | } 123 | if (tempList != null && tempList.size() > 0) { 124 | 125 | lastTopId = tempList.get(tempList.size() - 1) 126 | .getTopId(); 127 | 128 | noMore = false; 129 | mTops.addAll(tempList); 130 | mAdapter.notifyDataSetChanged(); 131 | 132 | } else { 133 | noMore = true; 134 | } 135 | isLoading = false; 136 | lv.postDelayed(new Runnable() { 137 | @Override 138 | public void run() { 139 | int lastVisiblePosition = lv 140 | .getFirstVisiblePosition() 141 | + lv.getChildCount(); 142 | int totalCount = mAdapter.getCount(); 143 | if (!noMore && lastVisiblePosition >= totalCount - 2 144 | && totalCount > 0) { 145 | getTops(); 146 | } 147 | } 148 | }, 100); 149 | break; 150 | case HandlerMessage.MSG_FAILURE: 151 | 152 | isLoading = false; 153 | break; 154 | default: 155 | break; 156 | } 157 | super.dispatchMessage(msg); 158 | } 159 | }; 160 | 161 | } 162 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/PicDetailActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.image; 17 | 18 | import android.app.Activity; 19 | import android.os.Bundle; 20 | import android.view.View; 21 | import android.view.WindowManager; 22 | import android.widget.Button; 23 | import android.widget.ImageButton; 24 | 25 | import net.bither.image.cache.ImageManageUtil; 26 | import net.bither.image.ui.base.ImageProgressView; 27 | 28 | import java.util.Locale; 29 | 30 | public class PicDetailActivity extends Activity { 31 | private static final int LIST_TOP_OFFSET = ImageManageUtil.dip2pix(50); 32 | private boolean useMemoryCache = false; 33 | private ImageProgressView ipvPhoto; 34 | private ImageButton ibBack; 35 | private Button btnBack; 36 | private Top top; 37 | 38 | @Override 39 | protected void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | overridePendingTransition(R.anim.slide_in_right, 0); 42 | setContentView(R.layout.activity_pic_detail); 43 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 44 | getWindow().getAttributes().dimAmount = 0.75f; 45 | if (getIntent().getExtras() != null 46 | && getIntent().getExtras().containsKey( 47 | BitherApplication.PIC_PASS_VALUE_TAG)) { 48 | top = (Top) getIntent().getExtras().get( 49 | BitherApplication.PIC_PASS_VALUE_TAG); 50 | } 51 | if (top == null) { 52 | finish(); 53 | return; 54 | } 55 | 56 | 57 | showPiCommentInfo(); 58 | 59 | } 60 | 61 | private void showPiCommentInfo() { 62 | ipvPhoto = (ImageProgressView) findViewById(R.id.ipv_photo_big); 63 | ibBack=(ImageButton)findViewById(R.id.ibtn_back); 64 | ibBack.setOnClickListener(new View.OnClickListener() { 65 | @Override 66 | public void onClick(View v) { 67 | finish(); 68 | overridePendingTransition(0, R.anim.slide_out_right); 69 | } 70 | }); 71 | findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() { 72 | @Override 73 | public void onClick(View v) { 74 | finish(); 75 | overridePendingTransition(0, R.anim.slide_out_right); 76 | } 77 | }); 78 | ipvPhoto.dowloadPicameraImage(top.getPicName(), 79 | useMemoryCache); 80 | } 81 | 82 | 83 | private boolean scrolled = false; 84 | 85 | 86 | @Override 87 | public void onBackPressed() { 88 | 89 | super.onBackPressed(); 90 | overridePendingTransition(0, R.anim.slide_out_right); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/Top.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image; 18 | 19 | import org.json.JSONArray; 20 | import org.json.JSONException; 21 | import org.json.JSONObject; 22 | 23 | import java.io.Serializable; 24 | import java.text.ParseException; 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | 28 | public class Top implements Serializable { 29 | private static final long serialVersionUID = 1L; 30 | private static final String TOP_ID = "pic_id"; 31 | public static final String PIC_NAME = "pic_name"; 32 | 33 | 34 | private long mTopId; 35 | private String picName; 36 | 37 | public long getTopId() { 38 | return mTopId; 39 | } 40 | 41 | public void setTopId(long mTopId) { 42 | this.mTopId = mTopId; 43 | } 44 | 45 | public String getPicName() { 46 | return this.picName; 47 | } 48 | 49 | public void setPicName(String picName) { 50 | this.picName = picName; 51 | } 52 | 53 | public static List formatArray(JSONArray jsonArray) 54 | throws JSONException, ParseException { 55 | List tops = new ArrayList(); 56 | for (int i = 0; i < jsonArray.length(); i++) { 57 | Top top = new Top(); 58 | JSONObject jsonObject = jsonArray.getJSONObject(i); 59 | if (!jsonObject.isNull(TOP_ID)) { 60 | top.setTopId(jsonObject.getLong(TOP_ID)); 61 | } 62 | if (!jsonObject.isNull(PIC_NAME)) { 63 | top.setPicName(jsonObject.getString(PIC_NAME)); 64 | } 65 | 66 | tops.add(top); 67 | } 68 | return tops; 69 | 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/adapter/PiTopAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.adapter; 18 | 19 | import android.content.Context; 20 | import android.view.LayoutInflater; 21 | import android.view.View; 22 | import android.view.ViewGroup; 23 | import android.widget.BaseAdapter; 24 | import android.widget.LinearLayout; 25 | 26 | import net.bither.image.ui.base.PicDetailClickListener; 27 | import net.bither.image.R; 28 | import net.bither.image.Top; 29 | import net.bither.image.cache.ImageManageUtil; 30 | import net.bither.image.ui.base.TopAnimHandler; 31 | 32 | import java.util.ArrayList; 33 | import java.util.List; 34 | 35 | public class PiTopAdapter extends BaseAdapter { 36 | private List mTops; 37 | private Context mContext; 38 | private LayoutInflater mLayoutInflater; 39 | public static final int ColumnCount = ImageManageUtil.getScreenWidth() >= 1080 ? 4 40 | : 3; 41 | static int margin = ImageManageUtil.dip2pix(1); 42 | static int topMargin = ImageManageUtil.dip2pix(0); 43 | static int topPadding = ImageManageUtil.dip2pix(7); 44 | static int horizontalPadding = ImageManageUtil.dip2pix(5); 45 | public static final int imageSize = (ImageManageUtil.getScreenWidth() 46 | - margin * (ColumnCount + 1) - horizontalPadding * 2) 47 | / ColumnCount; 48 | 49 | public PiTopAdapter(Context context, List tops) { 50 | mTops = tops; 51 | mContext = context; 52 | mLayoutInflater = LayoutInflater.from(mContext); 53 | 54 | } 55 | 56 | @Override 57 | public int getCount() { 58 | if (mTops == null) { 59 | return 0; 60 | } 61 | int count = (int) Math.ceil((double) mTops.size() 62 | / (double) ColumnCount); 63 | return count; 64 | } 65 | 66 | @SuppressWarnings("unchecked") 67 | @Override 68 | public View getView(int position, View convertView, ViewGroup parent) { 69 | List cells; 70 | if (convertView == null) { 71 | LinearLayout ll = (LinearLayout) mLayoutInflater.inflate( 72 | R.layout.list_item_top, null); 73 | LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( 74 | imageSize, imageSize); 75 | lp.rightMargin = margin; 76 | cells = new ArrayList(); 77 | for (int i = 0; i < ColumnCount; i++) { 78 | TopAnimHandler.CellHolder cell = new TopAnimHandler.CellHolder(mLayoutInflater); 79 | cells.add(cell); 80 | cell.addToView(ll, lp); 81 | } 82 | ll.setTag(cells); 83 | convertView = ll; 84 | } else { 85 | cells = (List) convertView.getTag(); 86 | // for (TopAnimHandler.CellHolder cellHolder : cells) { 87 | // animHandler.obtainMessage(TopAnimHandler.MSG.ADD_CELL, cellHolder) 88 | // .sendToTarget(); 89 | // } 90 | } 91 | 92 | if (position == 0) { 93 | convertView.setPadding(margin + horizontalPadding, margin 94 | + topMargin + topPadding, horizontalPadding, 0); 95 | } else { 96 | convertView.setPadding(margin + horizontalPadding, margin 97 | + topMargin, horizontalPadding, 0); 98 | } 99 | for (int i = 0; i < ColumnCount; i++) { 100 | TopAnimHandler.CellHolder cell = cells.get(i); 101 | int p = position * ColumnCount + i; 102 | if (p < mTops.size()) { 103 | cell.fl.setVisibility(View.VISIBLE); 104 | Top top = mTops.get(p); 105 | cell.setPiCommon(top); 106 | 107 | cell.fl.setOnClickListener(new PicDetailClickListener(top 108 | )); 109 | if (top != null) { 110 | cell.reset(); 111 | } 112 | } else { 113 | cell.setPiCommon(null); 114 | cell.fl.setVisibility(View.INVISIBLE); 115 | } 116 | } 117 | return convertView; 118 | } 119 | 120 | @Override 121 | public Object getItem(int position) { 122 | return null; 123 | } 124 | 125 | @Override 126 | public long getItemId(int position) { 127 | return 0; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/BitmapCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright (C) 2012 The Android Open Source Project 19 | * 20 | * Licensed under the Apache License, Version 2.0 (the "License"); 21 | * you may not use this file except in compliance with the License. 22 | * You may obtain a copy of the License at 23 | * 24 | * http://www.apache.org/licenses/LICENSE-2.0 25 | * 26 | * Unless required by applicable law or agreed to in writing, software 27 | * distributed under the License is distributed on an "AS IS" BASIS, 28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | * See the License for the specific language governing permissions and 30 | * limitations under the License. 31 | */ 32 | 33 | package net.bither.image.cache; 34 | 35 | import android.graphics.Bitmap; 36 | 37 | public abstract interface BitmapCallback { 38 | public abstract void bindToTask( 39 | AsyncTask paramLoadBitmapTask); 40 | 41 | public abstract void reportError(); 42 | 43 | public abstract void reportProgress(String paramString, int paramInt); 44 | 45 | public abstract void setBitmap(String paramString, Bitmap paramBitmap); 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/FetcherHolder.java: -------------------------------------------------------------------------------- 1 | package net.bither.image.cache; 2 | 3 | import android.graphics.Bitmap.CompressFormat; 4 | 5 | import net.bither.image.BitherApplication; 6 | 7 | 8 | public class FetcherHolder { 9 | private static ImageFetcher LARGE_IMAGE_FETCHER; 10 | private static ImageFetcher SMALL_IMAGE_FETCHER; 11 | // public static final String LARGE_IMAGE_CACHE_DIR = "lcache"; 12 | // public static final String SMALL_IMAGE_CACHE_DIR = "scache"; 13 | 14 | public static final String PI_IMAGE_CACHE_DIR = "picache"; 15 | 16 | private static ImageCache IMAGE_CACHE; 17 | private static boolean CHECK_JOURNAL = true; 18 | 19 | // TODO : jjz considering to upgrade the image cache to use same fetcher and 20 | // same imagecache, bitmap should be with the size info, when upgrade getcai 21 | private static void addImageCacheToFetcher(ImageFetcher fetcher) { 22 | ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams( 23 | BitherApplication.mContext, PI_IMAGE_CACHE_DIR); 24 | cacheParams.compressFormat = CompressFormat.JPEG; 25 | cacheParams.compressQuality = 100; 26 | cacheParams.diskCacheSize = 100 * 1024 * 1024; 27 | // Set memory cache to 25% of mem class 28 | cacheParams.setMemCacheSizePercent(BitherApplication.mContext, 0.25f); 29 | if (IMAGE_CACHE == null) { 30 | fetcher.addImageCache(cacheParams, CHECK_JOURNAL); 31 | IMAGE_CACHE = fetcher.getImageCache(); 32 | } else { 33 | fetcher.setImageCache(IMAGE_CACHE); 34 | // because we can only use addImageCache to init Disk Cache, so here 35 | // we call it again 36 | fetcher.addImageCache(cacheParams, CHECK_JOURNAL); 37 | } 38 | CHECK_JOURNAL = false; 39 | } 40 | 41 | public static ImageFetcher getLargeImageFetcher() { 42 | if (LARGE_IMAGE_FETCHER == null) { 43 | // In fact we don't use this size at all. Because inPurgeable will 44 | // make bitmap smaller than reducing size 45 | LARGE_IMAGE_FETCHER = new ImageFetcher(BitherApplication.mContext, 46 | Math.min(ImageManageUtil.getScreenWidth(), 47 | ImageManageUtil.IMAGE_WIDTH)); 48 | addImageCacheToFetcher(LARGE_IMAGE_FETCHER); 49 | } 50 | return LARGE_IMAGE_FETCHER; 51 | } 52 | 53 | public static ImageFetcher getSmallImageFetcher() { 54 | // The ImageFetcher takes care of loading images into our ImageView 55 | // children asynchronously 56 | if (SMALL_IMAGE_FETCHER == null) { 57 | SMALL_IMAGE_FETCHER = new ImageFetcher(BitherApplication.mContext, 58 | ImageManageUtil.getSmallImageCacheWidth()); 59 | addImageCacheToFetcher(SMALL_IMAGE_FETCHER); 60 | } 61 | return SMALL_IMAGE_FETCHER; 62 | } 63 | 64 | public static void closeImageFetchers() { 65 | if (FetcherHolder.LARGE_IMAGE_FETCHER != null) { 66 | FetcherHolder.LARGE_IMAGE_FETCHER.closeCache(); 67 | FetcherHolder.LARGE_IMAGE_FETCHER = null; 68 | } 69 | if (FetcherHolder.SMALL_IMAGE_FETCHER != null) { 70 | FetcherHolder.SMALL_IMAGE_FETCHER.closeCache(); 71 | FetcherHolder.SMALL_IMAGE_FETCHER = null; 72 | } 73 | IMAGE_CACHE = null; 74 | CHECK_JOURNAL = true; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/FileDowloadProgressListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.cache; 18 | 19 | public interface FileDowloadProgressListener { 20 | public void onProgress(ProgressValue progressValue); 21 | 22 | public void onCancel(); 23 | 24 | public enum DownloadType { 25 | PREPARE, BEGIN, DOWNLOING, END, CANCEL, ERROR 26 | } 27 | 28 | public class ProgressValue { 29 | private DownloadType mDownloadType; 30 | private int mValue; 31 | private int mSum; 32 | private String mKey; 33 | 34 | public ProgressValue(DownloadType downloadType, int sum, int value) { 35 | this.mDownloadType = downloadType; 36 | this.mValue = value; 37 | this.mSum = sum; 38 | 39 | } 40 | 41 | public ProgressValue(String key, DownloadType downloadType, int sum, 42 | int value) { 43 | this.mDownloadType = downloadType; 44 | this.mValue = value; 45 | this.setSum(sum); 46 | this.setKey(key); 47 | 48 | } 49 | 50 | public DownloadType getDownloadType() { 51 | return mDownloadType; 52 | } 53 | 54 | public void setDownloadType(DownloadType mDownloadType) { 55 | this.mDownloadType = mDownloadType; 56 | } 57 | 58 | public int getValue() { 59 | return mValue; 60 | } 61 | 62 | public void setValue(int mValue) { 63 | this.mValue = mValue; 64 | } 65 | 66 | public String getKey() { 67 | return mKey; 68 | } 69 | 70 | public void setKey(String mKey) { 71 | this.mKey = mKey; 72 | } 73 | 74 | public int getSum() { 75 | return mSum; 76 | } 77 | 78 | public void setSum(int mSum) { 79 | this.mSum = mSum; 80 | } 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/ImageCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright (C) 2012 The Android Open Source Project 19 | * 20 | * Licensed under the Apache License, Version 2.0 (the "License"); 21 | * you may not use this file except in compliance with the License. 22 | * You may obtain a copy of the License at 23 | * 24 | * http://www.apache.org/licenses/LICENSE-2.0 25 | * 26 | * Unless required by applicable law or agreed to in writing, software 27 | * distributed under the License is distributed on an "AS IS" BASIS, 28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | * See the License for the specific language governing permissions and 30 | * limitations under the License. 31 | */ 32 | 33 | package net.bither.image.cache; 34 | 35 | import java.io.File; 36 | import java.io.FileInputStream; 37 | import java.io.IOException; 38 | import java.io.InputStream; 39 | import java.io.OutputStream; 40 | import java.security.MessageDigest; 41 | import java.security.NoSuchAlgorithmException; 42 | 43 | import android.annotation.TargetApi; 44 | import android.app.ActivityManager; 45 | import android.app.Fragment; 46 | import android.app.FragmentManager; 47 | import android.content.Context; 48 | import android.graphics.Bitmap; 49 | import android.graphics.Bitmap.CompressFormat; 50 | import android.graphics.BitmapFactory; 51 | import android.os.Bundle; 52 | import android.os.Environment; 53 | import android.os.StatFs; 54 | import android.support.v4.util.LruCache; 55 | import android.util.Log; 56 | 57 | import net.bither.image.BitherApplication; 58 | import net.bither.image.BuildConfig; 59 | import net.bither.util.NativeUtil; 60 | 61 | 62 | /** 63 | * This class holds our bitmap caches (memory and disk). 64 | */ 65 | public class ImageCache { 66 | private static final String TAG = "ImageCache"; 67 | 68 | // Default memory cache size 69 | private static final int DEFAULT_MEM_CACHE_SIZE = 1024 * 1024 * 5; // 5MB 70 | 71 | // Default disk cache size 72 | private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB 73 | 74 | // Compression settings when writing images to disk cache 75 | private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG; 76 | private static final int DEFAULT_COMPRESS_QUALITY = 70; 77 | private static final int DISK_CACHE_INDEX = 0; 78 | 79 | // Constants to easily toggle various caches 80 | private static final boolean DEFAULT_MEM_CACHE_ENABLED = true; 81 | private static final boolean DEFAULT_DISK_CACHE_ENABLED = true; 82 | private static final boolean DEFAULT_CLEAR_DISK_CACHE_ON_START = false; 83 | private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false; 84 | 85 | private DiskLruCache mDiskLruCache; 86 | private LruCache mMemoryCache; 87 | private ImageCacheParams mCacheParams; 88 | private final Object mDiskCacheLock = new Object(); 89 | private boolean mDiskCacheStarting = true; 90 | 91 | /** 92 | * Creating a new ImageCache object using the specified parameters. 93 | * 94 | * @param cacheParams 95 | * The cache parameters to use to initialize the cache 96 | */ 97 | public ImageCache(ImageCacheParams cacheParams, boolean checkJournal) { 98 | // --checkJournal 99 | init(cacheParams, checkJournal); 100 | } 101 | 102 | /** 103 | * Creating a new ImageCache object using the default parameters. 104 | * 105 | * @param context 106 | * The context to use 107 | * @param uniqueName 108 | * A unique name that will be appended to the cache directory 109 | */ 110 | public ImageCache(Context context, String uniqueName, boolean checkJournal) { 111 | // --checkJournal 112 | init(new ImageCacheParams(context, uniqueName), checkJournal); 113 | } 114 | 115 | /** 116 | * Find and return an existing ImageCache stored in a {@link net.bither.image.cache.ImageCache.RetainFragment} 117 | * , if not found a new one is created using the supplied params and saved 118 | * to a {@link net.bither.image.cache.ImageCache.RetainFragment}. 119 | * 120 | * @param fragmentManager 121 | * The fragment manager to use when dealing with the retained 122 | * fragment. 123 | * @param cacheParams 124 | * The cache parameters to use if creating the ImageCache 125 | * @return An existing retained ImageCache object or a new one if one did 126 | * not exist 127 | */ 128 | public static ImageCache findOrCreateCache(FragmentManager fragmentManager, 129 | ImageCacheParams cacheParams) { 130 | 131 | // Search for, or create an instance of the non-UI RetainFragment 132 | final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager); 133 | 134 | // See if we already have an ImageCache stored in RetainFragment 135 | ImageCache imageCache = (ImageCache) mRetainFragment.getObject(); 136 | 137 | // No existing ImageCache, create one and store it in RetainFragment 138 | if (imageCache == null) { 139 | imageCache = new ImageCache(cacheParams, true); 140 | mRetainFragment.setObject(imageCache); 141 | } 142 | 143 | return imageCache; 144 | } 145 | 146 | /** 147 | * Initialize the cache, providing all parameters. 148 | * 149 | * @param cacheParams 150 | * The cache parameters to initialize the cache 151 | */ 152 | private void init(ImageCacheParams cacheParams, boolean checkJournal) { 153 | // --checkJournal 154 | mCacheParams = cacheParams; 155 | 156 | // Set up memory cache 157 | if (mCacheParams.memoryCacheEnabled) { 158 | if (BuildConfig.DEBUG) { 159 | Log.d(TAG, "Memory cache created (size = " 160 | + mCacheParams.memCacheSize + ")"); 161 | } 162 | mMemoryCache = new LruCache( 163 | mCacheParams.memCacheSize) { 164 | /** 165 | * Measure item size in bytes rather than units which is more 166 | * practical for a bitmap cache 167 | */ 168 | @Override 169 | protected int sizeOf(String key, Bitmap bitmap) { 170 | return getBitmapSize(bitmap); 171 | } 172 | }; 173 | } 174 | 175 | // By default the disk cache is not initialized here as it should be 176 | // initialized 177 | // on a separate thread due to disk access. 178 | if (cacheParams.initDiskCacheOnCreate) { 179 | // Set up disk cache 180 | initDiskCache(checkJournal); 181 | } 182 | } 183 | 184 | /** 185 | * Initializes the disk cache. Note that this includes disk access so this 186 | * should not be executed on the main/UI thread. By default an ImageCache 187 | * does not initialize the disk cache when it is created, instead you should 188 | * call initDiskCache() to initialize it on a background thread. 189 | */ 190 | public void initDiskCache(boolean checkJournal) { 191 | // --checkJournal 192 | // Set up disk cache 193 | synchronized (mDiskCacheLock) { 194 | if (mDiskLruCache == null || mDiskLruCache.isClosed()) { 195 | File diskCacheDir = mCacheParams.diskCacheDir; 196 | if (mCacheParams.diskCacheEnabled && diskCacheDir != null) { 197 | if (!diskCacheDir.exists()) { 198 | diskCacheDir.mkdirs(); 199 | } 200 | if (getUsableSpace(diskCacheDir) > 0.5 * 1024 * 1024) { 201 | try { 202 | mDiskLruCache = DiskLruCache 203 | .open(diskCacheDir, 1, 1, 204 | mCacheParams.diskCacheSize, 205 | checkJournal); 206 | if (BuildConfig.DEBUG) { 207 | Log.d(TAG, "Disk cache initialized"); 208 | } 209 | } catch (final IOException e) { 210 | mCacheParams.diskCacheDir = null; 211 | Log.e(TAG, "initDiskCache - " + e); 212 | } 213 | } 214 | } 215 | } 216 | mDiskCacheStarting = false; 217 | mDiskCacheLock.notifyAll(); 218 | } 219 | } 220 | 221 | /** 222 | * Adds a bitmap to both memory and disk cache. 223 | * 224 | * @param data 225 | * Unique identifier for the bitmap to store 226 | * @param bitmap 227 | * The bitmap to store 228 | */ 229 | public void addBitmapToCache(String data, Bitmap bitmap, 230 | boolean addToMemoryCache) { 231 | // addToMemoryCache 232 | if (data == null || bitmap == null) { 233 | return; 234 | } 235 | 236 | if (addToMemoryCache) { 237 | // Add to memory cache 238 | if (mMemoryCache != null && mMemoryCache.get(data) == null) { 239 | mMemoryCache.put(data, bitmap); 240 | } 241 | } 242 | 243 | synchronized (mDiskCacheLock) { 244 | // Add to disk cache 245 | if (mDiskLruCache != null) { 246 | final String key = hashKeyForDisk(data); 247 | OutputStream out = null; 248 | try { 249 | DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); 250 | if (snapshot == null) { 251 | final DiskLruCache.Editor editor = mDiskLruCache 252 | .edit(key); 253 | if (editor != null) { 254 | out = editor.newOutputStream(DISK_CACHE_INDEX); 255 | File httpFile = new File(getDiskCacheDir( 256 | BitherApplication.mContext, 257 | ImageFetcher.HTTP_CACHE_DIR), key + ".0"); 258 | boolean httpFileExists = httpFile.exists(); 259 | if (!httpFileExists) { 260 | NativeUtil.compressBitmap(bitmap, 261 | ImageManageUtil.IMAGE_ME_SAVE_QUALITY, 262 | httpFile.getAbsolutePath(), true); 263 | // bitmap.compress(mCacheParams.compressFormat, 264 | // mCacheParams.compressQuality, out); 265 | } 266 | FileInputStream fis = new FileInputStream(httpFile); 267 | Utils.copyStream(fis, out); 268 | fis.close(); 269 | if (!httpFileExists) { 270 | httpFile.delete(); 271 | } 272 | editor.commit(); 273 | out.close(); 274 | } 275 | } else { 276 | snapshot.getInputStream(DISK_CACHE_INDEX).close(); 277 | } 278 | } catch (final IOException e) { 279 | Log.e(TAG, "addBitmapToCache - " + e); 280 | } catch (Exception e) { 281 | Log.e(TAG, "addBitmapToCache - " + e); 282 | } finally { 283 | try { 284 | if (out != null) { 285 | out.close(); 286 | } 287 | } catch (IOException e) { 288 | } 289 | } 290 | } 291 | } 292 | } 293 | 294 | /** 295 | * Get from memory cache. 296 | * 297 | * @param data 298 | * Unique identifier for which item to get 299 | * @return The bitmap if found in cache, null otherwise 300 | */ 301 | public Bitmap getBitmapFromMemCache(String data) { 302 | if (mMemoryCache != null) { 303 | final Bitmap memBitmap = mMemoryCache.get(data); 304 | if (memBitmap != null) { 305 | if (BuildConfig.DEBUG) { 306 | Log.d(TAG, "Memory cache hit"); 307 | } 308 | return memBitmap; 309 | } 310 | } 311 | return null; 312 | } 313 | 314 | /** 315 | * Get from disk cache. 316 | * 317 | * @param data 318 | * Unique identifier for which item to get 319 | * @return The bitmap if found in cache, null otherwise 320 | */ 321 | public Bitmap getBitmapFromDiskCache(String data) { 322 | final String key = hashKeyForDisk(data); 323 | synchronized (mDiskCacheLock) { 324 | while (mDiskCacheStarting) { 325 | try { 326 | mDiskCacheLock.wait(); 327 | } catch (InterruptedException e) { 328 | } 329 | } 330 | if (mDiskLruCache != null) { 331 | InputStream inputStream = null; 332 | try { 333 | final DiskLruCache.Snapshot snapshot = mDiskLruCache 334 | .get(key); 335 | if (snapshot != null) { 336 | if (BuildConfig.DEBUG) { 337 | Log.d(TAG, "Disk cache hit"); 338 | } 339 | inputStream = snapshot.getInputStream(DISK_CACHE_INDEX); 340 | if (inputStream != null) { 341 | BitmapFactory.Options options = new BitmapFactory.Options(); 342 | // Learned from Ig 343 | byte[] bytes = Utils.readBytes(inputStream); 344 | options.inPurgeable = true; 345 | options.inInputShareable = false; 346 | 347 | Bitmap bitmap = BitmapFactory.decodeByteArray( 348 | bytes, 0, bytes.length, options); 349 | return bitmap; 350 | } 351 | } 352 | } catch (final IOException e) { 353 | Log.e(TAG, "getBitmapFromDiskCache - " + e); 354 | } finally { 355 | try { 356 | if (inputStream != null) { 357 | inputStream.close(); 358 | } 359 | } catch (IOException e) { 360 | } 361 | } 362 | } 363 | return null; 364 | } 365 | } 366 | 367 | /** 368 | * Clears both the memory and disk cache associated with this ImageCache 369 | * object. Note that this includes disk access so this should not be 370 | * executed on the main/UI thread. 371 | */ 372 | public void clearCache() { 373 | if (mMemoryCache != null) { 374 | mMemoryCache.evictAll(); 375 | if (BuildConfig.DEBUG) { 376 | Log.d(TAG, "Memory cache cleared"); 377 | } 378 | } 379 | 380 | synchronized (mDiskCacheLock) { 381 | mDiskCacheStarting = true; 382 | if (mDiskLruCache != null && !mDiskLruCache.isClosed()) { 383 | try { 384 | mDiskLruCache.delete(); 385 | if (BuildConfig.DEBUG) { 386 | Log.d(TAG, "Disk cache cleared"); 387 | } 388 | } catch (IOException e) { 389 | Log.e(TAG, "clearCache - " + e); 390 | } 391 | mDiskLruCache = null; 392 | // --checkJournal 393 | initDiskCache(true); 394 | } 395 | } 396 | } 397 | 398 | public void clearMemoryCache() { 399 | if (mMemoryCache != null) { 400 | mMemoryCache.evictAll(); 401 | if (BuildConfig.DEBUG) { 402 | Log.d(TAG, "Memory cache cleared"); 403 | } 404 | } 405 | } 406 | 407 | /** 408 | * Flushes the disk cache associated with this ImageCache object. Note that 409 | * this includes disk access so this should not be executed on the main/UI 410 | * thread. 411 | */ 412 | public void flush() { 413 | synchronized (mDiskCacheLock) { 414 | if (mDiskLruCache != null) { 415 | try { 416 | mDiskLruCache.flush(); 417 | if (BuildConfig.DEBUG) { 418 | Log.d(TAG, "Disk cache flushed"); 419 | } 420 | } catch (IOException e) { 421 | Log.e(TAG, "flush - " + e); 422 | } 423 | } 424 | } 425 | } 426 | 427 | /** 428 | * Closes the disk cache associated with this ImageCache object. Note that 429 | * this includes disk access so this should not be executed on the main/UI 430 | * thread. 431 | */ 432 | public void close() { 433 | synchronized (mDiskCacheLock) { 434 | if (mDiskLruCache != null) { 435 | try { 436 | if (!mDiskLruCache.isClosed()) { 437 | mDiskLruCache.close(); 438 | mDiskLruCache = null; 439 | if (BuildConfig.DEBUG) { 440 | Log.d(TAG, "Disk cache closed"); 441 | } 442 | } 443 | } catch (IOException e) { 444 | Log.e(TAG, "close - " + e); 445 | } 446 | } 447 | } 448 | } 449 | 450 | /** 451 | * A holder class that contains cache parameters. 452 | */ 453 | public static class ImageCacheParams { 454 | public int memCacheSize = DEFAULT_MEM_CACHE_SIZE; 455 | public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE; 456 | public File diskCacheDir; 457 | public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT; 458 | public int compressQuality = DEFAULT_COMPRESS_QUALITY; 459 | public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED; 460 | public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED; 461 | public boolean clearDiskCacheOnStart = DEFAULT_CLEAR_DISK_CACHE_ON_START; 462 | public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE; 463 | 464 | public ImageCacheParams(Context context, String uniqueName) { 465 | diskCacheDir = getDiskCacheDir(context, uniqueName); 466 | } 467 | 468 | public ImageCacheParams(File diskCacheDir) { 469 | this.diskCacheDir = diskCacheDir; 470 | } 471 | 472 | /** 473 | * Sets the memory cache size based on a percentage of the device memory 474 | * class. Eg. setting percent to 0.2 would set the memory cache to one 475 | * fifth of the device memory class. Throws 476 | * {@link IllegalArgumentException} if percent is < 0.05 or > .8. 477 | * 478 | * This value should be chosen carefully based on a number of factors 479 | * Refer to the corresponding Android Training class for more 480 | * discussion: http://developer.android.com/training/displaying-bitmaps/ 481 | * 482 | * @param context 483 | * Context to use to fetch memory class 484 | * @param percent 485 | * Percent of memory class to use to size memory cache 486 | */ 487 | public void setMemCacheSizePercent(Context context, float percent) { 488 | if (percent < 0.05f || percent > 0.8f) { 489 | throw new IllegalArgumentException( 490 | "setMemCacheSizePercent - percent must be " 491 | + "between 0.05 and 0.8 (inclusive)"); 492 | } 493 | memCacheSize = Math.round(percent * getMemoryClass(context) * 1024 494 | * 1024); 495 | } 496 | 497 | private static int getMemoryClass(Context context) { 498 | return ((ActivityManager) context 499 | .getSystemService(Context.ACTIVITY_SERVICE)) 500 | .getMemoryClass(); 501 | } 502 | } 503 | 504 | /** 505 | * Get a usable cache directory (external if available, internal otherwise). 506 | * 507 | * @param context 508 | * The context to use 509 | * @param uniqueName 510 | * A unique directory name to append to the cache dir 511 | * @return The cache dir 512 | */ 513 | public static File getDiskCacheDir(Context context, String uniqueName) { 514 | // Check if media is mounted or storage is built-in, if so, try and use 515 | // external cache dir 516 | // otherwise use internal cache dir 517 | final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment 518 | .getExternalStorageState()) || !isExternalStorageRemovable() ? getExternalCacheDir( 519 | context).getPath() 520 | : context.getCacheDir().getPath(); 521 | 522 | return new File(cachePath + File.separator + uniqueName); 523 | } 524 | 525 | /** 526 | * A hashing method that changes a string (like a URL) into a hash suitable 527 | * for using as a disk filename. 528 | */ 529 | public static String hashKeyForDisk(String key) { 530 | String cacheKey; 531 | try { 532 | final MessageDigest mDigest = MessageDigest.getInstance("MD5"); 533 | mDigest.update(key.getBytes()); 534 | cacheKey = bytesToHexString(mDigest.digest()); 535 | } catch (NoSuchAlgorithmException e) { 536 | cacheKey = String.valueOf(key.hashCode()); 537 | } 538 | return cacheKey; 539 | } 540 | 541 | private static String bytesToHexString(byte[] bytes) { 542 | // http://stackoverflow.com/questions/332079 543 | StringBuilder sb = new StringBuilder(); 544 | for (int i = 0; i < bytes.length; i++) { 545 | String hex = Integer.toHexString(0xFF & bytes[i]); 546 | if (hex.length() == 1) { 547 | sb.append('0'); 548 | } 549 | sb.append(hex); 550 | } 551 | return sb.toString(); 552 | } 553 | 554 | /** 555 | * Get the size in bytes of a bitmap. 556 | * 557 | * @param bitmap 558 | * @return size in bytes 559 | */ 560 | @TargetApi(12) 561 | public static int getBitmapSize(Bitmap bitmap) { 562 | if (Utils.hasHoneycombMR1()) { 563 | return bitmap.getByteCount(); 564 | } 565 | // Pre HC-MR1 566 | return bitmap.getRowBytes() * bitmap.getHeight(); 567 | } 568 | 569 | /** 570 | * Check if external storage is built-in or removable. 571 | * 572 | * @return True if external storage is removable (like an SD card), false 573 | * otherwise. 574 | */ 575 | @TargetApi(9) 576 | public static boolean isExternalStorageRemovable() { 577 | if (Utils.hasGingerbread()) { 578 | return Environment.isExternalStorageRemovable(); 579 | } 580 | return true; 581 | } 582 | 583 | /** 584 | * Get the external app cache directory. 585 | * 586 | * @param context 587 | * The context to use 588 | * @return The external cache dir 589 | */ 590 | @TargetApi(8) 591 | public static File getExternalCacheDir(Context context) { 592 | if (Utils.hasFroyo()) { 593 | return context.getExternalCacheDir(); 594 | } 595 | 596 | // Before Froyo we need to construct the external cache dir ourselves 597 | final String cacheDir = "/Android/data/" + context.getPackageName() 598 | + "/cache/"; 599 | return new File(Environment.getExternalStorageDirectory().getPath() 600 | + cacheDir); 601 | } 602 | 603 | /** 604 | * Check how much usable space is available at a given path. 605 | * 606 | * @param path 607 | * The path to check 608 | * @return The space available in bytes 609 | */ 610 | @TargetApi(9) 611 | public static long getUsableSpace(File path) { 612 | if (Utils.hasGingerbread()) { 613 | return path.getUsableSpace(); 614 | } 615 | final StatFs stats = new StatFs(path.getPath()); 616 | return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks(); 617 | } 618 | 619 | /** 620 | * Locate an existing instance of this Fragment or if not found, create and 621 | * add it using FragmentManager. 622 | * 623 | * @param fm 624 | * The FragmentManager manager to use. 625 | * @return The existing instance of the Fragment or the new instance if just 626 | * created. 627 | */ 628 | public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) { 629 | // Check to see if we have retained the worker fragment. 630 | RetainFragment mRetainFragment = (RetainFragment) fm 631 | .findFragmentByTag(TAG); 632 | 633 | // If not retained (or first time running), we need to create and add 634 | // it. 635 | if (mRetainFragment == null) { 636 | mRetainFragment = new RetainFragment(); 637 | fm.beginTransaction().add(mRetainFragment, TAG) 638 | .commitAllowingStateLoss(); 639 | } 640 | 641 | return mRetainFragment; 642 | } 643 | 644 | /** 645 | * A simple non-UI Fragment that stores a single Object and is retained over 646 | * configuration changes. It will be used to retain the ImageCache object. 647 | */ 648 | public static class RetainFragment extends Fragment { 649 | private Object mObject; 650 | 651 | /** 652 | * Empty constructor as per the Fragment documentation 653 | */ 654 | public RetainFragment() { 655 | } 656 | 657 | @Override 658 | public void onCreate(Bundle savedInstanceState) { 659 | super.onCreate(savedInstanceState); 660 | 661 | // Make sure this Fragment is retained over a configuration change 662 | setRetainInstance(true); 663 | } 664 | 665 | /** 666 | * Store a single object in this Fragment. 667 | * 668 | * @param object 669 | * The object to store 670 | */ 671 | public void setObject(Object object) { 672 | mObject = object; 673 | } 674 | 675 | /** 676 | * Get the stored object. 677 | * 678 | * @return The stored object 679 | */ 680 | public Object getObject() { 681 | return mObject; 682 | } 683 | } 684 | 685 | } 686 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/ImageFetcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright (C) 2012 The Android Open Source Project 19 | * 20 | * Licensed under the Apache License, Version 2.0 (the "License"); 21 | * you may not use this file except in compliance with the License. 22 | * You may obtain a copy of the License at 23 | * 24 | * http://www.apache.org/licenses/LICENSE-2.0 25 | * 26 | * Unless required by applicable law or agreed to in writing, software 27 | * distributed under the License is distributed on an "AS IS" BASIS, 28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | * See the License for the specific language governing permissions and 30 | * limitations under the License. 31 | */ 32 | 33 | package net.bither.image.cache; 34 | 35 | import java.io.BufferedInputStream; 36 | import java.io.BufferedOutputStream; 37 | import java.io.File; 38 | import java.io.FileDescriptor; 39 | import java.io.FileInputStream; 40 | import java.io.IOException; 41 | import java.io.OutputStream; 42 | import java.net.HttpURLConnection; 43 | import java.net.URL; 44 | 45 | import android.content.Context; 46 | import android.graphics.Bitmap; 47 | import android.net.ConnectivityManager; 48 | import android.net.NetworkInfo; 49 | import android.os.Build; 50 | import android.util.Log; 51 | 52 | import net.bither.image.BuildConfig; 53 | import net.bither.image.exception.Http404Exception; 54 | import net.bither.image.http.HttpSetting; 55 | 56 | 57 | /** 58 | * A simple subclass of {@link ImageResizer} that fetches and resizes images 59 | * fetched from a URL. 60 | */ 61 | public class ImageFetcher extends ImageResizer { 62 | private static final String TAG = "ImageFetcher"; 63 | private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB 64 | public static final String HTTP_CACHE_DIR = "http"; 65 | private static final int IO_BUFFER_SIZE = 8 * 1024; 66 | 67 | private DiskLruCache mHttpDiskCache; 68 | private File mHttpCacheDir; 69 | private boolean mHttpDiskCacheStarting = true; 70 | private final Object mHttpDiskCacheLock = new Object(); 71 | private static final int DISK_CACHE_INDEX = 0; 72 | 73 | /** 74 | * Initialize providing a target image width and height for the processing 75 | * images. 76 | * 77 | * @param context 78 | * @param imageWidth 79 | * @param imageHeight 80 | */ 81 | public ImageFetcher(Context context, int imageWidth, int imageHeight) { 82 | super(context, imageWidth, imageHeight); 83 | init(context); 84 | } 85 | 86 | /** 87 | * Initialize providing a single target image size (used for both width and 88 | * height); 89 | * 90 | * @param context 91 | * @param imageSize 92 | */ 93 | public ImageFetcher(Context context, int imageSize) { 94 | super(context, imageSize); 95 | init(context); 96 | } 97 | 98 | private void init(Context context) { 99 | checkConnection(context); 100 | mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR); 101 | } 102 | 103 | @Override 104 | protected void initDiskCacheInternal(boolean checkJournal) { 105 | // -checkJournal 106 | super.initDiskCacheInternal(checkJournal); 107 | initHttpDiskCache(checkJournal); 108 | } 109 | 110 | private void initHttpDiskCache(boolean checkJournal) { 111 | // -checkJournal 112 | if (!mHttpCacheDir.exists()) { 113 | mHttpCacheDir.mkdirs(); 114 | } 115 | synchronized (mHttpDiskCacheLock) { 116 | if (ImageCache.getUsableSpace(mHttpCacheDir) > 0.5 * 1024 * 1024) { 117 | try { 118 | // -checkJournal 119 | mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, 120 | HTTP_CACHE_SIZE, checkJournal); 121 | 122 | if (BuildConfig.DEBUG) { 123 | Log.d(TAG, "HTTP cache initialized"); 124 | } 125 | } catch (IOException e) { 126 | mHttpDiskCache = null; 127 | } 128 | } 129 | mHttpDiskCacheStarting = false; 130 | mHttpDiskCacheLock.notifyAll(); 131 | } 132 | } 133 | 134 | @Override 135 | protected void clearCacheInternal() { 136 | super.clearCacheInternal(); 137 | synchronized (mHttpDiskCacheLock) { 138 | if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) { 139 | try { 140 | mHttpDiskCache.delete(); 141 | if (BuildConfig.DEBUG) { 142 | Log.d(TAG, "HTTP cache cleared"); 143 | } 144 | } catch (IOException e) { 145 | Log.e(TAG, "clearCacheInternal - " + e); 146 | } 147 | mHttpDiskCache = null; 148 | mHttpDiskCacheStarting = true; 149 | // -checkJournal 150 | initHttpDiskCache(true); 151 | } 152 | } 153 | } 154 | 155 | @Override 156 | protected void flushCacheInternal() { 157 | super.flushCacheInternal(); 158 | synchronized (mHttpDiskCacheLock) { 159 | if (mHttpDiskCache != null) { 160 | try { 161 | mHttpDiskCache.flush(); 162 | if (BuildConfig.DEBUG) { 163 | Log.d(TAG, "HTTP cache flushed"); 164 | } 165 | } catch (IOException e) { 166 | Log.e(TAG, "flush - " + e); 167 | } 168 | } 169 | } 170 | } 171 | 172 | @Override 173 | protected void closeCacheInternal() { 174 | super.closeCacheInternal(); 175 | synchronized (mHttpDiskCacheLock) { 176 | if (mHttpDiskCache != null) { 177 | try { 178 | if (!mHttpDiskCache.isClosed()) { 179 | mHttpDiskCache.close(); 180 | mHttpDiskCache = null; 181 | if (BuildConfig.DEBUG) { 182 | Log.d(TAG, "HTTP cache closed"); 183 | } 184 | } 185 | } catch (IOException e) { 186 | Log.e(TAG, "closeCacheInternal - " + e); 187 | } 188 | } 189 | } 190 | } 191 | 192 | /** 193 | * Simple network connection check. 194 | * 195 | * @param context 196 | */ 197 | private void checkConnection(Context context) { 198 | final ConnectivityManager cm = (ConnectivityManager) context 199 | .getSystemService(Context.CONNECTIVITY_SERVICE); 200 | final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 201 | if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) { 202 | // Toast.makeText(context, R.string.network_or_connection_error, 203 | // Toast.LENGTH_LONG).show(); 204 | Log.e(TAG, "checkConnection - no connection found"); 205 | } 206 | } 207 | 208 | /** 209 | * The main process method, which will be called by the ImageWorker in the 210 | * AsyncTask background thread. 211 | * 212 | * @param data 213 | * The data to load the bitmap, in this case, a regular http URL 214 | * @return The downloaded and resized bitmap 215 | * @throws Http404Exception 216 | */ 217 | private Bitmap processBitmap(String data, 218 | AsyncTask bitmapWorkerTask) 219 | throws Http404Exception { 220 | 221 | if (BuildConfig.DEBUG) { 222 | Log.d(TAG, "processBitmap - " + data); 223 | } 224 | 225 | final String key = ImageCache.hashKeyForDisk(data); 226 | FileDescriptor fileDescriptor = null; 227 | FileInputStream fileInputStream = null; 228 | DiskLruCache.Snapshot snapshot; 229 | synchronized (mHttpDiskCacheLock) { 230 | // Wait for disk cache to initialize 231 | while (mHttpDiskCacheStarting) { 232 | try { 233 | mHttpDiskCacheLock.wait(); 234 | } catch (InterruptedException e) { 235 | } 236 | } 237 | 238 | if (mHttpDiskCache != null) { 239 | try { 240 | snapshot = mHttpDiskCache.get(key); 241 | if (snapshot == null) { 242 | if (BuildConfig.DEBUG) { 243 | Log.d(TAG, 244 | "processBitmap, not found in http cache, downloading..."); 245 | } 246 | DiskLruCache.Editor editor = mHttpDiskCache.edit(key); 247 | if (editor != null) { 248 | boolean downloadSuccess = false; 249 | try { 250 | downloadSuccess = downloadUrlToStream( 251 | data, 252 | editor.newOutputStream(DISK_CACHE_INDEX), 253 | bitmapWorkerTask); 254 | 255 | } catch (Http404Exception e) {// catch Http404 256 | editor.abort(); 257 | throw e; // --NoImageAvailable 258 | } 259 | if (downloadSuccess) { 260 | editor.commit(); 261 | } else { 262 | editor.abort(); 263 | } 264 | 265 | } 266 | snapshot = mHttpDiskCache.get(key); 267 | } 268 | if (snapshot != null) { 269 | fileInputStream = (FileInputStream) snapshot 270 | .getInputStream(DISK_CACHE_INDEX); 271 | fileDescriptor = fileInputStream.getFD(); 272 | } 273 | } catch (IOException e) { 274 | Log.e(TAG, "processBitmap - " + e); 275 | } catch (IllegalStateException e) { 276 | Log.e(TAG, "processBitmap - " + e); 277 | } finally { 278 | if (fileDescriptor == null && fileInputStream != null) { 279 | try { 280 | fileInputStream.close(); 281 | } catch (IOException e) { 282 | } 283 | } 284 | } 285 | } 286 | } 287 | 288 | Bitmap bitmap = null; 289 | if (fileDescriptor != null) { 290 | bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, 291 | mImageWidth, mImageHeight); 292 | } 293 | if (fileInputStream != null) { 294 | try { 295 | fileInputStream.close(); 296 | } catch (IOException e) { 297 | } 298 | } 299 | return bitmap; 300 | } 301 | 302 | @Override 303 | protected Bitmap processBitmap(Object data, 304 | AsyncTask bitmapWorkerTask) 305 | throws Http404Exception { 306 | return processBitmap(String.valueOf(data), bitmapWorkerTask); 307 | } 308 | 309 | /** 310 | * Download a bitmap from a URL and write the content to an output stream. 311 | * 312 | * @param urlString 313 | * The URL to fetch 314 | * @return true if successful, false otherwise 315 | * @throws Http404Exception 316 | */ 317 | public boolean downloadUrlToStream(String urlString, 318 | OutputStream outputStream, 319 | AsyncTask bitmapWorkerTask) 320 | throws Http404Exception {// throws Http404Exception 321 | // --NoImageAvailable 322 | 323 | disableConnectionReuseIfNecessary(); 324 | HttpURLConnection urlConnection = null; 325 | BufferedOutputStream out = null; 326 | BufferedInputStream in = null; 327 | bitmapWorkerTask.publishProgress(new FileDowloadProgressListener.ProgressValue( 328 | FileDowloadProgressListener.DownloadType.PREPARE, 0, 0)); 329 | int count = 0; 330 | try { 331 | final URL url = new URL(urlString); 332 | urlConnection = (HttpURLConnection) url.openConnection(); 333 | urlConnection 334 | .setConnectTimeout(HttpSetting.HTTP_CONNECTION_TIMEOUT); 335 | urlConnection.setReadTimeout(HttpSetting.HTTP_SO_TIMEOUT); 336 | int httpCode = urlConnection.getResponseCode(); 337 | if (httpCode == 404) {// to decide HttpCode 404 --NoImageAvailable 338 | bitmapWorkerTask.publishProgress(new FileDowloadProgressListener.ProgressValue( 339 | FileDowloadProgressListener.DownloadType.END, count, 0)); 340 | throw new Http404Exception("404"); 341 | } 342 | bitmapWorkerTask.publishProgress(new FileDowloadProgressListener.ProgressValue( 343 | FileDowloadProgressListener.DownloadType.BEGIN, urlConnection.getContentLength(), 0)); 344 | in = new BufferedInputStream(urlConnection.getInputStream(), 345 | IO_BUFFER_SIZE); 346 | out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); 347 | int b; 348 | while ((b = in.read()) != -1) { 349 | out.write(b); 350 | count++; 351 | if (count % 32 == 0) { 352 | bitmapWorkerTask.publishProgress(new FileDowloadProgressListener.ProgressValue( 353 | FileDowloadProgressListener.DownloadType.DOWNLOING, urlConnection 354 | .getContentLength(), count)); 355 | } 356 | } 357 | bitmapWorkerTask.publishProgress(new FileDowloadProgressListener.ProgressValue( 358 | FileDowloadProgressListener.DownloadType.END, urlConnection.getContentLength(), count)); 359 | return true; 360 | } catch (final IOException e) { 361 | bitmapWorkerTask 362 | .publishProgress(new FileDowloadProgressListener.ProgressValue(FileDowloadProgressListener.DownloadType.ERROR, 363 | urlConnection.getContentLength(), count)); 364 | Log.e(TAG, "Error in downloadBitmap - " + e); 365 | } finally { 366 | if (urlConnection != null) { 367 | urlConnection.disconnect(); 368 | } 369 | try { 370 | if (out != null) { 371 | out.close(); 372 | } 373 | if (in != null) { 374 | in.close(); 375 | } 376 | } catch (final IOException e) { 377 | } 378 | } 379 | return false; 380 | } 381 | 382 | /** 383 | * Workaround for bug pre-Froyo, see here for more info: 384 | * http://android-developers.blogspot.com/2011/09/androids-http-clients.html 385 | */ 386 | public static void disableConnectionReuseIfNecessary() { 387 | // HTTP connection reuse which was buggy pre-froyo 388 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { 389 | System.setProperty("http.keepAlive", "false"); 390 | } 391 | } 392 | } 393 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/ImageManageUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.cache; 18 | 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileNotFoundException; 22 | import java.io.IOException; 23 | 24 | import android.graphics.Bitmap; 25 | import android.graphics.Bitmap.Config; 26 | import android.graphics.BitmapFactory; 27 | import android.graphics.Canvas; 28 | import android.graphics.Matrix; 29 | import android.graphics.Paint; 30 | import android.graphics.PorterDuff.Mode; 31 | import android.graphics.PorterDuffXfermode; 32 | import android.graphics.Rect; 33 | import android.graphics.RectF; 34 | import android.view.View; 35 | import android.view.Window; 36 | 37 | import net.bither.image.BitherApplication; 38 | 39 | public class ImageManageUtil { 40 | private static final int IMAGE_AVATAR_WIDTH_DP = 36; 41 | 42 | public static final int IMAGE_WIDTH = 612; 43 | public static final int MIDDLE_IMAGE_WIDTH = 305; 44 | public static final int SMALL_IMAGE_WIDTH = 150; 45 | public static final int IMAGE_SAVE_WIDTH = IMAGE_WIDTH * 2; 46 | public static final int IMAGE_ME_SAVE_QUALITY = 80; 47 | public static final int IMAGE_PICTURES_SAVE_QUALITY = 95; 48 | public static int PIIMAGE_MIDLLE_SIZE = getScreenWidth() - dip2pix(10); 49 | 50 | 51 | private static Bitmap getRoundCornerBitmapFromRes(int id) { 52 | Bitmap bit = BitmapFactory.decodeResource( 53 | BitherApplication.mContext.getResources(), id); 54 | bit = getRoundCornerBitmap(bit); 55 | return bit; 56 | } 57 | 58 | public static Bitmap getBitmapFromAsset(String path) { 59 | try { 60 | return BitmapFactory.decodeStream(BitherApplication.mContext 61 | .getAssets().open(path)); 62 | } catch (IOException e) { 63 | e.printStackTrace(); 64 | return null; 65 | } 66 | } 67 | 68 | 69 | public static Bitmap getNoImageAvailableBitmap(int width, int height) { 70 | Bitmap bitmap = getBitmapFromAsset("Image/no_image_available.jpg"); 71 | return getThumbnailBitmap(bitmap, width, height, true); 72 | } 73 | 74 | public static Bitmap getImageRemovedBitmap(int width, int height) { 75 | Bitmap bitmap = getBitmapFromAsset("Image/image_removed.jpg"); 76 | return getThumbnailBitmap(bitmap, width, height, true); 77 | } 78 | 79 | 80 | public static Bitmap getImageRemovedSmallBitmap(int width, int height) { 81 | Bitmap bitmap = getBitmapFromAsset("Image/image_removed_small.jpg"); 82 | return getThumbnailBitmap(bitmap, width, height, true); 83 | } 84 | 85 | public static final int dip2pix(float dip) { 86 | final float scale = BitherApplication.mContext.getResources() 87 | .getDisplayMetrics().density; 88 | return (int) (dip * scale + 0.5f); 89 | } 90 | 91 | public static final int getSmallImageCacheWidth() { 92 | return Math.min((getScreenWidth() - dip2pix(9) * 2) / 3, 93 | SMALL_IMAGE_WIDTH); 94 | } 95 | 96 | 97 | public static int getScreenWidth() { 98 | return BitherApplication.mContext.getResources().getDisplayMetrics().widthPixels; 99 | } 100 | 101 | public static int getScreenHeight() { 102 | return BitherApplication.mContext.getResources().getDisplayMetrics().heightPixels; 103 | } 104 | 105 | // operate bitmap 106 | 107 | public static Bitmap getThumbnailBitmap(Bitmap source, int width, 108 | int height, boolean needRecycleSource) { 109 | if (source == null) 110 | return source; 111 | if (Math.min(source.getWidth(), source.getHeight()) > Math.min(width, 112 | height)) { 113 | Bitmap result = null; 114 | if (needRecycleSource) { 115 | result = extractThumbnail(source, width, height, 116 | OPTIONS_RECYCLE_INPUT); 117 | } else { 118 | result = extractThumbnail(source, width, height); 119 | } 120 | return result; 121 | } else { 122 | return source; 123 | } 124 | } 125 | 126 | public static Bitmap getMatrixBitmap(Bitmap bm, int w, int h, 127 | boolean needRecycleSource) { 128 | int width = bm.getWidth(); 129 | int height = bm.getHeight(); 130 | boolean isCompress = (width > w && height > h) && (w != 0 && h != 0) 131 | && (w != width || h != height); 132 | if (isCompress) { 133 | float scaleWidth = ((float) w) / width; 134 | float scaleHeight = ((float) h) / height; 135 | float scale = Math.max(scaleWidth, scaleHeight); 136 | Matrix matrix = new Matrix(); 137 | matrix.postScale(scale, scale); 138 | Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, width, height, 139 | matrix, true); 140 | 141 | if (needRecycleSource && bm != null && bm != bitmap) { 142 | bm.recycle(); 143 | } 144 | return bitmap; 145 | } else { 146 | return bm; 147 | } 148 | } 149 | 150 | public static Bitmap getMatrixBitmap(File file, int w, int h) { 151 | try { 152 | 153 | if (file == null || !file.exists()) { 154 | return null; 155 | } 156 | Bitmap bm = getBitmap(file, w, h); 157 | Bitmap result = getMatrixBitmap(bm, w, h, true); 158 | return result; 159 | 160 | } catch (Exception e) { 161 | e.printStackTrace(); 162 | return null; 163 | 164 | } finally { 165 | 166 | } 167 | } 168 | 169 | public static Bitmap getBitmap(File file, int width, int height) { 170 | try { 171 | final Bitmap bm; 172 | 173 | BitmapFactory.Options opts = new BitmapFactory.Options(); 174 | opts.inJustDecodeBounds = true; 175 | if (file == null || !file.exists()) { 176 | return null; 177 | } else if (file.length() == 0) { 178 | file.delete(); 179 | return null; 180 | } 181 | FileInputStream fileInputStream; 182 | 183 | fileInputStream = new FileInputStream(file); 184 | 185 | BitmapFactory.decodeFile(file.getAbsolutePath(), opts); 186 | 187 | int be = 1; 188 | if (height != 0) { 189 | be = (int) (opts.outHeight / (float) width); 190 | if (be <= 0) 191 | be = 1; 192 | } 193 | 194 | opts.inSampleSize = be; 195 | opts.inJustDecodeBounds = false; 196 | opts.inPreferredConfig = Config.ARGB_8888; 197 | 198 | bm = BitmapFactory.decodeStream(fileInputStream, null, opts); 199 | fileInputStream.close(); 200 | return bm; 201 | 202 | } catch (FileNotFoundException e) { 203 | e.printStackTrace(); 204 | return null; 205 | } catch (IOException e) { 206 | e.printStackTrace(); 207 | return null; 208 | } 209 | 210 | } 211 | 212 | 213 | public static Bitmap getRotationOfHorizontal(Bitmap bitmap) { 214 | Matrix matrix = new Matrix(); 215 | matrix.postScale(-1, 1); 216 | Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), 217 | bitmap.getHeight(), matrix, true); 218 | if (result != bitmap) { 219 | bitmap.recycle(); 220 | } 221 | return result; 222 | 223 | } 224 | 225 | 226 | public static final Bitmap getRoundCornerBitmap(Bitmap bitmap, float roundPx) { 227 | if (bitmap == null) 228 | return bitmap; 229 | Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), 230 | bitmap.getHeight(), Config.ARGB_8888); 231 | Canvas canvas = new Canvas(output); 232 | canvas.drawARGB(0, 0, 0, 0); 233 | final int color = 0xff010101; 234 | final Paint paint = new Paint(); 235 | final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 236 | final RectF rectF = new RectF(rect); 237 | paint.setAntiAlias(true); 238 | paint.setColor(color); 239 | canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 240 | paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 241 | canvas.drawBitmap(bitmap, rect, rect, paint); 242 | bitmap.recycle(); 243 | return output; 244 | } 245 | 246 | 247 | public static Bitmap getSquareBitmapFromOriBitmap(byte[] bytes, 248 | int Orientation) { 249 | Bitmap bit = getBitmapNearestSize(bytes, 250 | IMAGE_SAVE_WIDTH); 251 | int oriSize = Math.min(bit.getWidth(), bit.getHeight()); 252 | int targetSize = Math.min(oriSize, IMAGE_SAVE_WIDTH); 253 | Bitmap bmp = Bitmap.createBitmap(targetSize, targetSize, 254 | Config.ARGB_8888); 255 | Canvas canvas = new Canvas(bmp); 256 | canvas.save(); 257 | canvas.rotate(Orientation); 258 | Rect srcRect; 259 | if ((Orientation % 360) < 180) { 260 | srcRect = new Rect(0, 0, oriSize, oriSize); 261 | } else { 262 | srcRect = new Rect(bit.getWidth() - oriSize, bit.getHeight() 263 | - oriSize, bit.getWidth(), bit.getHeight()); 264 | } 265 | Rect destRect = new Rect(0, 0, bmp.getWidth(), bmp.getHeight()); 266 | Matrix matrix = new Matrix(); 267 | matrix.postRotate(-Orientation); 268 | RectF destRectF = new RectF(destRect); 269 | matrix.mapRect(destRectF); 270 | canvas.drawBitmap(bit, srcRect, destRectF, null); 271 | bit.recycle(); 272 | canvas.restore(); 273 | return bmp; 274 | } 275 | 276 | private static Bitmap getBitmapNearestSize(byte[] bytes, int size) { 277 | try { 278 | BitmapFactory.Options opts = new BitmapFactory.Options(); 279 | opts.inJustDecodeBounds = true; 280 | BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts); 281 | int bmpSize = Math.min(opts.outHeight, opts.outWidth); 282 | opts.inSampleSize = getSampleSize(bmpSize, size); 283 | opts.inJustDecodeBounds = false; 284 | opts.inPurgeable = true; 285 | opts.inInputShareable = false; 286 | opts.inPreferredConfig = Config.ARGB_8888; 287 | return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts); 288 | } catch (Exception e) { 289 | e.printStackTrace(); 290 | return null; 291 | } 292 | } 293 | 294 | private static int getSampleSize(int fileSize, int targetSize) { 295 | int sampleSize = 1; 296 | if (fileSize > targetSize * 2) { 297 | int sampleLessThanSize = 0; 298 | do { 299 | sampleLessThanSize++; 300 | } while (fileSize / sampleLessThanSize > targetSize); 301 | 302 | for (int i = 1; i <= sampleLessThanSize; i++) { 303 | if (Math.abs(fileSize / i - targetSize) <= Math.abs(fileSize 304 | / sampleSize - targetSize)) { 305 | sampleSize = i; 306 | } 307 | } 308 | } else { 309 | if (fileSize <= targetSize) { 310 | sampleSize = 1; 311 | } else { 312 | sampleSize = 2; 313 | } 314 | } 315 | return sampleSize; 316 | } 317 | 318 | public static Bitmap getBitmapNearestSize(String fileName, int size) { 319 | try { 320 | File file = new File(fileName); 321 | if (file == null || !file.exists()) { 322 | return null; 323 | } else if (file.length() == 0) { 324 | file.delete(); 325 | return null; 326 | } 327 | BitmapFactory.Options opts = new BitmapFactory.Options(); 328 | opts.inJustDecodeBounds = true; 329 | BitmapFactory.decodeFile(fileName, opts); 330 | int sampleSize = getSampleSize( 331 | Math.min(opts.outHeight, opts.outWidth), size); 332 | opts.inSampleSize = sampleSize; 333 | opts.inJustDecodeBounds = false; 334 | opts.inPurgeable = true; 335 | opts.inInputShareable = false; 336 | opts.inPreferredConfig = Config.ARGB_8888; 337 | Bitmap bit = BitmapFactory.decodeFile(fileName, opts); 338 | return bit; 339 | } catch (Exception e) { 340 | e.printStackTrace(); 341 | return null; 342 | } 343 | } 344 | 345 | 346 | public static Bitmap byteArrayToBitmap(byte[] bytes) { 347 | BitmapFactory.Options options = new BitmapFactory.Options(); 348 | options.inPurgeable = true; 349 | options.inInputShareable = false; 350 | return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); 351 | } 352 | 353 | 354 | public static final Bitmap getRoundCornerBitmap(Bitmap bitmap) { 355 | if (bitmap == null) 356 | return bitmap; 357 | Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), 358 | bitmap.getHeight(), Config.ARGB_8888); 359 | Canvas canvas = new Canvas(output); 360 | canvas.drawARGB(0, 0, 0, 0); 361 | float roundPx; 362 | final int color = 0xff010101; 363 | final Paint paint = new Paint(); 364 | final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 365 | final RectF rectF = new RectF(rect); 366 | roundPx = 7; 367 | paint.setAntiAlias(true); 368 | paint.setColor(color); 369 | canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 370 | paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 371 | canvas.drawBitmap(bitmap, rect, rect, paint); 372 | bitmap.recycle(); 373 | return output; 374 | } 375 | 376 | 377 | public static Bitmap getBitmapFromView(View v, int width, int height) { 378 | v.measure(width, height); 379 | v.layout(0, 0, width, height); 380 | Bitmap bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888); 381 | v.draw(new Canvas(bmp)); 382 | return bmp; 383 | } 384 | 385 | 386 | public static Bitmap getBitmapFromView(View v) { 387 | Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), 388 | Config.ARGB_8888); 389 | v.draw(new Canvas(bmp)); 390 | return bmp; 391 | } 392 | 393 | 394 | public static Bitmap CorverBitmap(Bitmap base, Bitmap cover) { 395 | if (base != null && cover != null) { 396 | int width = base.getWidth(); 397 | int height = base.getHeight(); 398 | Canvas c = new Canvas(base); 399 | Paint paint = new Paint(); 400 | c.drawBitmap(cover, null, new Rect(0, 0, width, height), paint); 401 | cover.recycle(); 402 | cover = null; 403 | } 404 | return base; 405 | } 406 | 407 | 408 | public static final int getStatusBarHeight(Window window) { 409 | Rect frame = new Rect(); 410 | window.getDecorView().getWindowVisibleDisplayFrame(frame); 411 | return frame.top; 412 | } 413 | 414 | /** 415 | * Copied from android ThumbnailUtils, we don't want the 0.9 threshold 416 | *

417 | * Creates a centered bitmap of the desired size. 418 | * 419 | * @param source original bitmap source 420 | * @param width targeted width 421 | * @param height targeted height 422 | * @param options options used during thumbnail extraction 423 | */ 424 | public static Bitmap extractThumbnail(Bitmap source, int width, int height, 425 | int options) { 426 | if (source == null) { 427 | return null; 428 | } 429 | 430 | float scale; 431 | if (source.getWidth() < source.getHeight()) { 432 | scale = width / (float) source.getWidth(); 433 | } else { 434 | scale = height / (float) source.getHeight(); 435 | } 436 | Matrix matrix = new Matrix(); 437 | matrix.setScale(scale, scale); 438 | Bitmap thumbnail = transform(matrix, source, width, height, 439 | OPTIONS_SCALE_UP | options); 440 | return thumbnail; 441 | } 442 | 443 | /** 444 | * Creates a centered bitmap of the desired size. 445 | * 446 | * @param source original bitmap source 447 | * @param width targeted width 448 | * @param height targeted height 449 | */ 450 | public static Bitmap extractThumbnail(Bitmap source, int width, int height) { 451 | return extractThumbnail(source, width, height, OPTIONS_NONE); 452 | } 453 | 454 | /** 455 | * Copied from android ThumbnailUtils, we don't want the 0.9 threshold 456 | * Transform source Bitmap to targeted width and height. 457 | */ 458 | private static Bitmap transform(Matrix scaler, Bitmap source, 459 | int targetWidth, int targetHeight, int options) { 460 | boolean scaleUp = (options & OPTIONS_SCALE_UP) != 0; 461 | boolean recycle = (options & OPTIONS_RECYCLE_INPUT) != 0; 462 | 463 | int deltaX = source.getWidth() - targetWidth; 464 | int deltaY = source.getHeight() - targetHeight; 465 | if (!scaleUp && (deltaX < 0 || deltaY < 0)) { 466 | /* 467 | * In this case the bitmap is smaller, at least in one dimension, 468 | * than the target. Transform it by placing as much of the image as 469 | * possible into the target and leaving the top/bottom or left/right 470 | * (or both) black. 471 | */ 472 | Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, 473 | Config.ARGB_8888); 474 | Canvas c = new Canvas(b2); 475 | 476 | int deltaXHalf = Math.max(0, deltaX / 2); 477 | int deltaYHalf = Math.max(0, deltaY / 2); 478 | Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf 479 | + Math.min(targetWidth, source.getWidth()), deltaYHalf 480 | + Math.min(targetHeight, source.getHeight())); 481 | int dstX = (targetWidth - src.width()) / 2; 482 | int dstY = (targetHeight - src.height()) / 2; 483 | Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight 484 | - dstY); 485 | c.drawBitmap(source, src, dst, null); 486 | if (recycle) { 487 | source.recycle(); 488 | } 489 | c.setBitmap(null); 490 | return b2; 491 | } 492 | float bitmapWidthF = source.getWidth(); 493 | float bitmapHeightF = source.getHeight(); 494 | 495 | float bitmapAspect = bitmapWidthF / bitmapHeightF; 496 | float viewAspect = (float) targetWidth / targetHeight; 497 | 498 | if (bitmapAspect > viewAspect) { 499 | float scale = targetHeight / bitmapHeightF; 500 | scaler.setScale(scale, scale); 501 | } else { 502 | float scale = targetWidth / bitmapWidthF; 503 | scaler.setScale(scale, scale); 504 | } 505 | 506 | Bitmap b1; 507 | b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), 508 | source.getHeight(), scaler, true); 509 | 510 | if (recycle && b1 != source) { 511 | source.recycle(); 512 | } 513 | 514 | int dx1 = Math.max(0, b1.getWidth() - targetWidth); 515 | int dy1 = Math.max(0, b1.getHeight() - targetHeight); 516 | 517 | Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth, 518 | targetHeight); 519 | 520 | if (b2 != b1) { 521 | if (recycle || b1 != source) { 522 | b1.recycle(); 523 | } 524 | } 525 | 526 | return b2; 527 | } 528 | 529 | private static final int OPTIONS_NONE = 0x0; 530 | private static final int OPTIONS_SCALE_UP = 0x1; 531 | public static final int OPTIONS_RECYCLE_INPUT = 0x2; 532 | 533 | 534 | } 535 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/ImageResizer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright (C) 2012 The Android Open Source Project 19 | * 20 | * Licensed under the Apache License, Version 2.0 (the "License"); 21 | * you may not use this file except in compliance with the License. 22 | * You may obtain a copy of the License at 23 | * 24 | * http://www.apache.org/licenses/LICENSE-2.0 25 | * 26 | * Unless required by applicable law or agreed to in writing, software 27 | * distributed under the License is distributed on an "AS IS" BASIS, 28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | * See the License for the specific language governing permissions and 30 | * limitations under the License. 31 | */ 32 | 33 | package net.bither.image.cache; 34 | 35 | import java.io.FileDescriptor; 36 | import java.io.FileInputStream; 37 | import java.io.IOException; 38 | 39 | import android.content.Context; 40 | import android.content.res.Resources; 41 | import android.graphics.Bitmap; 42 | import android.graphics.BitmapFactory; 43 | import android.util.Log; 44 | 45 | import net.bither.image.BuildConfig; 46 | import net.bither.image.exception.Http404Exception; 47 | 48 | 49 | /** 50 | * A simple subclass of {@link ImageWorker} that resizes images from resources 51 | * given a target width and height. Useful for when the input images might be 52 | * too large to simply load directly into memory. 53 | */ 54 | public class ImageResizer extends ImageWorker { 55 | private static final String TAG = "ImageResizer"; 56 | protected int mImageWidth; 57 | protected int mImageHeight; 58 | 59 | /** 60 | * Initialize providing a single target image size (used for both width and 61 | * height); 62 | * 63 | * @param context 64 | * @param imageWidth 65 | * @param imageHeight 66 | */ 67 | public ImageResizer(Context context, int imageWidth, int imageHeight) { 68 | super(context); 69 | setImageSize(imageWidth, imageHeight); 70 | } 71 | 72 | /** 73 | * Initialize providing a single target image size (used for both width and 74 | * height); 75 | * 76 | * @param context 77 | * @param imageSize 78 | */ 79 | public ImageResizer(Context context, int imageSize) { 80 | super(context); 81 | setImageSize(imageSize); 82 | } 83 | 84 | /** 85 | * Set the target image width and height. 86 | * 87 | * @param width 88 | * @param height 89 | */ 90 | public void setImageSize(int width, int height) { 91 | mImageWidth = width; 92 | mImageHeight = height; 93 | } 94 | 95 | /** 96 | * Set the target image size (width and height will be the same). 97 | * 98 | * @param size 99 | */ 100 | public void setImageSize(int size) { 101 | setImageSize(size, size); 102 | } 103 | 104 | /** 105 | * The main processing method. This happens in a background task. In this 106 | * case we are just sampling down the bitmap and returning it from a 107 | * resource. 108 | * 109 | * @param resId 110 | * @return 111 | */ 112 | private Bitmap processBitmap(int resId) { 113 | if (BuildConfig.DEBUG) { 114 | Log.d(TAG, "processBitmap - " + resId); 115 | } 116 | return decodeSampledBitmapFromResource(mResources, resId, mImageWidth, 117 | mImageHeight); 118 | } 119 | 120 | // 121 | @Override 122 | protected Bitmap processBitmap(Object data, 123 | AsyncTask bitmapWorkerTask) 124 | throws Http404Exception { 125 | return processBitmap(Integer.parseInt(String.valueOf(data))); 126 | } 127 | 128 | /** 129 | * Decode and sample down a bitmap from resources to the requested width and 130 | * height. 131 | * 132 | * @param res 133 | * The resources object containing the image data 134 | * @param resId 135 | * The resource id of the image data 136 | * @param reqWidth 137 | * The requested width of the resulting bitmap 138 | * @param reqHeight 139 | * The requested height of the resulting bitmap 140 | * @return A bitmap sampled down from the original with the same aspect 141 | * ratio and dimensions that are equal to or greater than the 142 | * requested width and height 143 | */ 144 | public static Bitmap decodeSampledBitmapFromResource(Resources res, 145 | int resId, int reqWidth, int reqHeight) { 146 | 147 | // First decode with inJustDecodeBounds=true to check dimensions 148 | final BitmapFactory.Options options = new BitmapFactory.Options(); 149 | options.inJustDecodeBounds = true; 150 | BitmapFactory.decodeResource(res, resId, options); 151 | 152 | // Calculate inSampleSize 153 | options.inSampleSize = calculateInSampleSize(options, reqWidth, 154 | reqHeight); 155 | 156 | // Decode bitmap with inSampleSize set 157 | options.inJustDecodeBounds = false; 158 | return BitmapFactory.decodeResource(res, resId, options); 159 | } 160 | 161 | /** 162 | * Decode and sample down a bitmap from a file to the requested width and 163 | * height. 164 | * 165 | * @param filename 166 | * The full path of the file to decode 167 | * @param reqWidth 168 | * The requested width of the resulting bitmap 169 | * @param reqHeight 170 | * The requested height of the resulting bitmap 171 | * @return A bitmap sampled down from the original with the same aspect 172 | * ratio and dimensions that are equal to or greater than the 173 | * requested width and height 174 | */ 175 | public static Bitmap decodeSampledBitmapFromFile(String filename, 176 | int reqWidth, int reqHeight) { 177 | 178 | // First decode with inJustDecodeBounds=true to check dimensions 179 | final BitmapFactory.Options options = new BitmapFactory.Options(); 180 | options.inJustDecodeBounds = true; 181 | BitmapFactory.decodeFile(filename, options); 182 | 183 | // Calculate inSampleSize 184 | options.inSampleSize = calculateInSampleSize(options, reqWidth, 185 | reqHeight); 186 | 187 | // Decode bitmap with inSampleSize set 188 | options.inJustDecodeBounds = false; 189 | return BitmapFactory.decodeFile(filename, options); 190 | } 191 | 192 | /** 193 | * Decode and sample down a bitmap from a file input stream to the requested 194 | * width and height. 195 | * 196 | * @param fileDescriptor 197 | * The file descriptor to read from 198 | * @param reqWidth 199 | * The requested width of the resulting bitmap 200 | * @param reqHeight 201 | * The requested height of the resulting bitmap 202 | * @return A bitmap sampled down from the original with the same aspect 203 | * ratio and dimensions that are equal to or greater than the 204 | * requested width and height 205 | */ 206 | public static Bitmap decodeSampledBitmapFromDescriptor( 207 | FileDescriptor fileDescriptor, int reqWidth, int reqHeight) { 208 | 209 | // First decode with inJustDecodeBounds=true to check dimensions 210 | final BitmapFactory.Options options = new BitmapFactory.Options(); 211 | options.inJustDecodeBounds = true; 212 | BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); 213 | 214 | // Calculate inSampleSize 215 | options.inSampleSize = calculateInSampleSize(options, reqWidth, 216 | reqHeight); 217 | 218 | FileInputStream fileInput = new FileInputStream(fileDescriptor); 219 | try { 220 | // Decode bitmap with inSampleSize set 221 | options.inJustDecodeBounds = false; 222 | 223 | // Learned from Ig 224 | byte[] bytes = Utils.readBytes(fileInput); 225 | options.inPurgeable = true; 226 | options.inInputShareable = false; 227 | 228 | Bitmap result = BitmapFactory.decodeByteArray(bytes, 0, 229 | bytes.length, options); 230 | 231 | return result; 232 | } catch (IOException e) { 233 | e.printStackTrace(); 234 | return null; 235 | } 236 | } 237 | 238 | /** 239 | * Calculate an inSampleSize for use in a {@link android.graphics.BitmapFactory.Options} 240 | * object when decoding bitmaps using the decode* methods from 241 | * {@link android.graphics.BitmapFactory}. This implementation calculates the closest 242 | * inSampleSize that will result in the final decoded bitmap having a width 243 | * and height equal to or larger than the requested width and height. This 244 | * implementation does not ensure a power of 2 is returned for inSampleSize 245 | * which can be faster when decoding but results in a larger bitmap which 246 | * isn't as useful for caching purposes. 247 | * 248 | * @param options 249 | * An options object with out* params already populated (run 250 | * through a decode* method with inJustDecodeBounds==true 251 | * @param reqWidth 252 | * The requested width of the resulting bitmap 253 | * @param reqHeight 254 | * The requested height of the resulting bitmap 255 | * @return The value to be used for inSampleSize 256 | */ 257 | public static int calculateInSampleSize(BitmapFactory.Options options, 258 | int reqWidth, int reqHeight) { 259 | // Raw height and width of image 260 | final int height = options.outHeight; 261 | final int width = options.outWidth; 262 | int inSampleSize = 1; 263 | 264 | if (height > reqHeight || width > reqWidth) { 265 | if (width > height) { 266 | inSampleSize = Math.round((float) height / (float) reqHeight); 267 | } else { 268 | inSampleSize = Math.round((float) width / (float) reqWidth); 269 | } 270 | 271 | // This offers some additional logic in case the image has a strange 272 | // aspect ratio. For example, a panorama may have a much larger 273 | // width than height. In these cases the total pixels might still 274 | // end up being too large to fit comfortably in memory, so we should 275 | // be more aggressive with sample down the image (=larger 276 | // inSampleSize). 277 | 278 | final float totalPixels = width * height; 279 | 280 | // Anything more than 2x the requested pixels we'll sample down 281 | // further. 282 | final float totalReqPixelsCap = reqWidth * reqHeight * 2; 283 | 284 | while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { 285 | inSampleSize++; 286 | } 287 | } 288 | return inSampleSize; 289 | } 290 | } 291 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/cache/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright (C) 2012 The Android Open Source Project 19 | * 20 | * Licensed under the Apache License, Version 2.0 (the "License"); 21 | * you may not use this file except in compliance with the License. 22 | * You may obtain a copy of the License at 23 | * 24 | * http://www.apache.org/licenses/LICENSE-2.0 25 | * 26 | * Unless required by applicable law or agreed to in writing, software 27 | * distributed under the License is distributed on an "AS IS" BASIS, 28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | * See the License for the specific language governing permissions and 30 | * limitations under the License. 31 | */ 32 | 33 | package net.bither.image.cache; 34 | 35 | import android.annotation.TargetApi; 36 | import android.os.Build; 37 | import android.os.StrictMode; 38 | 39 | import java.io.BufferedInputStream; 40 | import java.io.BufferedOutputStream; 41 | import java.io.IOException; 42 | import java.io.InputStream; 43 | import java.io.OutputStream; 44 | 45 | /** 46 | * Class containing some static utility methods. 47 | */ 48 | public class Utils { 49 | private Utils() { 50 | }; 51 | 52 | @TargetApi(11) 53 | public static void enableStrictMode() { 54 | if (Utils.hasGingerbread()) { 55 | StrictMode.ThreadPolicy.Builder threadPolicyBuilder = new StrictMode.ThreadPolicy.Builder() 56 | .detectAll().penaltyLog(); 57 | StrictMode.VmPolicy.Builder vmPolicyBuilder = new StrictMode.VmPolicy.Builder() 58 | .detectAll().penaltyLog(); 59 | 60 | if (Utils.hasHoneycomb()) { 61 | threadPolicyBuilder.penaltyFlashScreen(); 62 | // TODO : Add our activities later 63 | // vmPolicyBuilder 64 | // .setClassInstanceLimit(ImageGridActivity.class, 1) 65 | // .setClassInstanceLimit(ImageDetailActivity.class, 1); 66 | } 67 | StrictMode.setThreadPolicy(threadPolicyBuilder.build()); 68 | StrictMode.setVmPolicy(vmPolicyBuilder.build()); 69 | } 70 | } 71 | 72 | public static boolean hasFroyo() { 73 | // Can use static final constants like FROYO, declared in later versions 74 | // of the OS since they are inlined at compile time. This is guaranteed 75 | // behavior. 76 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; 77 | } 78 | 79 | public static boolean hasGingerbread() { 80 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; 81 | } 82 | 83 | public static boolean hasHoneycomb() { 84 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; 85 | } 86 | 87 | public static boolean hasHoneycombMR1() { 88 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; 89 | } 90 | 91 | public static boolean hasICS() { 92 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; 93 | } 94 | 95 | public static boolean hasJellyBean() { 96 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; 97 | } 98 | 99 | public static byte[] readBytes(InputStream paramInputStream) 100 | throws IOException { 101 | byte[] arrayOfByte = new byte[paramInputStream.available()]; 102 | paramInputStream.read(arrayOfByte); 103 | return arrayOfByte; 104 | } 105 | 106 | public static void copyStream(InputStream is, OutputStream os) { 107 | BufferedInputStream bis = null; 108 | BufferedOutputStream bos = null; 109 | try { 110 | bis = new BufferedInputStream(is); 111 | bos = new BufferedOutputStream(os); 112 | byte[] bt = new byte[8192]; 113 | int len = bis.read(bt); 114 | while (len != -1) { 115 | bos.write(bt, 0, len); 116 | len = bis.read(bt); 117 | } 118 | bis.close(); 119 | bos.close(); 120 | } catch (Exception e) { 121 | 122 | e.printStackTrace(); 123 | } finally { 124 | 125 | } 126 | 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/exception/Http400Exception.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.image.exception; 17 | 18 | public class Http400Exception extends HttpException { 19 | private static final long serialVersionUID = 1L; 20 | 21 | public Http400Exception(Exception cause) { 22 | super(cause); 23 | } 24 | 25 | public Http400Exception(String msg, int statusCode) { 26 | super(msg, statusCode); 27 | } 28 | 29 | public Http400Exception(String msg, Exception cause, int statusCode) { 30 | super(msg, cause, statusCode); 31 | 32 | } 33 | 34 | public Http400Exception(String msg, Exception cause) { 35 | super(msg, cause); 36 | } 37 | 38 | public Http400Exception(String msg) { 39 | super(msg); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/exception/Http404Exception.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.image.exception; 17 | 18 | public class Http404Exception extends HttpException { 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | public Http404Exception(Exception cause) { 23 | super(cause); 24 | } 25 | 26 | public Http404Exception(String msg, int statusCode) { 27 | super(msg, statusCode); 28 | } 29 | 30 | public Http404Exception(String msg, Exception cause, int statusCode) { 31 | super(msg, cause, statusCode); 32 | 33 | } 34 | 35 | public Http404Exception(String msg, Exception cause) { 36 | super(msg, cause); 37 | } 38 | 39 | public Http404Exception(String msg) { 40 | super(msg); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/exception/HttpException.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * 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 net.bither.image.exception; /** * http statusCode not 200 deal with access to the network(http),other don't * need */ public class HttpException extends Exception { private static final long serialVersionUID = 1L; private int statusCode = -1; public HttpException(String msg) { super(msg); } public HttpException(Exception cause) { super(cause); } public HttpException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public HttpException(String msg, Exception cause) { super(msg, cause); } public HttpException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public HttpException(int statusCode) { this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } } -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/http/BaseHttpResponse.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * 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 net.bither.image.http; import android.content.Context; import net.bither.image.exception.Http400Exception; import net.bither.image.exception.Http404Exception; import net.bither.image.exception.HttpException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.io.BufferedReader; import java.io.InputStreamReader; public abstract class BaseHttpResponse { protected T result; private Context mContext; private String mUrl; private DefaultHttpClient mHttpClient; public T getResult() { return result; } public abstract void setResult(String response) throws Exception; public Context getContext() { return mContext; } public void setContext(Context context) { this.mContext = context; } public String getUrl() { return mUrl; } public void setUrl(String url) { this.mUrl = url; } public DefaultHttpClient getHttpClient() { return mHttpClient; } public void setHttpClient() { this.mHttpClient = getThreadSafeHttpClient(); } protected String getReponse(HttpResponse httpResponse) throws Exception { HttpEntity httpEntity = httpResponse.getEntity(); String response = getResponseFromEntity(httpEntity); int code = httpResponse.getStatusLine().getStatusCode(); String error = code + ":" + response; switch (code) { case 200: break; case 400: throw new Http400Exception(error); case 403: case 404: throw new Http404Exception(error); default: throw new HttpException(error); } return response; } private String getResponseFromEntity(HttpEntity entity) throws Exception { StringBuffer buffer = new StringBuffer(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader( entity.getContent(), "utf-8"), 8192); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); } return buffer.toString(); } private DefaultHttpClient getThreadSafeHttpClient() { DefaultHttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager mgr = httpClient.getConnectionManager(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HttpSetting.HTTP_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HttpSetting.HTTP_SO_TIMEOUT); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager( params, mgr.getSchemeRegistry()), params); return httpClient; } } -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/http/GetChannelApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.image.http; 17 | 18 | import net.bither.image.Top; 19 | 20 | import java.util.List; 21 | 22 | import org.json.JSONArray; 23 | 24 | 25 | public class GetChannelApi extends HttpGetResponse> { 26 | 27 | public GetChannelApi(long topId) { 28 | String url = "http://ws.getcai.com/api/2/ch/popular/"; 29 | if (topId > 0) { 30 | url = url + Long.toString(topId) + "/"; 31 | } 32 | setUrl(url); 33 | 34 | } 35 | @Override 36 | public void setResult(String response) throws Exception { 37 | 38 | this.result = Top.formatArray(new JSONArray(response)); 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/http/HttpGetResponse.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * 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 net.bither.image.http; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; public abstract class HttpGetResponse extends BaseHttpResponse { public void handleHttpGet() throws Exception { setHttpClient(); try { HttpGet httpGet = new HttpGet(getUrl()); httpGet.setHeader("Accept", "application/json"); HttpResponse httpResponse = getHttpClient().execute(httpGet); String response = getReponse(httpResponse); setResult(response); } catch (Exception e) { throw e; } finally { getHttpClient().getConnectionManager().shutdown(); } } } -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/http/HttpSetting.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.http; 18 | 19 | public class HttpSetting { 20 | /** 21 | * HTTP_CONNECTION_TIMEOUT: Set the timeout in milliseconds until a 22 | * connection is established. The default value is zero, that means the 23 | * timeout is not used. 24 | */ 25 | public static final int HTTP_CONNECTION_TIMEOUT = 5 * 1000; 26 | /** 27 | * HTTP_SO_TIMEOUT: Set the default socket timeout (SO_TIMEOUT). in 28 | * milliseconds which is the timeout for waiting for data. 29 | */ 30 | public static final int HTTP_SO_TIMEOUT = 7 * 1000; 31 | 32 | // session 33 | public static final String SESSION_ID = "sessionid"; 34 | public static final String CSRF_TOKEN = "csrftoken"; 35 | public static final String TOKEN = "token"; 36 | public static final String CSRF_MIDDLE_WARE_TOKEN = "csrfmiddlewaretoken"; 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/runnable/BaseRunnable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.runnable; 18 | 19 | import android.os.Handler; 20 | 21 | public abstract class BaseRunnable implements Runnable { 22 | private Handler mHandler; 23 | 24 | public Handler getHandler() { 25 | return mHandler; 26 | } 27 | 28 | public void setHandler(Handler handler) { 29 | this.mHandler = handler; 30 | } 31 | 32 | public void obtainMessage(int what) { 33 | if (mHandler != null) { 34 | this.mHandler.obtainMessage(what).sendToTarget(); 35 | } 36 | } 37 | 38 | public void obtainMessage(int what, Object obj) { 39 | if (mHandler != null) { 40 | this.mHandler.obtainMessage(what, obj).sendToTarget(); 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/runnable/GetChannelRunnable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.runnable; 18 | 19 | import net.bither.image.Top; 20 | import net.bither.image.http.GetChannelApi; 21 | 22 | import java.util.List; 23 | 24 | public class GetChannelRunnable extends BaseRunnable { 25 | private long mTopId; 26 | 27 | 28 | public GetChannelRunnable(long topId) { 29 | this.mTopId = topId; 30 | 31 | } 32 | 33 | @Override 34 | public void run() { 35 | obtainMessage(HandlerMessage.MSG_PREPARE); 36 | try { 37 | GetChannelApi getTopAPI = new GetChannelApi(mTopId); 38 | getTopAPI.handleHttpGet(); 39 | List tops = getTopAPI.getResult(); 40 | obtainMessage(HandlerMessage.MSG_SUCCESS, tops); 41 | } catch (Exception e) { 42 | obtainMessage(HandlerMessage.MSG_FAILURE); 43 | e.printStackTrace(); 44 | } 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/runnable/HandlerMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.runnable; 18 | 19 | public class HandlerMessage { 20 | public static final int MSG_PREPARE = 0; 21 | public static final int MSG_SUCCESS = 1; 22 | public static final int MSG_CANCEL = 2; 23 | 24 | // error 25 | public static final int MSG_FAILURE = 3; 26 | public static final int MSG_FAILURE_NETWORK = 4; 27 | public static final int MSG_AUTH_ERROR = 5; 28 | public static final int MSG_400 = 6; 29 | public static final int MSG_404 = 7; 30 | public static final int MSG_FILE_NOT_FOUND = 8; 31 | 32 | // finance 33 | public static final int MSG_EDIT_FINANCE = 9; 34 | public static final int MSG_DOWLOAD_FINANCE = 10; 35 | // other 36 | public static final int MSG_BEGIN_DELETE = 11; 37 | public static final int MSG_REGISTER_FLAG = 12; 38 | public static final int MSG_UPLOAD_AVATAR = 13; 39 | public static final int MSG_SAVE_FILE_FINISH = 14; 40 | public static final int MSG_ROM_RXCEPTION = 15; 41 | public static final int MSG_PIC_INSERT_DB = 16; 42 | public static final int MSG_SDCARD_EXCEPTION = 17; 43 | public static final int MSG_THIS_USER_BIND_OTHER_UID = 18; 44 | public static final int MSG_OTHER_USER_BIND_THIS_UID = 19; 45 | public static final int MSG_IS_DUPLICATE_REQUEST = 20; 46 | public static final int MSG_VALID_NO_PASS = 21; 47 | 48 | public static final int MSG_DOWLOAD = 30; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/ui/base/ImageProgressView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.ui.base; 18 | 19 | import android.content.Context; 20 | import android.graphics.Bitmap; 21 | import android.graphics.drawable.Drawable; 22 | import android.util.AttributeSet; 23 | import android.util.TypedValue; 24 | import android.view.Gravity; 25 | import android.view.LayoutInflater; 26 | import android.view.View; 27 | import android.widget.FrameLayout; 28 | import android.widget.ImageView; 29 | import android.widget.ImageView.ScaleType; 30 | import android.widget.LinearLayout; 31 | import android.widget.ProgressBar; 32 | import android.widget.TextView; 33 | 34 | import net.bither.image.R; 35 | import net.bither.image.cache.FetcherHolder; 36 | import net.bither.image.cache.FileDowloadProgressListener; 37 | import net.bither.image.cache.ImageManageUtil; 38 | import net.bither.image.cache.ImageWorker; 39 | 40 | import java.util.Locale; 41 | 42 | public class ImageProgressView extends FrameLayout { 43 | private TextView tvReload; 44 | private ImageView mIv; 45 | private ProgressBar mPb; 46 | private LinearLayout mPbContainer; 47 | private Context mContext; 48 | private LinearLayout.LayoutParams pbLp; 49 | private LayoutInflater inflater; 50 | 51 | private String mImageUrl; 52 | private int mWidth; 53 | private int mHeight; 54 | private boolean mIsAddMemoryCache; 55 | 56 | private int pbHeight = -1; 57 | 58 | private OnClickListener oriOnClickListener; 59 | 60 | public ImageProgressView(Context context) { 61 | super(context); 62 | initViews(); 63 | } 64 | 65 | public ImageProgressView(Context context, AttributeSet attrs, int defStyle) { 66 | super(context, attrs, defStyle); 67 | initViews(); 68 | } 69 | 70 | public ImageProgressView(Context context, AttributeSet attrs) { 71 | super(context, attrs); 72 | initViews(); 73 | } 74 | 75 | private void initViews() { 76 | this.mContext = this.getContext(); 77 | inflater = LayoutInflater.from(mContext); 78 | mIv = new ImageView(mContext); 79 | mIv.setScaleType(ScaleType.FIT_XY); 80 | mPb = (ProgressBar) inflater.inflate( 81 | R.layout.image_progress_view_progress_bar, null); 82 | mPbContainer = new LinearLayout(mContext); 83 | this.addView(mIv, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 84 | pbLp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 85 | LayoutParams.WRAP_CONTENT, Gravity.CENTER); 86 | mPbContainer.addView(mPb, pbLp); 87 | mPbContainer.setPadding(40, 0, 40, 0); 88 | this.addView(mPbContainer, new LayoutParams( 89 | LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 90 | Gravity.CENTER)); 91 | pbLp = (LinearLayout.LayoutParams) mPb.getLayoutParams(); 92 | mPbContainer.setVisibility(View.GONE); 93 | tvReload = new TextView(mContext); 94 | tvReload.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); 95 | tvReload.setText("image_progress_view_tap_to_reload"); 96 | tvReload.setTextColor(getResources().getColor( 97 | R.color.image_progress_bar)); 98 | LayoutParams lpReload = new LayoutParams(LayoutParams.WRAP_CONTENT, 99 | LayoutParams.WRAP_CONTENT, Gravity.CENTER); 100 | addView(tvReload, lpReload); 101 | tvReload.setVisibility(View.GONE); 102 | } 103 | 104 | public void dowloadPicameraImage(String picName, boolean isAddMemoryCache) { 105 | String url = "http://pic.getcai.com/pic/%d/%s.jpg/"; 106 | url = String.format(Locale.US, url, ImageManageUtil.IMAGE_WIDTH, picName); 107 | int imageSize = ImageManageUtil.PIIMAGE_MIDLLE_SIZE; 108 | dowloadImage(url, imageSize, imageSize, isAddMemoryCache); 109 | 110 | } 111 | 112 | FileDowloadProgressListener imageProgressListener = new FileDowloadProgressListener() { 113 | @Override 114 | public void onCancel() { 115 | hideAndResetProgressBar(); 116 | 117 | } 118 | 119 | @Override 120 | public void onProgress(ProgressValue progressValue) { 121 | if (progressValue != null) { 122 | switch (progressValue.getDownloadType()) { 123 | case PREPARE: 124 | showProgressBar(); 125 | break; 126 | case BEGIN: 127 | beginDownload(progressValue.getSum()); 128 | // LogUtil.debug("progress", 129 | // "sum:"+progressValue.getValue()); 130 | break; 131 | case DOWNLOING: 132 | setProgress(progressValue.getValue()); 133 | break; 134 | case END: 135 | hideAndResetProgressBar(); 136 | // LogUtil.debug("progress", 137 | // "count:"+progressValue.getValue()); 138 | break; 139 | case ERROR: 140 | showError(); 141 | break; 142 | default: 143 | break; 144 | } 145 | } 146 | 147 | } 148 | }; 149 | 150 | public void onDestroy() { 151 | mIv.setImageBitmap(null); 152 | } 153 | 154 | public void dowloadImage(String url, int w, int h, boolean isAddMemoryCache) { 155 | mImageUrl = url; 156 | mWidth = w; 157 | mHeight = h; 158 | mIsAddMemoryCache = isAddMemoryCache; 159 | hideAndResetProgressBar(); 160 | mIv.setTag(imageProgressListener); 161 | FetcherHolder.getLargeImageFetcher().loadImage(url, mIv, 162 | isAddMemoryCache); 163 | } 164 | 165 | /** 166 | * ��ʼ���أ���ʾ����������ͼƬ 167 | * 168 | * @param max 169 | * ��ʼ����ʱ����ProgressBar���ֵ 170 | */ 171 | public void beginDownload(int max) { 172 | showProgressBar(); 173 | setMax(max); 174 | } 175 | 176 | public void showProgressBar() { 177 | tvReload.setVisibility(View.GONE); 178 | mPbContainer.setVisibility(View.VISIBLE); 179 | } 180 | 181 | public void hideAndResetProgressBar() { 182 | setOnClickListener(oriOnClickListener); 183 | mPbContainer.setVisibility(View.GONE); 184 | tvReload.setVisibility(View.GONE); 185 | setMax(100);// �����õĻ��첽��������ִ�е�ʱ���ȡ���ϴε�ֵ 186 | setProgress(0); 187 | } 188 | 189 | public void showError() { 190 | hideAndResetProgressBar(); 191 | tvReload.setVisibility(View.VISIBLE); 192 | super.setOnClickListener(reloadClick); 193 | setClickable(true); 194 | } 195 | 196 | public void setMax(int max) { 197 | mPb.setMax(max); 198 | } 199 | 200 | public void setProgress(int progress) { 201 | mPb.setProgress(progress); 202 | } 203 | 204 | public void incrementProgressBy(int diff) { 205 | mPb.incrementProgressBy(diff); 206 | } 207 | 208 | public void setImageBitmap(Bitmap bm) { 209 | mIv.setImageBitmap(bm); 210 | 211 | } 212 | 213 | public Drawable getDrawable() { 214 | if (mIv.getDrawable() instanceof ImageWorker.AsyncDrawable) { 215 | return null; 216 | } else { 217 | return mIv.getDrawable(); 218 | } 219 | } 220 | 221 | @Override 222 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 223 | super.onSizeChanged(w, h, oldw, oldh); 224 | if (pbHeight == -1) { 225 | if (h > 150) { 226 | if (pbLp.height != 25) { 227 | pbLp.height = 25; 228 | } 229 | } else { 230 | if (pbLp.height != 7) { 231 | pbLp.height = 7; 232 | } 233 | } 234 | } else { 235 | if (pbLp.height != pbHeight) { 236 | pbLp.height = pbHeight; 237 | } 238 | } 239 | } 240 | 241 | public ProgressBar getProgressBar() { 242 | return mPb; 243 | } 244 | 245 | public ImageView getImageView() { 246 | return mIv; 247 | } 248 | 249 | public void setProgressBarHeight(int height) { 250 | pbHeight = height; 251 | pbLp.height = pbHeight; 252 | } 253 | 254 | @Override 255 | public void setOnClickListener(OnClickListener l) { 256 | oriOnClickListener = l; 257 | super.setOnClickListener(l); 258 | if (oriOnClickListener != null) { 259 | setClickable(true); 260 | } else { 261 | setClickable(false); 262 | } 263 | } 264 | 265 | private OnClickListener reloadClick = new OnClickListener() { 266 | 267 | @Override 268 | public void onClick(View v) { 269 | dowloadImage(mImageUrl, mWidth, mHeight, mIsAddMemoryCache); 270 | } 271 | }; 272 | 273 | } 274 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/ui/base/PicDetailClickListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.ui.base; 18 | 19 | import android.content.Context; 20 | import android.content.Intent; 21 | import android.view.View; 22 | import android.view.View.OnClickListener; 23 | 24 | import net.bither.image.BitherApplication; 25 | import net.bither.image.PicDetailActivity; 26 | import net.bither.image.Top; 27 | 28 | public class PicDetailClickListener implements OnClickListener { 29 | 30 | /** 31 | * can't click again in 1s 32 | */ 33 | private boolean clicked = false; 34 | private Context context; 35 | private Top pic; 36 | 37 | public PicDetailClickListener(Top pic) { 38 | this.pic = pic; 39 | } 40 | 41 | protected Intent processIntent(Intent intent) { 42 | return intent; 43 | } 44 | 45 | @Override 46 | public void onClick(View v) { 47 | if (!clicked) { 48 | clicked = true; 49 | v.postDelayed(new Runnable() { 50 | @Override 51 | public void run() { 52 | clicked = false; 53 | } 54 | }, 1000); 55 | context = v.getContext(); 56 | 57 | Intent intent = new Intent(context, PicDetailActivity.class); 58 | intent.putExtra(BitherApplication.PIC_PASS_VALUE_TAG, pic); 59 | context.startActivity(processIntent(intent)); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/image/ui/base/TopAnimHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.image.ui.base; 18 | 19 | import android.graphics.Bitmap; 20 | import android.graphics.Rect; 21 | import android.graphics.drawable.Drawable; 22 | import android.os.Handler; 23 | import android.os.Message; 24 | import android.view.Gravity; 25 | import android.view.LayoutInflater; 26 | import android.view.View; 27 | import android.view.animation.Animation; 28 | import android.view.animation.Animation.AnimationListener; 29 | import android.view.animation.DecelerateInterpolator; 30 | import android.view.animation.TranslateAnimation; 31 | import android.widget.AbsListView.OnScrollListener; 32 | import android.widget.FrameLayout; 33 | import android.widget.ImageView; 34 | import android.widget.LinearLayout; 35 | 36 | import net.bither.image.R; 37 | import net.bither.image.Top; 38 | import net.bither.image.DisplayImagaUtil; 39 | 40 | import java.util.ArrayList; 41 | import java.util.List; 42 | 43 | public class TopAnimHandler extends Handler { 44 | public static final class MSG { 45 | public static final int CHECK = 1745; 46 | public static final int ADD_CELL = 1758; 47 | public static final int ONSCROLL = 1826; 48 | public static final int SINGLE_ANIMATION_END = 1840; 49 | public static final int RESUME = 1355; 50 | public static final int PAUSE = 1356; 51 | public static final int CLEAR = 1819; 52 | } 53 | 54 | private static final int AnimDelay = 1700; 55 | private List cells = new ArrayList(); 56 | private List animCells = new ArrayList(); 57 | private NextAnim nextAnim = new NextAnim(); 58 | 59 | private int scrollState = OnScrollListener.SCROLL_STATE_IDLE; 60 | 61 | @Override 62 | public void handleMessage(Message msg) { 63 | switch (msg.what) { 64 | case MSG.ADD_CELL: 65 | if (msg.obj != null && msg.obj instanceof CellHolder) { 66 | addCell((CellHolder) msg.obj); 67 | } 68 | break; 69 | case MSG.CHECK: 70 | case MSG.RESUME: 71 | check(); 72 | break; 73 | case MSG.ONSCROLL: 74 | scrollState = (Integer) msg.obj; 75 | onScrollStateChange(scrollState); 76 | break; 77 | case MSG.SINGLE_ANIMATION_END: 78 | nextAnim(); 79 | break; 80 | case MSG.PAUSE: 81 | stopAnimQueue(); 82 | break; 83 | case MSG.CLEAR: 84 | stopAnimQueue(); 85 | clear(); 86 | break; 87 | default: 88 | break; 89 | } 90 | super.handleMessage(msg); 91 | } 92 | 93 | private void clear() { 94 | cells.clear(); 95 | animCells.clear(); 96 | } 97 | 98 | private void startAnimQueue() { 99 | nextAnim.setCurrentCell(null); 100 | removeCallbacks(nextAnim); 101 | post(nextAnim); 102 | } 103 | 104 | private void nextAnim() { 105 | removeCallbacks(nextAnim); 106 | postDelayed(nextAnim, AnimDelay); 107 | } 108 | 109 | private void stopAnimQueue() { 110 | removeCallbacks(check); 111 | removeCallbacks(nextAnim); 112 | removeCallbacks(reset); 113 | nextAnim.setCurrentCell(null); 114 | postDelayed(reset, AnimDelay); 115 | } 116 | 117 | private void check() { 118 | if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) { 119 | return; 120 | } 121 | removeCallbacks(reset); 122 | removeCallbacks(check); 123 | postDelayed(check, AnimDelay); 124 | } 125 | 126 | private void onScrollStateChange(int state) { 127 | if (state == OnScrollListener.SCROLL_STATE_IDLE) { 128 | check(); 129 | } else { 130 | stopAnimQueue(); 131 | } 132 | } 133 | 134 | private Runnable reset = new Runnable() { 135 | 136 | @Override 137 | public void run() { 138 | for (CellHolder cell : cells) { 139 | cell.reset(); 140 | } 141 | } 142 | }; 143 | 144 | private Runnable check = new Runnable() { 145 | 146 | @Override 147 | public void run() { 148 | if (cells.size() == 0) { 149 | return; 150 | } 151 | // for (CellHolder cell : cells) { 152 | // if (cell.isToAnimate() && !animCells.contains(cell)) { 153 | // animCells.add(cell); 154 | // } 155 | // if (!cell.isToAnimate() && animCells.contains(cell)) { 156 | // animCells.remove(cell); 157 | // } 158 | // if (!cell.isReadyForAnimation()) { 159 | // return; 160 | // } 161 | // } 162 | if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { 163 | startAnimQueue(); 164 | } 165 | } 166 | }; 167 | 168 | private void addCell(CellHolder cell) { 169 | if (!cells.contains(cell)) { 170 | cells.add(cell); 171 | } 172 | } 173 | 174 | private class NextAnim implements Runnable { 175 | private CellHolder currentCell; 176 | 177 | public void setCurrentCell(CellHolder cell) { 178 | currentCell = cell; 179 | } 180 | 181 | @Override 182 | public void run() { 183 | if (animCells.size() > 0) { 184 | CellHolder cell = animCells.get(0); 185 | if (currentCell != null && animCells.contains(currentCell)) { 186 | int curPos = animCells.indexOf(currentCell); 187 | curPos++; 188 | if (curPos >= animCells.size()) { 189 | curPos = 0; 190 | } 191 | cell = animCells.get(curPos); 192 | } 193 | cell.anim(); 194 | setCurrentCell(cell); 195 | } 196 | } 197 | } 198 | 199 | public static class CellHolder { 200 | private static final int AnimDuration = 700; 201 | Rect paddingRect = new Rect(); 202 | public FrameLayout fl; 203 | private FrameLayout flContainer; 204 | public ImageView iv; 205 | public ImageView ivAnimated; 206 | String imageName = ""; 207 | int currentPosition; 208 | boolean isReadyForAnimation = false; 209 | 210 | AnimCheckRunnable animCheckRunnable = new AnimCheckRunnable(); 211 | 212 | public CellHolder(LayoutInflater inflater) { 213 | fl = (FrameLayout) inflater.inflate( 214 | R.layout.list_item_top_grid_item, null); 215 | 216 | iv = (ImageView) fl.findViewById(R.id.iv); 217 | ivAnimated = (ImageView) fl 218 | .findViewById(R.id.iv_animated); 219 | flContainer = (FrameLayout) fl.findViewById(R.id.fl); 220 | Drawable foreground = inflater.getContext().getResources() 221 | .getDrawable(R.drawable.grid_photo_overlay); 222 | foreground.getPadding(paddingRect); 223 | fl.setForeground(foreground); 224 | fl.setPadding(paddingRect.left, paddingRect.top, paddingRect.right, 225 | paddingRect.bottom); 226 | fl.setForegroundGravity(Gravity.FILL); 227 | 228 | 229 | } 230 | 231 | 232 | private class AnimListener implements AnimationListener { 233 | private Bitmap bmp; 234 | 235 | public AnimListener(Bitmap bmp) { 236 | this.bmp = bmp; 237 | } 238 | 239 | @Override 240 | public void onAnimationStart(Animation animation) { 241 | } 242 | 243 | @Override 244 | public void onAnimationRepeat(Animation animation) { 245 | } 246 | 247 | @Override 248 | public void onAnimationEnd(Animation animation) { 249 | ivAnimated.removeCallbacks(animCheckRunnable); 250 | iv.setImageBitmap(bmp); 251 | bmp = null; 252 | ivAnimated.postDelayed(animEndRunnable, 50); 253 | } 254 | } 255 | 256 | ; 257 | 258 | private Runnable animEndRunnable = new Runnable() { 259 | 260 | @Override 261 | public void run() { 262 | ivAnimated.setImageBitmap(null); 263 | ivAnimated.setVisibility(View.INVISIBLE); 264 | 265 | } 266 | }; 267 | 268 | public void anim() { 269 | currentPosition++; 270 | if (imageName == null) { 271 | return; 272 | } 273 | 274 | DisplayImagaUtil.showSmallImage( 275 | imageName, ivAnimated, true); 276 | } 277 | 278 | public void addToView(LinearLayout v, LinearLayout.LayoutParams lp) { 279 | v.addView(fl, lp); 280 | iv.getLayoutParams().height = lp.height - paddingRect.top 281 | - paddingRect.bottom; 282 | iv.getLayoutParams().width = lp.width - paddingRect.left 283 | - paddingRect.right; 284 | ivAnimated.getLayoutParams().height = iv.getLayoutParams().height; 285 | ivAnimated.getLayoutParams().width = iv.getLayoutParams().width; 286 | flContainer.getLayoutParams().height = iv.getLayoutParams().height; 287 | flContainer.getLayoutParams().width = iv.getLayoutParams().width; 288 | 289 | } 290 | 291 | public void setPiCommon(Top pi) { 292 | imageName = pi.getPicName(); 293 | } 294 | 295 | 296 | public boolean isReadyForAnimation() { 297 | return isReadyForAnimation; 298 | } 299 | 300 | public void reset() { 301 | ivAnimated.clearAnimation(); 302 | ivAnimated.setImageBitmap(null); 303 | ivAnimated.setVisibility(View.INVISIBLE); 304 | ivAnimated.removeCallbacks(animEndRunnable); 305 | ivAnimated.removeCallbacks(animCheckRunnable); 306 | iv.clearAnimation(); 307 | currentPosition = 0; 308 | 309 | DisplayImagaUtil.showSmallImage( 310 | imageName, iv, true); 311 | 312 | } 313 | 314 | private TranslateAnimation getTransAnim() { 315 | int direction = (int) Math.floor(Math.random() * 4); 316 | TranslateAnimation a; 317 | switch (direction) { 318 | case 0: 319 | a = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1, 320 | Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0, 321 | Animation.ABSOLUTE, 0); 322 | break; 323 | case 1: 324 | a = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1, 325 | Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0, 326 | Animation.ABSOLUTE, 0); 327 | break; 328 | case 2: 329 | a = new TranslateAnimation(Animation.ABSOLUTE, 0, 330 | Animation.ABSOLUTE, 0, Animation.RELATIVE_TO_SELF, 1, 331 | Animation.ABSOLUTE, 0); 332 | break; 333 | case 3: 334 | default: 335 | a = new TranslateAnimation(Animation.ABSOLUTE, 0, 336 | Animation.ABSOLUTE, 0, Animation.RELATIVE_TO_SELF, -1, 337 | Animation.ABSOLUTE, 0); 338 | break; 339 | } 340 | a.setInterpolator(new DecelerateInterpolator(1.2f)); 341 | a.setDuration(AnimDuration); 342 | return a; 343 | } 344 | 345 | private class AnimCheckRunnable implements Runnable { 346 | private Animation anim; 347 | 348 | public void setAnimation(Animation anim) { 349 | this.anim = anim; 350 | } 351 | 352 | @Override 353 | public void run() { 354 | if (anim != null && !anim.hasStarted()) { 355 | ivAnimated.setImageBitmap(null); 356 | ivAnimated.setVisibility(View.INVISIBLE); 357 | 358 | } 359 | } 360 | } 361 | } 362 | 363 | } 364 | -------------------------------------------------------------------------------- /app/src/main/java/net/bither/util/NativeUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.util; 18 | 19 | import android.graphics.Bitmap; 20 | import android.graphics.Bitmap.Config; 21 | import android.graphics.Canvas; 22 | import android.graphics.Rect; 23 | import android.util.Log; 24 | 25 | public class NativeUtil { 26 | private static int DEFAULT_QUALITY = 95; 27 | 28 | public static void compressBitmap(Bitmap bit, String fileName, 29 | boolean optimize) { 30 | compressBitmap(bit, DEFAULT_QUALITY, fileName, optimize); 31 | 32 | } 33 | 34 | public static void compressBitmap(Bitmap bit, int quality, String fileName, 35 | boolean optimize) { 36 | Log.d("native", "compress of native"); 37 | if (bit.getConfig() != Config.ARGB_8888) { 38 | Bitmap result = null; 39 | 40 | result = Bitmap.createBitmap(bit.getWidth(), bit.getHeight(), 41 | Config.ARGB_8888); 42 | Canvas canvas = new Canvas(result); 43 | Rect rect = new Rect(0, 0, bit.getWidth(), bit.getHeight()); 44 | canvas.drawBitmap(bit, null, rect, null); 45 | saveBitmap(result, quality, fileName, optimize); 46 | result.recycle(); 47 | } else { 48 | saveBitmap(bit, quality, fileName, optimize); 49 | } 50 | 51 | } 52 | 53 | private static void saveBitmap(Bitmap bit, int quality, String fileName, 54 | boolean optimize) { 55 | compressBitmap(bit, bit.getWidth(), bit.getHeight(), quality, 56 | fileName.getBytes(), optimize); 57 | 58 | } 59 | 60 | private static native String compressBitmap(Bitmap bit, int w, int h, 61 | int quality, byte[] fileNameBytes, boolean optimize); 62 | 63 | static { 64 | System.loadLibrary("jpegbither"); 65 | System.loadLibrary("bitherjni"); 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_in_bottom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_in_right.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_in_top.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_out_bottom_left.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 14 | 15 | 26 | 27 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_out_right.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_out_top.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/button_small_green.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-hdpi/button_small_green.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/button_small_green_pressed.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-hdpi/button_small_green_pressed.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/tab_divider.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-hdpi/tab_divider.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ui_topnav_titlebar_background.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-hdpi/ui_topnav_titlebar_background.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/grid_cell_background.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/grid_cell_background.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/grid_cell_overlay.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/grid_cell_overlay.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/grid_photo_overlay.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/grid_photo_overlay.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/photo_bg_default.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/photo_bg_default.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/photo_bg_pressed.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/photo_bg_pressed.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/photo_delete.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/photo_delete.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/photo_delete_pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-mdpi/photo_delete_pressed.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/title_bar_light_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-xhdpi/title_bar_light_back.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bither-bitmap-sample/f36bfeaebada6c1ceff9a982359b02489cfa0abf/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable/button_small_green_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/image_progress_view_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/image_progress_view_progress_drawable.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/photo_bg_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/photo_touchable_foreground.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/post_share_at_user_list_item_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/progress_horizontal.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/selectable_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/tab_button_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/top_amt_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/top_amt_background_small.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/transparent.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ui_touchable_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/user_level_progress_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/user_level_progress_drawable.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_pic_detail.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 15 | 16 | 23 | 24 | 29 | 30 | 31 | 32 | 33 | 40 | 41 |