├── .gitignore ├── ABOUT.txt ├── Application ├── build.gradle ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── android │ │ │ ├── common │ │ │ └── logger │ │ │ │ ├── Log.java │ │ │ │ ├── LogFragment.java │ │ │ │ ├── LogNode.java │ │ │ │ ├── LogView.java │ │ │ │ ├── LogWrapper.java │ │ │ │ └── MessageOnlyLogFilter.java │ │ │ └── displayingbitmaps │ │ │ ├── provider │ │ │ └── Images.java │ │ │ ├── ui │ │ │ ├── ImageDetailActivity.java │ │ │ ├── ImageDetailFragment.java │ │ │ ├── ImageGridActivity.java │ │ │ ├── ImageGridFragment.java │ │ │ └── RecyclingImageView.java │ │ │ └── util │ │ │ ├── AsyncTask.java │ │ │ ├── DiskLruCache.java │ │ │ ├── ImageCache.java │ │ │ ├── ImageFetcher.java │ │ │ ├── ImageResizer.java │ │ │ ├── ImageWorker.java │ │ │ ├── RecyclingBitmapDrawable.java │ │ │ └── Utils.java │ │ └── res │ │ ├── drawable-hdpi │ │ ├── ic_launcher.png │ │ └── tile.9.png │ │ ├── drawable-mdpi │ │ └── ic_launcher.png │ │ ├── drawable-nodpi │ │ └── empty_photo.png │ │ ├── drawable-xhdpi │ │ └── ic_launcher.png │ │ ├── drawable-xxhdpi │ │ └── ic_launcher.png │ │ ├── drawable │ │ └── photogrid_list_selector.xml │ │ ├── layout │ │ ├── image_detail_fragment.xml │ │ ├── image_detail_pager.xml │ │ └── image_grid_fragment.xml │ │ ├── menu │ │ └── main_menu.xml │ │ ├── values-large │ │ └── dimens.xml │ │ ├── values-sw600dp │ │ ├── template-dimens.xml │ │ └── template-styles.xml │ │ ├── values-v11 │ │ ├── styles.xml │ │ └── template-styles.xml │ │ ├── values-v21 │ │ ├── base-colors.xml │ │ └── base-template-styles.xml │ │ ├── values-xlarge │ │ └── dimens.xml │ │ └── values │ │ ├── base-strings.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ ├── styles.xml │ │ ├── template-dimens.xml │ │ └── template-styles.xml └── tests │ ├── AndroidManifest.xml │ └── src │ └── com │ └── example │ └── android │ └── displayingbitmaps │ └── tests │ └── SampleTests.java ├── CONTRIB.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── packaging.yaml └── 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 | # Android Studio Navigation editor temp files 29 | .navigation/ 30 | 31 | # Android Studio captures folder 32 | captures/ 33 | 34 | .idea/ 35 | *.iml 36 | **/*.iml 37 | -------------------------------------------------------------------------------- /ABOUT.txt: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 The Android Open Source Project 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | --------------------------------------- 16 | 17 | This is a sample application for the Android Training class "Displaying Bitmaps 18 | Efficiently" (http://developer.android.com/training/displaying-bitmaps/). 19 | 20 | It demonstrates how to load large bitmaps efficiently off the main UI thread, 21 | caching bitmaps (both in memory and on disk), managing bitmap memory and 22 | displaying bitmaps in UI elements such as ViewPager and ListView/GridView. -------------------------------------------------------------------------------- /Application/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | buildscript { 3 | repositories { 4 | jcenter() 5 | } 6 | 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.0.0-alpha3' 9 | } 10 | } 11 | 12 | apply plugin: 'com.android.application' 13 | 14 | repositories { 15 | jcenter() 16 | mavenLocal() 17 | } 18 | 19 | dependencies { 20 | compile "com.android.support:support-v4:23.1.1" 21 | compile "com.android.support:gridlayout-v7:23.1.1" 22 | compile "com.android.support:cardview-v7:23.1.1" 23 | compile("org.deeplearning4j:deeplearning4j-core:0.4-rc3.8"){ 24 | exclude group: "ch.qos.logback", module: "logback-core" 25 | exclude group: "ch.qos.logback", module: "logback-classic" 26 | } 27 | compile("org.nd4j:nd4j-x86:0.4-rc3.9-SNAPSHOT"){ 28 | exclude group: "ch.qos.logback", module: "logback-core" 29 | exclude group: "ch.qos.logback", module: "logback-classic" 30 | } 31 | compile 'com.github.tony19:logback-android-core:1.1.1-4' 32 | compile 'com.github.tony19:logback-android-classic:1.1.1-4' 33 | } 34 | 35 | android { 36 | compileSdkVersion 23 37 | buildToolsVersion "23.0.2" 38 | 39 | defaultConfig { 40 | minSdkVersion 9 41 | targetSdkVersion 23 42 | versionCode 1 43 | versionName "0.1-SNAPSHOT" 44 | multiDexEnabled true 45 | } 46 | 47 | compileOptions { 48 | sourceCompatibility JavaVersion.VERSION_1_7 49 | targetCompatibility JavaVersion.VERSION_1_7 50 | } 51 | 52 | sourceSets { 53 | androidTest.setRoot('tests') 54 | androidTest.java.srcDirs = ['tests/src'] 55 | 56 | } 57 | 58 | dexOptions { 59 | incremental true 60 | javaMaxHeapSize "2048M" 61 | } 62 | packagingOptions { 63 | exclude 'META-INF/DEPENDENCIES.txt' 64 | exclude 'META-INF/LICENSE' 65 | exclude 'META-INF/LICENSE.txt' 66 | exclude 'META-INF/license.txt' 67 | exclude 'META-INF/NOTICE' 68 | exclude 'META-INF/NOTICE.txt' 69 | exclude 'META-INF/notice.txt' 70 | exclude 'META-INF/DEPENDENCIES' 71 | exclude 'META-INF/io.netty.versions.properties' 72 | exclude 'META-INF/INDEX.LIST' 73 | exclude 'META-INF/services/javax.imageio.spi.ImageReaderSpi' 74 | exclude 'META-INF/services/javax.imageio.spi.ImageWriterSpi' 75 | exclude 'META-INF/services/com.fasterxml.jackson.core.JsonFactory' 76 | } 77 | 78 | } 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /Application/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 34 | 35 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 48 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/Log.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 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 com.example.android.common.logger; 17 | 18 | /** 19 | * Helper class for a list (or tree) of LoggerNodes. 20 | * 21 | *

When this is set as the head of the list, 22 | * an instance of it can function as a drop-in replacement for {@link android.util.Log}. 23 | * Most of the methods in this class server only to map a method call in Log to its equivalent 24 | * in LogNode.

25 | */ 26 | public class Log { 27 | // Grabbing the native values from Android's native logging facilities, 28 | // to make for easy migration and interop. 29 | public static final int NONE = -1; 30 | public static final int VERBOSE = android.util.Log.VERBOSE; 31 | public static final int DEBUG = android.util.Log.DEBUG; 32 | public static final int INFO = android.util.Log.INFO; 33 | public static final int WARN = android.util.Log.WARN; 34 | public static final int ERROR = android.util.Log.ERROR; 35 | public static final int ASSERT = android.util.Log.ASSERT; 36 | 37 | // Stores the beginning of the LogNode topology. 38 | private static LogNode mLogNode; 39 | 40 | /** 41 | * Returns the next LogNode in the linked list. 42 | */ 43 | public static LogNode getLogNode() { 44 | return mLogNode; 45 | } 46 | 47 | /** 48 | * Sets the LogNode data will be sent to. 49 | */ 50 | public static void setLogNode(LogNode node) { 51 | mLogNode = node; 52 | } 53 | 54 | /** 55 | * Instructs the LogNode to print the log data provided. Other LogNodes can 56 | * be chained to the end of the LogNode as desired. 57 | * 58 | * @param priority Log level of the data being logged. Verbose, Error, etc. 59 | * @param tag Tag for for the log data. Can be used to organize log statements. 60 | * @param msg The actual message to be logged. 61 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 62 | * to extract and print useful information. 63 | */ 64 | public static void println(int priority, String tag, String msg, Throwable tr) { 65 | if (mLogNode != null) { 66 | mLogNode.println(priority, tag, msg, tr); 67 | } 68 | } 69 | 70 | /** 71 | * Instructs the LogNode to print the log data provided. Other LogNodes can 72 | * be chained to the end of the LogNode as desired. 73 | * 74 | * @param priority Log level of the data being logged. Verbose, Error, etc. 75 | * @param tag Tag for for the log data. Can be used to organize log statements. 76 | * @param msg The actual message to be logged. The actual message to be logged. 77 | */ 78 | public static void println(int priority, String tag, String msg) { 79 | println(priority, tag, msg, null); 80 | } 81 | 82 | /** 83 | * Prints a message at VERBOSE priority. 84 | * 85 | * @param tag Tag for for the log data. Can be used to organize log statements. 86 | * @param msg The actual message to be logged. 87 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 88 | * to extract and print useful information. 89 | */ 90 | public static void v(String tag, String msg, Throwable tr) { 91 | println(VERBOSE, tag, msg, tr); 92 | } 93 | 94 | /** 95 | * Prints a message at VERBOSE priority. 96 | * 97 | * @param tag Tag for for the log data. Can be used to organize log statements. 98 | * @param msg The actual message to be logged. 99 | */ 100 | public static void v(String tag, String msg) { 101 | v(tag, msg, null); 102 | } 103 | 104 | 105 | /** 106 | * Prints a message at DEBUG priority. 107 | * 108 | * @param tag Tag for for the log data. Can be used to organize log statements. 109 | * @param msg The actual message to be logged. 110 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 111 | * to extract and print useful information. 112 | */ 113 | public static void d(String tag, String msg, Throwable tr) { 114 | println(DEBUG, tag, msg, tr); 115 | } 116 | 117 | /** 118 | * Prints a message at DEBUG priority. 119 | * 120 | * @param tag Tag for for the log data. Can be used to organize log statements. 121 | * @param msg The actual message to be logged. 122 | */ 123 | public static void d(String tag, String msg) { 124 | d(tag, msg, null); 125 | } 126 | 127 | /** 128 | * Prints a message at INFO priority. 129 | * 130 | * @param tag Tag for for the log data. Can be used to organize log statements. 131 | * @param msg The actual message to be logged. 132 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 133 | * to extract and print useful information. 134 | */ 135 | public static void i(String tag, String msg, Throwable tr) { 136 | println(INFO, tag, msg, tr); 137 | } 138 | 139 | /** 140 | * Prints a message at INFO priority. 141 | * 142 | * @param tag Tag for for the log data. Can be used to organize log statements. 143 | * @param msg The actual message to be logged. 144 | */ 145 | public static void i(String tag, String msg) { 146 | i(tag, msg, null); 147 | } 148 | 149 | /** 150 | * Prints a message at WARN priority. 151 | * 152 | * @param tag Tag for for the log data. Can be used to organize log statements. 153 | * @param msg The actual message to be logged. 154 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 155 | * to extract and print useful information. 156 | */ 157 | public static void w(String tag, String msg, Throwable tr) { 158 | println(WARN, tag, msg, tr); 159 | } 160 | 161 | /** 162 | * Prints a message at WARN priority. 163 | * 164 | * @param tag Tag for for the log data. Can be used to organize log statements. 165 | * @param msg The actual message to be logged. 166 | */ 167 | public static void w(String tag, String msg) { 168 | w(tag, msg, null); 169 | } 170 | 171 | /** 172 | * Prints a message at WARN priority. 173 | * 174 | * @param tag Tag for for the log data. Can be used to organize log statements. 175 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 176 | * to extract and print useful information. 177 | */ 178 | public static void w(String tag, Throwable tr) { 179 | w(tag, null, tr); 180 | } 181 | 182 | /** 183 | * Prints a message at ERROR priority. 184 | * 185 | * @param tag Tag for for the log data. Can be used to organize log statements. 186 | * @param msg The actual message to be logged. 187 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 188 | * to extract and print useful information. 189 | */ 190 | public static void e(String tag, String msg, Throwable tr) { 191 | println(ERROR, tag, msg, tr); 192 | } 193 | 194 | /** 195 | * Prints a message at ERROR priority. 196 | * 197 | * @param tag Tag for for the log data. Can be used to organize log statements. 198 | * @param msg The actual message to be logged. 199 | */ 200 | public static void e(String tag, String msg) { 201 | e(tag, msg, null); 202 | } 203 | 204 | /** 205 | * Prints a message at ASSERT priority. 206 | * 207 | * @param tag Tag for for the log data. Can be used to organize log statements. 208 | * @param msg The actual message to be logged. 209 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 210 | * to extract and print useful information. 211 | */ 212 | public static void wtf(String tag, String msg, Throwable tr) { 213 | println(ASSERT, tag, msg, tr); 214 | } 215 | 216 | /** 217 | * Prints a message at ASSERT priority. 218 | * 219 | * @param tag Tag for for the log data. Can be used to organize log statements. 220 | * @param msg The actual message to be logged. 221 | */ 222 | public static void wtf(String tag, String msg) { 223 | wtf(tag, msg, null); 224 | } 225 | 226 | /** 227 | * Prints a message at ASSERT priority. 228 | * 229 | * @param tag Tag for for the log data. Can be used to organize log statements. 230 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 231 | * to extract and print useful information. 232 | */ 233 | public static void wtf(String tag, Throwable tr) { 234 | wtf(tag, null, tr); 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 The Android Open Source Project 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 | * Copyright 2013 The Android Open Source Project 18 | * 19 | * Licensed under the Apache License, Version 2.0 (the "License"); 20 | * you may not use this file except in compliance with the License. 21 | * You may obtain a copy of the License at 22 | * 23 | * http://www.apache.org/licenses/LICENSE-2.0 24 | * 25 | * Unless required by applicable law or agreed to in writing, software 26 | * distributed under the License is distributed on an "AS IS" BASIS, 27 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | * See the License for the specific language governing permissions and 29 | * limitations under the License. 30 | */ 31 | 32 | package com.example.android.common.logger; 33 | 34 | import android.graphics.Typeface; 35 | import android.os.Bundle; 36 | import android.support.v4.app.Fragment; 37 | import android.text.Editable; 38 | import android.text.TextWatcher; 39 | import android.view.Gravity; 40 | import android.view.LayoutInflater; 41 | import android.view.View; 42 | import android.view.ViewGroup; 43 | import android.widget.ScrollView; 44 | 45 | /** 46 | * Simple fraggment which contains a LogView and uses is to output log data it receives 47 | * through the LogNode interface. 48 | */ 49 | public class LogFragment extends Fragment { 50 | 51 | private LogView mLogView; 52 | private ScrollView mScrollView; 53 | 54 | public LogFragment() {} 55 | 56 | public View inflateViews() { 57 | mScrollView = new ScrollView(getActivity()); 58 | ViewGroup.LayoutParams scrollParams = new ViewGroup.LayoutParams( 59 | ViewGroup.LayoutParams.MATCH_PARENT, 60 | ViewGroup.LayoutParams.MATCH_PARENT); 61 | mScrollView.setLayoutParams(scrollParams); 62 | 63 | mLogView = new LogView(getActivity()); 64 | ViewGroup.LayoutParams logParams = new ViewGroup.LayoutParams(scrollParams); 65 | logParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; 66 | mLogView.setLayoutParams(logParams); 67 | mLogView.setClickable(true); 68 | mLogView.setFocusable(true); 69 | mLogView.setTypeface(Typeface.MONOSPACE); 70 | 71 | // Want to set padding as 16 dips, setPadding takes pixels. Hooray math! 72 | int paddingDips = 16; 73 | double scale = getResources().getDisplayMetrics().density; 74 | int paddingPixels = (int) ((paddingDips * (scale)) + .5); 75 | mLogView.setPadding(paddingPixels, paddingPixels, paddingPixels, paddingPixels); 76 | mLogView.setCompoundDrawablePadding(paddingPixels); 77 | 78 | mLogView.setGravity(Gravity.BOTTOM); 79 | mLogView.setTextAppearance(getActivity(), android.R.style.TextAppearance_Holo_Medium); 80 | 81 | mScrollView.addView(mLogView); 82 | return mScrollView; 83 | } 84 | 85 | @Override 86 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 87 | Bundle savedInstanceState) { 88 | 89 | View result = inflateViews(); 90 | 91 | mLogView.addTextChangedListener(new TextWatcher() { 92 | @Override 93 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 94 | 95 | @Override 96 | public void onTextChanged(CharSequence s, int start, int before, int count) {} 97 | 98 | @Override 99 | public void afterTextChanged(Editable s) { 100 | mScrollView.fullScroll(ScrollView.FOCUS_DOWN); 101 | } 102 | }); 103 | return result; 104 | } 105 | 106 | public LogView getLogView() { 107 | return mLogView; 108 | } 109 | } -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.common.logger; 17 | 18 | /** 19 | * Basic interface for a logging system that can output to one or more targets. 20 | * Note that in addition to classes that will output these logs in some format, 21 | * one can also implement this interface over a filter and insert that in the chain, 22 | * such that no targets further down see certain data, or see manipulated forms of the data. 23 | * You could, for instance, write a "ToHtmlLoggerNode" that just converted all the log data 24 | * it received to HTML and sent it along to the next node in the chain, without printing it 25 | * anywhere. 26 | */ 27 | public interface LogNode { 28 | 29 | /** 30 | * Instructs first LogNode in the list to print the log data provided. 31 | * @param priority Log level of the data being logged. Verbose, Error, etc. 32 | * @param tag Tag for for the log data. Can be used to organize log statements. 33 | * @param msg The actual message to be logged. The actual message to be logged. 34 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 35 | * to extract and print useful information. 36 | */ 37 | public void println(int priority, String tag, String msg, Throwable tr); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 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 com.example.android.common.logger; 17 | 18 | import android.app.Activity; 19 | import android.content.Context; 20 | import android.util.*; 21 | import android.widget.TextView; 22 | 23 | /** Simple TextView which is used to output log data received through the LogNode interface. 24 | */ 25 | public class LogView extends TextView implements LogNode { 26 | 27 | public LogView(Context context) { 28 | super(context); 29 | } 30 | 31 | public LogView(Context context, AttributeSet attrs) { 32 | super(context, attrs); 33 | } 34 | 35 | public LogView(Context context, AttributeSet attrs, int defStyle) { 36 | super(context, attrs, defStyle); 37 | } 38 | 39 | /** 40 | * Formats the log data and prints it out to the LogView. 41 | * @param priority Log level of the data being logged. Verbose, Error, etc. 42 | * @param tag Tag for for the log data. Can be used to organize log statements. 43 | * @param msg The actual message to be logged. The actual message to be logged. 44 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 45 | * to extract and print useful information. 46 | */ 47 | @Override 48 | public void println(int priority, String tag, String msg, Throwable tr) { 49 | 50 | 51 | String priorityStr = null; 52 | 53 | // For the purposes of this View, we want to print the priority as readable text. 54 | switch(priority) { 55 | case android.util.Log.VERBOSE: 56 | priorityStr = "VERBOSE"; 57 | break; 58 | case android.util.Log.DEBUG: 59 | priorityStr = "DEBUG"; 60 | break; 61 | case android.util.Log.INFO: 62 | priorityStr = "INFO"; 63 | break; 64 | case android.util.Log.WARN: 65 | priorityStr = "WARN"; 66 | break; 67 | case android.util.Log.ERROR: 68 | priorityStr = "ERROR"; 69 | break; 70 | case android.util.Log.ASSERT: 71 | priorityStr = "ASSERT"; 72 | break; 73 | default: 74 | break; 75 | } 76 | 77 | // Handily, the Log class has a facility for converting a stack trace into a usable string. 78 | String exceptionStr = null; 79 | if (tr != null) { 80 | exceptionStr = android.util.Log.getStackTraceString(tr); 81 | } 82 | 83 | // Take the priority, tag, message, and exception, and concatenate as necessary 84 | // into one usable line of text. 85 | final StringBuilder outputBuilder = new StringBuilder(); 86 | 87 | String delimiter = "\t"; 88 | appendIfNotNull(outputBuilder, priorityStr, delimiter); 89 | appendIfNotNull(outputBuilder, tag, delimiter); 90 | appendIfNotNull(outputBuilder, msg, delimiter); 91 | appendIfNotNull(outputBuilder, exceptionStr, delimiter); 92 | 93 | // In case this was originally called from an AsyncTask or some other off-UI thread, 94 | // make sure the update occurs within the UI thread. 95 | ((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() { 96 | @Override 97 | public void run() { 98 | // Display the text we just generated within the LogView. 99 | appendToLog(outputBuilder.toString()); 100 | } 101 | }))); 102 | 103 | if (mNext != null) { 104 | mNext.println(priority, tag, msg, tr); 105 | } 106 | } 107 | 108 | public LogNode getNext() { 109 | return mNext; 110 | } 111 | 112 | public void setNext(LogNode node) { 113 | mNext = node; 114 | } 115 | 116 | /** Takes a string and adds to it, with a separator, if the bit to be added isn't null. Since 117 | * the logger takes so many arguments that might be null, this method helps cut out some of the 118 | * agonizing tedium of writing the same 3 lines over and over. 119 | * @param source StringBuilder containing the text to append to. 120 | * @param addStr The String to append 121 | * @param delimiter The String to separate the source and appended strings. A tab or comma, 122 | * for instance. 123 | * @return The fully concatenated String as a StringBuilder 124 | */ 125 | private StringBuilder appendIfNotNull(StringBuilder source, String addStr, String delimiter) { 126 | if (addStr != null) { 127 | if (addStr.length() == 0) { 128 | delimiter = ""; 129 | } 130 | 131 | return source.append(addStr).append(delimiter); 132 | } 133 | return source; 134 | } 135 | 136 | // The next LogNode in the chain. 137 | LogNode mNext; 138 | 139 | /** Outputs the string as a new line of log data in the LogView. */ 140 | public void appendToLog(String s) { 141 | append("\n" + s); 142 | } 143 | 144 | 145 | } 146 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/LogWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.common.logger; 17 | 18 | import android.util.Log; 19 | 20 | /** 21 | * Helper class which wraps Android's native Log utility in the Logger interface. This way 22 | * normal DDMS output can be one of the many targets receiving and outputting logs simultaneously. 23 | */ 24 | public class LogWrapper implements LogNode { 25 | 26 | // For piping: The next node to receive Log data after this one has done its work. 27 | private LogNode mNext; 28 | 29 | /** 30 | * Returns the next LogNode in the linked list. 31 | */ 32 | public LogNode getNext() { 33 | return mNext; 34 | } 35 | 36 | /** 37 | * Sets the LogNode data will be sent to.. 38 | */ 39 | public void setNext(LogNode node) { 40 | mNext = node; 41 | } 42 | 43 | /** 44 | * Prints data out to the console using Android's native log mechanism. 45 | * @param priority Log level of the data being logged. Verbose, Error, etc. 46 | * @param tag Tag for for the log data. Can be used to organize log statements. 47 | * @param msg The actual message to be logged. The actual message to be logged. 48 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 49 | * to extract and print useful information. 50 | */ 51 | @Override 52 | public void println(int priority, String tag, String msg, Throwable tr) { 53 | // There actually are log methods that don't take a msg parameter. For now, 54 | // if that's the case, just convert null to the empty string and move on. 55 | String useMsg = msg; 56 | if (useMsg == null) { 57 | useMsg = ""; 58 | } 59 | 60 | // If an exeption was provided, convert that exception to a usable string and attach 61 | // it to the end of the msg method. 62 | if (tr != null) { 63 | msg += "\n" + Log.getStackTraceString(tr); 64 | } 65 | 66 | // This is functionally identical to Log.x(tag, useMsg); 67 | // For instance, if priority were Log.VERBOSE, this would be the same as Log.v(tag, useMsg) 68 | Log.println(priority, tag, useMsg); 69 | 70 | // If this isn't the last node in the chain, move things along. 71 | if (mNext != null) { 72 | mNext.println(priority, tag, msg, tr); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/common/logger/MessageOnlyLogFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 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 com.example.android.common.logger; 17 | 18 | /** 19 | * Simple {@link LogNode} filter, removes everything except the message. 20 | * Useful for situations like on-screen log output where you don't want a lot of metadata displayed, 21 | * just easy-to-read message updates as they're happening. 22 | */ 23 | public class MessageOnlyLogFilter implements LogNode { 24 | 25 | LogNode mNext; 26 | 27 | /** 28 | * Takes the "next" LogNode as a parameter, to simplify chaining. 29 | * 30 | * @param next The next LogNode in the pipeline. 31 | */ 32 | public MessageOnlyLogFilter(LogNode next) { 33 | mNext = next; 34 | } 35 | 36 | public MessageOnlyLogFilter() { 37 | } 38 | 39 | @Override 40 | public void println(int priority, String tag, String msg, Throwable tr) { 41 | if (mNext != null) { 42 | getNext().println(Log.NONE, null, msg, null); 43 | } 44 | } 45 | 46 | /** 47 | * Returns the next LogNode in the chain. 48 | */ 49 | public LogNode getNext() { 50 | return mNext; 51 | } 52 | 53 | /** 54 | * Sets the LogNode data will be sent to.. 55 | */ 56 | public void setNext(LogNode node) { 57 | mNext = node; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/provider/Images.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.provider; 18 | 19 | /** 20 | * Some simple test data to use for this sample app. 21 | */ 22 | public class Images { 23 | 24 | /** 25 | * This are PicasaWeb URLs and could potentially change. Ideally the PicasaWeb API should be 26 | * used to fetch the URLs. 27 | * 28 | * Credit to Romain Guy for the photos: 29 | * http://www.curious-creature.org/ 30 | * https://plus.google.com/109538161516040592207/about 31 | * http://www.flickr.com/photos/romainguy 32 | */ 33 | public final static String[] imageUrls = new String[] { 34 | "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg", 35 | "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg", 36 | "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg", 37 | "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg", 38 | "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg", 39 | "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg", 40 | "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg", 41 | "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg", 42 | "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg", 43 | "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg", 44 | "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s1024/Caterpillar.jpg", 45 | "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s1024/Chess.jpg", 46 | "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s1024/Chihuly.jpg", 47 | "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s1024/Closed%252520Door.jpg", 48 | "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s1024/Colorado%252520River%252520Sunset.jpg", 49 | "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s1024/Colors%252520of%252520Autumn.jpg", 50 | "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s1024/Countryside.jpg", 51 | "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s1024/Death%252520Valley%252520-%252520Dunes.jpg", 52 | "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s1024/Delicate%252520Arch.jpg", 53 | "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s1024/Despair.jpg", 54 | "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s1024/Eagle%252520Fall%252520Sunrise.jpg", 55 | "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s1024/Electric%252520Storm.jpg", 56 | "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s1024/False%252520Kiva.jpg", 57 | "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s1024/Fitzgerald%252520Streaks.jpg", 58 | "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s1024/Foggy%252520Sunset.jpg", 59 | "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s1024/Frantic.jpg", 60 | "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s1024/Golden%252520Gate%252520Afternoon.jpg", 61 | "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s1024/Golden%252520Gate%252520Fog.jpg", 62 | "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s1024/Golden%252520Grass.jpg", 63 | "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s1024/Grand%252520Teton.jpg", 64 | "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s1024/Grass%252520Closeup.jpg", 65 | "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s1024/Green%252520Grass.jpg", 66 | "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s1024/Hanging%252520Leaf.jpg", 67 | "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s1024/Highway%2525201.jpg", 68 | "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s1024/Horseshoe%252520Bend%252520Sunset.jpg", 69 | "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s1024/Horseshoe%252520Bend.jpg", 70 | "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s1024/Into%252520the%252520Blue.jpg", 71 | "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s1024/Jelly%252520Fish%2525202.jpg", 72 | "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s1024/Jelly%252520Fish%2525203.jpg", 73 | "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s1024/Kauai.jpg", 74 | "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s1024/Kyoto%252520Sunset.jpg", 75 | "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s1024/Lake%252520Tahoe%252520Colors.jpg", 76 | "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s1024/Lava%252520from%252520the%252520Sky.jpg", 77 | "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s1024/Leica%25252050mm%252520Summilux.jpg", 78 | "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s1024/Leica%25252050mm%252520Summilux.jpg", 79 | "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s1024/Leica%252520M8%252520%252528Front%252529.jpg", 80 | "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s1024/Light%252520to%252520Sand.jpg", 81 | "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s1024/Little%252520Bit%252520of%252520Paradise.jpg", 82 | "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s1024/Lone%252520Pine%252520Sunset.jpg", 83 | "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s1024/Lonely%252520Rock.jpg", 84 | "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s1024/Longue%252520Vue.jpg", 85 | "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s1024/Look%252520Me%252520in%252520the%252520Eye.jpg", 86 | "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s1024/Lost%252520in%252520a%252520Field.jpg", 87 | "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s1024/Marshall%252520Beach%252520Sunset.jpg", 88 | "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s1024/Mono%252520Lake%252520Blue.jpg", 89 | "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s1024/Monument%252520Valley%252520Overlook.jpg", 90 | "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s1024/Moving%252520Rock.jpg", 91 | "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s1024/Napali%252520Coast.jpg", 92 | "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s1024/One%252520Wheel.jpg", 93 | "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s1024/Open%252520Sky.jpg", 94 | "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s1024/Orange%252520Sunset.jpg", 95 | "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s1024/Orchid.jpg", 96 | "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s1024/Over%252520there.jpg", 97 | "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s1024/Plumes.jpg", 98 | "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s1024/Rainbokeh.jpg", 99 | "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s1024/Rainbow.jpg", 100 | "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s1024/Rice%252520Fields.jpg", 101 | "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s1024/Rockaway%252520Fire%252520Sky.jpg", 102 | "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s1024/Rockaway%252520Flow.jpg", 103 | "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s1024/Rockaway%252520Sunset%252520Sky.jpg", 104 | "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s1024/Russian%252520Ridge%252520Sunset.jpg", 105 | "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s1024/Rust%252520Knot.jpg", 106 | "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s1024/Sailing%252520Stones.jpg", 107 | "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s1024/Seahorse.jpg", 108 | "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s1024/Shinjuku%252520Street.jpg", 109 | "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s1024/Sierra%252520Heavens.jpg", 110 | "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s1024/Sierra%252520Sunset.jpg", 111 | "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s1024/Sin%252520Lights.jpg", 112 | "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s1024/Starry%252520Lake.jpg", 113 | "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s1024/Starry%252520Night.jpg", 114 | "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s1024/Stream.jpg", 115 | "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s1024/Strip%252520Sunset.jpg", 116 | "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s1024/Sunset%252520Hills.jpg", 117 | "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s1024/Tenaya%252520Lake%2525202.jpg", 118 | "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s1024/Tenaya%252520Lake.jpg", 119 | "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s1024/The%252520Cave%252520BW.jpg", 120 | "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s1024/The%252520Fisherman.jpg", 121 | "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s1024/The%252520Night%252520is%252520Coming.jpg", 122 | "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s1024/The%252520Road.jpg", 123 | "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s1024/Tokyo%252520Heights.jpg", 124 | "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s1024/Tokyo%252520Highway.jpg", 125 | "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s1024/Tokyo%252520Smog.jpg", 126 | "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s1024/Tufa%252520at%252520Night.jpg", 127 | "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s1024/Valley%252520Sunset.jpg", 128 | "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s1024/Windmill%252520Sunrise.jpg", 129 | "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s1024/Windmill.jpg", 130 | "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s1024/Windmills.jpg", 131 | "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s1024/Yet%252520Another%252520Rockaway%252520Sunset.jpg", 132 | "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s1024/Yosemite%252520Tree.jpg", 133 | }; 134 | 135 | /** 136 | * This are PicasaWeb thumbnail URLs and could potentially change. Ideally the PicasaWeb API 137 | * should be used to fetch the URLs. 138 | * 139 | * Credit to Romain Guy for the photos: 140 | * http://www.curious-creature.org/ 141 | * https://plus.google.com/109538161516040592207/about 142 | * http://www.flickr.com/photos/romainguy 143 | */ 144 | public final static String[] imageThumbUrls = new String[] { 145 | "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s240-c/A%252520Photographer.jpg", 146 | "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s240-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg", 147 | "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s240-c/Another%252520Rockaway%252520Sunset.jpg", 148 | "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s240-c/Antelope%252520Butte.jpg", 149 | "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s240-c/Antelope%252520Hallway.jpg", 150 | "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s240-c/Antelope%252520Walls.jpg", 151 | "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s240-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg", 152 | "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s240-c/Backlit%252520Cloud.jpg", 153 | "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s240-c/Bee%252520and%252520Flower.jpg", 154 | "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s240-c/Bonzai%252520Rock%252520Sunset.jpg", 155 | "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s240-c/Caterpillar.jpg", 156 | "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s240-c/Chess.jpg", 157 | "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s240-c/Chihuly.jpg", 158 | "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s240-c/Closed%252520Door.jpg", 159 | "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s240-c/Colorado%252520River%252520Sunset.jpg", 160 | "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s240-c/Colors%252520of%252520Autumn.jpg", 161 | "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s240-c/Countryside.jpg", 162 | "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s240-c/Death%252520Valley%252520-%252520Dunes.jpg", 163 | "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s240-c/Delicate%252520Arch.jpg", 164 | "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s240-c/Despair.jpg", 165 | "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s240-c/Eagle%252520Fall%252520Sunrise.jpg", 166 | "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s240-c/Electric%252520Storm.jpg", 167 | "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s240-c/False%252520Kiva.jpg", 168 | "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s240-c/Fitzgerald%252520Streaks.jpg", 169 | "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s240-c/Foggy%252520Sunset.jpg", 170 | "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s240-c/Frantic.jpg", 171 | "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s240-c/Golden%252520Gate%252520Afternoon.jpg", 172 | "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s240-c/Golden%252520Gate%252520Fog.jpg", 173 | "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s240-c/Golden%252520Grass.jpg", 174 | "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s240-c/Grand%252520Teton.jpg", 175 | "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s240-c/Grass%252520Closeup.jpg", 176 | "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s240-c/Green%252520Grass.jpg", 177 | "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s240-c/Hanging%252520Leaf.jpg", 178 | "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s240-c/Highway%2525201.jpg", 179 | "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s240-c/Horseshoe%252520Bend%252520Sunset.jpg", 180 | "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s240-c/Horseshoe%252520Bend.jpg", 181 | "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s240-c/Into%252520the%252520Blue.jpg", 182 | "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s240-c/Jelly%252520Fish%2525202.jpg", 183 | "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s240-c/Jelly%252520Fish%2525203.jpg", 184 | "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s240-c/Kauai.jpg", 185 | "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s240-c/Kyoto%252520Sunset.jpg", 186 | "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s240-c/Lake%252520Tahoe%252520Colors.jpg", 187 | "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s240-c/Lava%252520from%252520the%252520Sky.jpg", 188 | "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s240-c/Leica%25252050mm%252520Summilux.jpg", 189 | "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s240-c/Leica%25252050mm%252520Summilux.jpg", 190 | "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s240-c/Leica%252520M8%252520%252528Front%252529.jpg", 191 | "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s240-c/Light%252520to%252520Sand.jpg", 192 | "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s240-c/Little%252520Bit%252520of%252520Paradise.jpg", 193 | "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s240-c/Lone%252520Pine%252520Sunset.jpg", 194 | "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s240-c/Lonely%252520Rock.jpg", 195 | "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s240-c/Longue%252520Vue.jpg", 196 | "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s240-c/Look%252520Me%252520in%252520the%252520Eye.jpg", 197 | "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s240-c/Lost%252520in%252520a%252520Field.jpg", 198 | "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s240-c/Marshall%252520Beach%252520Sunset.jpg", 199 | "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s240-c/Mono%252520Lake%252520Blue.jpg", 200 | "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s240-c/Monument%252520Valley%252520Overlook.jpg", 201 | "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s240-c/Moving%252520Rock.jpg", 202 | "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s240-c/Napali%252520Coast.jpg", 203 | "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s240-c/One%252520Wheel.jpg", 204 | "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s240-c/Open%252520Sky.jpg", 205 | "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s240-c/Orange%252520Sunset.jpg", 206 | "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s240-c/Orchid.jpg", 207 | "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s240-c/Over%252520there.jpg", 208 | "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s240-c/Plumes.jpg", 209 | "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s240-c/Rainbokeh.jpg", 210 | "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s240-c/Rainbow.jpg", 211 | "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s240-c/Rice%252520Fields.jpg", 212 | "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s240-c/Rockaway%252520Fire%252520Sky.jpg", 213 | "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s240-c/Rockaway%252520Flow.jpg", 214 | "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s240-c/Rockaway%252520Sunset%252520Sky.jpg", 215 | "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s240-c/Russian%252520Ridge%252520Sunset.jpg", 216 | "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s240-c/Rust%252520Knot.jpg", 217 | "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s240-c/Sailing%252520Stones.jpg", 218 | "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s240-c/Seahorse.jpg", 219 | "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s240-c/Shinjuku%252520Street.jpg", 220 | "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s240-c/Sierra%252520Heavens.jpg", 221 | "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s240-c/Sierra%252520Sunset.jpg", 222 | "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s240-c/Sin%252520Lights.jpg", 223 | "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s240-c/Starry%252520Lake.jpg", 224 | "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s240-c/Starry%252520Night.jpg", 225 | "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s240-c/Stream.jpg", 226 | "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s240-c/Strip%252520Sunset.jpg", 227 | "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s240-c/Sunset%252520Hills.jpg", 228 | "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s240-c/Tenaya%252520Lake%2525202.jpg", 229 | "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s240-c/Tenaya%252520Lake.jpg", 230 | "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s240-c/The%252520Cave%252520BW.jpg", 231 | "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s240-c/The%252520Fisherman.jpg", 232 | "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s240-c/The%252520Night%252520is%252520Coming.jpg", 233 | "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s240-c/The%252520Road.jpg", 234 | "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s240-c/Tokyo%252520Heights.jpg", 235 | "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s240-c/Tokyo%252520Highway.jpg", 236 | "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s240-c/Tokyo%252520Smog.jpg", 237 | "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s240-c/Tufa%252520at%252520Night.jpg", 238 | "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s240-c/Valley%252520Sunset.jpg", 239 | "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s240-c/Windmill%252520Sunrise.jpg", 240 | "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s240-c/Windmill.jpg", 241 | "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s240-c/Windmills.jpg", 242 | "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s240-c/Yet%252520Another%252520Rockaway%252520Sunset.jpg", 243 | "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s240-c/Yosemite%252520Tree.jpg", 244 | }; 245 | } 246 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/ui/ImageDetailActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.ui; 18 | 19 | import android.annotation.TargetApi; 20 | import android.app.ActionBar; 21 | import android.os.Build.VERSION_CODES; 22 | import android.os.Bundle; 23 | import android.support.v4.app.Fragment; 24 | import android.support.v4.app.FragmentActivity; 25 | import android.support.v4.app.FragmentManager; 26 | import android.support.v4.app.FragmentStatePagerAdapter; 27 | import android.support.v4.app.NavUtils; 28 | import android.support.v4.view.ViewPager; 29 | import android.util.DisplayMetrics; 30 | import android.view.Menu; 31 | import android.view.MenuItem; 32 | import android.view.View; 33 | import android.view.View.OnClickListener; 34 | import android.view.WindowManager.LayoutParams; 35 | import android.widget.Toast; 36 | 37 | import com.example.android.displayingbitmaps.BuildConfig; 38 | import com.example.android.displayingbitmaps.R; 39 | import com.example.android.displayingbitmaps.provider.Images; 40 | import com.example.android.displayingbitmaps.util.ImageCache; 41 | import com.example.android.displayingbitmaps.util.ImageFetcher; 42 | import com.example.android.displayingbitmaps.util.Utils; 43 | 44 | public class ImageDetailActivity extends FragmentActivity implements OnClickListener { 45 | private static final String IMAGE_CACHE_DIR = "images"; 46 | public static final String EXTRA_IMAGE = "extra_image"; 47 | 48 | private ImagePagerAdapter mAdapter; 49 | private ImageFetcher mImageFetcher; 50 | private ViewPager mPager; 51 | 52 | @TargetApi(VERSION_CODES.HONEYCOMB) 53 | @Override 54 | public void onCreate(Bundle savedInstanceState) { 55 | if (BuildConfig.DEBUG) { 56 | Utils.enableStrictMode(); 57 | } 58 | super.onCreate(savedInstanceState); 59 | setContentView(R.layout.image_detail_pager); 60 | 61 | // Fetch screen height and width, to use as our max size when loading images as this 62 | // activity runs full screen 63 | final DisplayMetrics displayMetrics = new DisplayMetrics(); 64 | getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); 65 | final int height = displayMetrics.heightPixels; 66 | final int width = displayMetrics.widthPixels; 67 | 68 | // For this sample we'll use half of the longest width to resize our images. As the 69 | // image scaling ensures the image is larger than this, we should be left with a 70 | // resolution that is appropriate for both portrait and landscape. For best image quality 71 | // we shouldn't divide by 2, but this will use more memory and require a larger memory 72 | // cache. 73 | final int longest = (height > width ? height : width) / 2; 74 | 75 | ImageCache.ImageCacheParams cacheParams = 76 | new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR); 77 | cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory 78 | 79 | // The ImageFetcher takes care of loading images into our ImageView children asynchronously 80 | mImageFetcher = new ImageFetcher(this, longest); 81 | mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams); 82 | mImageFetcher.setImageFadeIn(false); 83 | 84 | // Set up ViewPager and backing adapter 85 | mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), Images.imageUrls.length); 86 | mPager = (ViewPager) findViewById(R.id.pager); 87 | mPager.setAdapter(mAdapter); 88 | mPager.setPageMargin((int) getResources().getDimension(R.dimen.horizontal_page_margin)); 89 | mPager.setOffscreenPageLimit(2); 90 | 91 | // Set up activity to go full screen 92 | getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN); 93 | 94 | // Enable some additional newer visibility and ActionBar features to create a more 95 | // immersive photo viewing experience 96 | if (Utils.hasHoneycomb()) { 97 | final ActionBar actionBar = getActionBar(); 98 | 99 | // Hide title text and set home as up 100 | actionBar.setDisplayShowTitleEnabled(false); 101 | actionBar.setDisplayHomeAsUpEnabled(true); 102 | 103 | // Hide and show the ActionBar as the visibility changes 104 | mPager.setOnSystemUiVisibilityChangeListener( 105 | new View.OnSystemUiVisibilityChangeListener() { 106 | @Override 107 | public void onSystemUiVisibilityChange(int vis) { 108 | if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) { 109 | actionBar.hide(); 110 | } else { 111 | actionBar.show(); 112 | } 113 | } 114 | }); 115 | 116 | // Start low profile mode and hide ActionBar 117 | mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); 118 | actionBar.hide(); 119 | } 120 | 121 | // Set the current item based on the extra passed in to this activity 122 | final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1); 123 | if (extraCurrentItem != -1) { 124 | mPager.setCurrentItem(extraCurrentItem); 125 | } 126 | } 127 | 128 | @Override 129 | public void onResume() { 130 | super.onResume(); 131 | mImageFetcher.setExitTasksEarly(false); 132 | } 133 | 134 | @Override 135 | protected void onPause() { 136 | super.onPause(); 137 | mImageFetcher.setExitTasksEarly(true); 138 | mImageFetcher.flushCache(); 139 | } 140 | 141 | @Override 142 | protected void onDestroy() { 143 | super.onDestroy(); 144 | mImageFetcher.closeCache(); 145 | } 146 | 147 | @Override 148 | public boolean onOptionsItemSelected(MenuItem item) { 149 | switch (item.getItemId()) { 150 | case android.R.id.home: 151 | NavUtils.navigateUpFromSameTask(this); 152 | return true; 153 | case R.id.clear_cache: 154 | mImageFetcher.clearCache(); 155 | Toast.makeText( 156 | this, R.string.clear_cache_complete_toast,Toast.LENGTH_SHORT).show(); 157 | return true; 158 | } 159 | return super.onOptionsItemSelected(item); 160 | } 161 | 162 | @Override 163 | public boolean onCreateOptionsMenu(Menu menu) { 164 | getMenuInflater().inflate(R.menu.main_menu, menu); 165 | return true; 166 | } 167 | 168 | /** 169 | * Called by the ViewPager child fragments to load images via the one ImageFetcher 170 | */ 171 | public ImageFetcher getImageFetcher() { 172 | return mImageFetcher; 173 | } 174 | 175 | /** 176 | * The main adapter that backs the ViewPager. A subclass of FragmentStatePagerAdapter as there 177 | * could be a large number of items in the ViewPager and we don't want to retain them all in 178 | * memory at once but create/destroy them on the fly. 179 | */ 180 | private class ImagePagerAdapter extends FragmentStatePagerAdapter { 181 | private final int mSize; 182 | 183 | public ImagePagerAdapter(FragmentManager fm, int size) { 184 | super(fm); 185 | mSize = size; 186 | } 187 | 188 | @Override 189 | public int getCount() { 190 | return mSize; 191 | } 192 | 193 | @Override 194 | public Fragment getItem(int position) { 195 | return ImageDetailFragment.newInstance(Images.imageUrls[position]); 196 | } 197 | } 198 | 199 | /** 200 | * Set on the ImageView in the ViewPager children fragments, to enable/disable low profile mode 201 | * when the ImageView is touched. 202 | */ 203 | @TargetApi(VERSION_CODES.HONEYCOMB) 204 | @Override 205 | public void onClick(View v) { 206 | final int vis = mPager.getSystemUiVisibility(); 207 | if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) { 208 | mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); 209 | } else { 210 | mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/ui/ImageDetailFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.ui; 18 | 19 | import android.os.Bundle; 20 | import android.support.v4.app.Fragment; 21 | import android.view.LayoutInflater; 22 | import android.view.View; 23 | import android.view.View.OnClickListener; 24 | import android.view.ViewGroup; 25 | import android.widget.ImageView; 26 | 27 | import com.example.android.displayingbitmaps.R; 28 | import com.example.android.displayingbitmaps.util.ImageFetcher; 29 | import com.example.android.displayingbitmaps.util.ImageWorker; 30 | import com.example.android.displayingbitmaps.util.Utils; 31 | 32 | /** 33 | * This fragment will populate the children of the ViewPager from {@link ImageDetailActivity}. 34 | */ 35 | public class ImageDetailFragment extends Fragment { 36 | private static final String IMAGE_DATA_EXTRA = "extra_image_data"; 37 | private String mImageUrl; 38 | private ImageView mImageView; 39 | private ImageFetcher mImageFetcher; 40 | 41 | /** 42 | * Factory method to generate a new instance of the fragment given an image number. 43 | * 44 | * @param imageUrl The image url to load 45 | * @return A new instance of ImageDetailFragment with imageNum extras 46 | */ 47 | public static ImageDetailFragment newInstance(String imageUrl) { 48 | final ImageDetailFragment f = new ImageDetailFragment(); 49 | 50 | final Bundle args = new Bundle(); 51 | args.putString(IMAGE_DATA_EXTRA, imageUrl); 52 | f.setArguments(args); 53 | 54 | return f; 55 | } 56 | 57 | /** 58 | * Empty constructor as per the Fragment documentation 59 | */ 60 | public ImageDetailFragment() {} 61 | 62 | /** 63 | * Populate image using a url from extras, use the convenience factory method 64 | * {@link ImageDetailFragment#newInstance(String)} to create this fragment. 65 | */ 66 | @Override 67 | public void onCreate(Bundle savedInstanceState) { 68 | super.onCreate(savedInstanceState); 69 | mImageUrl = getArguments() != null ? getArguments().getString(IMAGE_DATA_EXTRA) : null; 70 | } 71 | 72 | @Override 73 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 74 | Bundle savedInstanceState) { 75 | // Inflate and locate the main ImageView 76 | final View v = inflater.inflate(R.layout.image_detail_fragment, container, false); 77 | mImageView = (ImageView) v.findViewById(R.id.imageView); 78 | return v; 79 | } 80 | 81 | @Override 82 | public void onActivityCreated(Bundle savedInstanceState) { 83 | super.onActivityCreated(savedInstanceState); 84 | 85 | // Use the parent activity to load the image asynchronously into the ImageView (so a single 86 | // cache can be used over all pages in the ViewPager 87 | if (ImageDetailActivity.class.isInstance(getActivity())) { 88 | mImageFetcher = ((ImageDetailActivity) getActivity()).getImageFetcher(); 89 | mImageFetcher.loadImage(mImageUrl, mImageView); 90 | } 91 | 92 | // Pass clicks on the ImageView to the parent activity to handle 93 | if (OnClickListener.class.isInstance(getActivity()) && Utils.hasHoneycomb()) { 94 | mImageView.setOnClickListener((OnClickListener) getActivity()); 95 | } 96 | } 97 | 98 | @Override 99 | public void onDestroy() { 100 | super.onDestroy(); 101 | if (mImageView != null) { 102 | // Cancel any pending image work 103 | ImageWorker.cancelWork(mImageView); 104 | mImageView.setImageDrawable(null); 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/ui/ImageGridActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.ui; 18 | 19 | import android.os.Bundle; 20 | import android.support.v4.app.FragmentActivity; 21 | import android.support.v4.app.FragmentTransaction; 22 | 23 | import org.deeplearning4j.datasets.iterator.DataSetIterator; 24 | import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator; 25 | import org.deeplearning4j.eval.Evaluation; 26 | import org.deeplearning4j.nn.api.OptimizationAlgorithm; 27 | import org.deeplearning4j.nn.conf.GradientNormalization; 28 | import org.deeplearning4j.nn.conf.MultiLayerConfiguration; 29 | import org.deeplearning4j.nn.conf.NeuralNetConfiguration; 30 | import org.deeplearning4j.nn.conf.layers.DenseLayer; 31 | import org.deeplearning4j.nn.conf.layers.OutputLayer; 32 | import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; 33 | import org.deeplearning4j.nn.weights.WeightInit; 34 | import org.deeplearning4j.optimize.api.IterationListener; 35 | import org.deeplearning4j.optimize.listeners.ScoreIterationListener; 36 | import org.nd4j.linalg.api.ndarray.INDArray; 37 | import org.nd4j.linalg.dataset.DataSet; 38 | import org.nd4j.linalg.dataset.SplitTestAndTrain; 39 | import org.nd4j.linalg.factory.Nd4j; 40 | import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction; 41 | import org.slf4j.Logger; 42 | import org.slf4j.LoggerFactory; 43 | 44 | import java.util.*; 45 | 46 | /** 47 | * Simple FragmentActivity to hold the main {@link ImageGridFragment} and not much else. 48 | */ 49 | public class ImageGridActivity extends FragmentActivity { 50 | private static final String TAG = "ImageGridActivity"; 51 | 52 | private static Logger log = LoggerFactory.getLogger(ImageGridActivity.class); 53 | 54 | @Override 55 | protected void onCreate(Bundle savedInstanceState) { 56 | // if (BuildConfig.DEBUG) { 57 | // Utils.enableStrictMode(); 58 | // } 59 | super.onCreate(savedInstanceState); 60 | 61 | if (getSupportFragmentManager().findFragmentByTag(TAG) == null) { 62 | final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 63 | ft.add(android.R.id.content, new ImageGridFragment(), TAG); 64 | ft.commit(); 65 | } 66 | 67 | try { 68 | trainMLP(); 69 | } catch (Exception e) { 70 | e.printStackTrace(); 71 | } 72 | } 73 | 74 | public void trainMLP() throws Exception { 75 | Nd4j.ENFORCE_NUMERICAL_STABILITY = true; 76 | final int numRows = 28; 77 | final int numColumns = 28; 78 | int outputNum = 10; 79 | int numSamples = 10000; 80 | int batchSize = 500; 81 | int iterations = 10; 82 | int seed = 123; 83 | int listenerFreq = iterations / 5; 84 | int splitTrainNum = (int) (batchSize * .8); 85 | DataSet mnist; 86 | SplitTestAndTrain trainTest; 87 | DataSet trainInput; 88 | List testInput = new ArrayList<>(); 89 | List testLabels = new ArrayList<>(); 90 | 91 | log.info("Load data...."); 92 | DataSetIterator mnistIter = new MnistDataSetIterator(batchSize, numSamples, true); 93 | 94 | log.info("Build model...."); 95 | MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() 96 | .seed(seed) 97 | .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) 98 | .iterations(iterations) 99 | .gradientNormalization(GradientNormalization.RenormalizeL2PerLayer) 100 | .learningRate(1e-1f) 101 | .momentum(0.5) 102 | .momentumAfter(Collections.singletonMap(3, 0.9)) 103 | .useDropConnect(true) 104 | .list(2) 105 | .layer(0, new DenseLayer.Builder() 106 | .nIn(numRows * numColumns) 107 | .nOut(1000) 108 | .activation("relu") 109 | .weightInit(WeightInit.XAVIER) 110 | .build()) 111 | .layer(1, new OutputLayer.Builder(LossFunction.NEGATIVELOGLIKELIHOOD) 112 | .nIn(1000) 113 | .nOut(outputNum) 114 | .activation("softmax") 115 | .weightInit(WeightInit.XAVIER) 116 | .build()) 117 | .build(); 118 | 119 | MultiLayerNetwork model = new MultiLayerNetwork(conf); 120 | model.init(); 121 | model.setListeners(Arrays.asList((IterationListener) new ScoreIterationListener(listenerFreq))); 122 | 123 | log.info("Train model...."); 124 | model.setListeners(Arrays.asList((IterationListener) new ScoreIterationListener(listenerFreq))); 125 | while (mnistIter.hasNext()) { 126 | mnist = mnistIter.next(); 127 | trainTest = mnist.splitTestAndTrain(splitTrainNum, new Random(seed)); // train set that is the result 128 | trainInput = trainTest.getTrain(); // get feature matrix and labels for training 129 | testInput.add(trainTest.getTest().getFeatureMatrix()); 130 | testLabels.add(trainTest.getTest().getLabels()); 131 | model.fit(trainInput); 132 | } 133 | 134 | log.info("Evaluate model...."); 135 | Evaluation eval = new Evaluation(outputNum); 136 | for (int i = 0; i < testInput.size(); i++) { 137 | INDArray output = model.output(testInput.get(i)); 138 | eval.eval(testLabels.get(i), output); 139 | } 140 | 141 | log.info(eval.stats()); 142 | log.info("****************Example finished********************"); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/ui/ImageGridFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.ui; 18 | 19 | import android.annotation.TargetApi; 20 | import android.app.ActivityOptions; 21 | import android.content.Context; 22 | import android.content.Intent; 23 | import android.os.Build.VERSION_CODES; 24 | import android.os.Bundle; 25 | import android.support.v4.app.Fragment; 26 | import android.util.TypedValue; 27 | import android.view.LayoutInflater; 28 | import android.view.Menu; 29 | import android.view.MenuInflater; 30 | import android.view.MenuItem; 31 | import android.view.View; 32 | import android.view.ViewGroup; 33 | import android.view.ViewGroup.LayoutParams; 34 | import android.view.ViewTreeObserver; 35 | import android.widget.AbsListView; 36 | import android.widget.AdapterView; 37 | import android.widget.BaseAdapter; 38 | import android.widget.GridView; 39 | import android.widget.ImageView; 40 | import android.widget.Toast; 41 | 42 | import com.example.android.common.logger.Log; 43 | import com.example.android.displayingbitmaps.BuildConfig; 44 | import com.example.android.displayingbitmaps.R; 45 | import com.example.android.displayingbitmaps.provider.Images; 46 | import com.example.android.displayingbitmaps.util.ImageCache; 47 | import com.example.android.displayingbitmaps.util.ImageFetcher; 48 | import com.example.android.displayingbitmaps.util.Utils; 49 | 50 | /** 51 | * The main fragment that powers the ImageGridActivity screen. Fairly straight forward GridView 52 | * implementation with the key addition being the ImageWorker class w/ImageCache to load children 53 | * asynchronously, keeping the UI nice and smooth and caching thumbnails for quick retrieval. The 54 | * cache is retained over configuration changes like orientation change so the images are populated 55 | * quickly if, for example, the user rotates the device. 56 | */ 57 | public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener { 58 | private static final String TAG = "ImageGridFragment"; 59 | private static final String IMAGE_CACHE_DIR = "thumbs"; 60 | 61 | private int mImageThumbSize; 62 | private int mImageThumbSpacing; 63 | private ImageAdapter mAdapter; 64 | private ImageFetcher mImageFetcher; 65 | 66 | /** 67 | * Empty constructor as per the Fragment documentation 68 | */ 69 | public ImageGridFragment() {} 70 | 71 | @Override 72 | public void onCreate(Bundle savedInstanceState) { 73 | super.onCreate(savedInstanceState); 74 | setHasOptionsMenu(true); 75 | 76 | mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size); 77 | mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing); 78 | 79 | mAdapter = new ImageAdapter(getActivity()); 80 | 81 | ImageCache.ImageCacheParams cacheParams = 82 | new ImageCache.ImageCacheParams(getActivity(), IMAGE_CACHE_DIR); 83 | 84 | cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory 85 | 86 | // The ImageFetcher takes care of loading images into our ImageView children asynchronously 87 | mImageFetcher = new ImageFetcher(getActivity(), mImageThumbSize); 88 | mImageFetcher.setLoadingImage(R.drawable.empty_photo); 89 | mImageFetcher.addImageCache(getActivity().getSupportFragmentManager(), cacheParams); 90 | } 91 | 92 | @Override 93 | public View onCreateView( 94 | LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 95 | 96 | final View v = inflater.inflate(R.layout.image_grid_fragment, container, false); 97 | final GridView mGridView = (GridView) v.findViewById(R.id.gridView); 98 | mGridView.setAdapter(mAdapter); 99 | mGridView.setOnItemClickListener(this); 100 | mGridView.setOnScrollListener(new AbsListView.OnScrollListener() { 101 | @Override 102 | public void onScrollStateChanged(AbsListView absListView, int scrollState) { 103 | // Pause fetcher to ensure smoother scrolling when flinging 104 | if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { 105 | // Before Honeycomb pause image loading on scroll to help with performance 106 | if (!Utils.hasHoneycomb()) { 107 | mImageFetcher.setPauseWork(true); 108 | } 109 | } else { 110 | mImageFetcher.setPauseWork(false); 111 | } 112 | } 113 | 114 | @Override 115 | public void onScroll(AbsListView absListView, int firstVisibleItem, 116 | int visibleItemCount, int totalItemCount) { 117 | } 118 | }); 119 | 120 | // This listener is used to get the final width of the GridView and then calculate the 121 | // number of columns and the width of each column. The width of each column is variable 122 | // as the GridView has stretchMode=columnWidth. The column width is used to set the height 123 | // of each view so we get nice square thumbnails. 124 | mGridView.getViewTreeObserver().addOnGlobalLayoutListener( 125 | new ViewTreeObserver.OnGlobalLayoutListener() { 126 | @TargetApi(VERSION_CODES.JELLY_BEAN) 127 | @Override 128 | public void onGlobalLayout() { 129 | if (mAdapter.getNumColumns() == 0) { 130 | final int numColumns = (int) Math.floor( 131 | mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing)); 132 | if (numColumns > 0) { 133 | final int columnWidth = 134 | (mGridView.getWidth() / numColumns) - mImageThumbSpacing; 135 | mAdapter.setNumColumns(numColumns); 136 | mAdapter.setItemHeight(columnWidth); 137 | if (BuildConfig.DEBUG) { 138 | Log.d(TAG, "onCreateView - numColumns set to " + numColumns); 139 | } 140 | if (Utils.hasJellyBean()) { 141 | mGridView.getViewTreeObserver() 142 | .removeOnGlobalLayoutListener(this); 143 | } else { 144 | mGridView.getViewTreeObserver() 145 | .removeGlobalOnLayoutListener(this); 146 | } 147 | } 148 | } 149 | } 150 | }); 151 | 152 | return v; 153 | } 154 | 155 | @Override 156 | public void onResume() { 157 | super.onResume(); 158 | mImageFetcher.setExitTasksEarly(false); 159 | mAdapter.notifyDataSetChanged(); 160 | } 161 | 162 | @Override 163 | public void onPause() { 164 | super.onPause(); 165 | mImageFetcher.setPauseWork(false); 166 | mImageFetcher.setExitTasksEarly(true); 167 | mImageFetcher.flushCache(); 168 | } 169 | 170 | @Override 171 | public void onDestroy() { 172 | super.onDestroy(); 173 | mImageFetcher.closeCache(); 174 | } 175 | 176 | @TargetApi(VERSION_CODES.JELLY_BEAN) 177 | @Override 178 | public void onItemClick(AdapterView parent, View v, int position, long id) { 179 | final Intent i = new Intent(getActivity(), ImageDetailActivity.class); 180 | i.putExtra(ImageDetailActivity.EXTRA_IMAGE, (int) id); 181 | if (Utils.hasJellyBean()) { 182 | // makeThumbnailScaleUpAnimation() looks kind of ugly here as the loading spinner may 183 | // show plus the thumbnail image in GridView is cropped. so using 184 | // makeScaleUpAnimation() instead. 185 | ActivityOptions options = 186 | ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()); 187 | getActivity().startActivity(i, options.toBundle()); 188 | } else { 189 | startActivity(i); 190 | } 191 | } 192 | 193 | @Override 194 | public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 195 | inflater.inflate(R.menu.main_menu, menu); 196 | } 197 | 198 | @Override 199 | public boolean onOptionsItemSelected(MenuItem item) { 200 | switch (item.getItemId()) { 201 | case R.id.clear_cache: 202 | mImageFetcher.clearCache(); 203 | Toast.makeText(getActivity(), R.string.clear_cache_complete_toast, 204 | Toast.LENGTH_SHORT).show(); 205 | return true; 206 | } 207 | return super.onOptionsItemSelected(item); 208 | } 209 | 210 | /** 211 | * The main adapter that backs the GridView. This is fairly standard except the number of 212 | * columns in the GridView is used to create a fake top row of empty views as we use a 213 | * transparent ActionBar and don't want the real top row of images to start off covered by it. 214 | */ 215 | private class ImageAdapter extends BaseAdapter { 216 | 217 | private final Context mContext; 218 | private int mItemHeight = 0; 219 | private int mNumColumns = 0; 220 | private int mActionBarHeight = 0; 221 | private GridView.LayoutParams mImageViewLayoutParams; 222 | 223 | public ImageAdapter(Context context) { 224 | super(); 225 | mContext = context; 226 | mImageViewLayoutParams = new GridView.LayoutParams( 227 | LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 228 | // Calculate ActionBar height 229 | TypedValue tv = new TypedValue(); 230 | if (context.getTheme().resolveAttribute( 231 | android.R.attr.actionBarSize, tv, true)) { 232 | mActionBarHeight = TypedValue.complexToDimensionPixelSize( 233 | tv.data, context.getResources().getDisplayMetrics()); 234 | } 235 | } 236 | 237 | @Override 238 | public int getCount() { 239 | // If columns have yet to be determined, return no items 240 | if (getNumColumns() == 0) { 241 | return 0; 242 | } 243 | 244 | // Size + number of columns for top empty row 245 | return Images.imageThumbUrls.length + mNumColumns; 246 | } 247 | 248 | @Override 249 | public Object getItem(int position) { 250 | return position < mNumColumns ? 251 | null : Images.imageThumbUrls[position - mNumColumns]; 252 | } 253 | 254 | @Override 255 | public long getItemId(int position) { 256 | return position < mNumColumns ? 0 : position - mNumColumns; 257 | } 258 | 259 | @Override 260 | public int getViewTypeCount() { 261 | // Two types of views, the normal ImageView and the top row of empty views 262 | return 2; 263 | } 264 | 265 | @Override 266 | public int getItemViewType(int position) { 267 | return (position < mNumColumns) ? 1 : 0; 268 | } 269 | 270 | @Override 271 | public boolean hasStableIds() { 272 | return true; 273 | } 274 | 275 | @Override 276 | public View getView(int position, View convertView, ViewGroup container) { 277 | 278 | // First check if this is the top row 279 | if (position < mNumColumns) { 280 | if (convertView == null) { 281 | convertView = new View(mContext); 282 | } 283 | // Set empty view with height of ActionBar 284 | convertView.setLayoutParams(new AbsListView.LayoutParams( 285 | LayoutParams.MATCH_PARENT, mActionBarHeight)); 286 | return convertView; 287 | } 288 | 289 | // Now handle the main ImageView thumbnails 290 | ImageView imageView; 291 | if (convertView == null) { // if it's not recycled, instantiate and initialize 292 | imageView = new RecyclingImageView(mContext); 293 | imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 294 | imageView.setLayoutParams(mImageViewLayoutParams); 295 | } else { // Otherwise re-use the converted view 296 | imageView = (ImageView) convertView; 297 | } 298 | 299 | // Check the height matches our calculated column width 300 | if (imageView.getLayoutParams().height != mItemHeight) { 301 | imageView.setLayoutParams(mImageViewLayoutParams); 302 | } 303 | 304 | // Finally load the image asynchronously into the ImageView, this also takes care of 305 | // setting a placeholder image while the background thread runs 306 | mImageFetcher.loadImage(Images.imageThumbUrls[position - mNumColumns], imageView); 307 | return imageView; 308 | 309 | } 310 | 311 | /** 312 | * Sets the item height. Useful for when we know the column width so the height can be set 313 | * to match. 314 | * 315 | * @param height 316 | */ 317 | public void setItemHeight(int height) { 318 | if (height == mItemHeight) { 319 | return; 320 | } 321 | mItemHeight = height; 322 | mImageViewLayoutParams = 323 | new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight); 324 | mImageFetcher.setImageSize(height); 325 | notifyDataSetChanged(); 326 | } 327 | 328 | public void setNumColumns(int numColumns) { 329 | mNumColumns = numColumns; 330 | } 331 | 332 | public int getNumColumns() { 333 | return mNumColumns; 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/ui/RecyclingImageView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 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 com.example.android.displayingbitmaps.ui; 18 | 19 | import android.content.Context; 20 | import android.graphics.drawable.Drawable; 21 | import android.graphics.drawable.LayerDrawable; 22 | import android.util.AttributeSet; 23 | import android.widget.ImageView; 24 | 25 | import com.example.android.displayingbitmaps.util.RecyclingBitmapDrawable; 26 | 27 | /** 28 | * Sub-class of ImageView which automatically notifies the drawable when it is 29 | * being displayed. 30 | */ 31 | public class RecyclingImageView extends ImageView { 32 | 33 | public RecyclingImageView(Context context) { 34 | super(context); 35 | } 36 | 37 | public RecyclingImageView(Context context, AttributeSet attrs) { 38 | super(context, attrs); 39 | } 40 | 41 | /** 42 | * @see android.widget.ImageView#onDetachedFromWindow() 43 | */ 44 | @Override 45 | protected void onDetachedFromWindow() { 46 | // This has been detached from Window, so clear the drawable 47 | setImageDrawable(null); 48 | 49 | super.onDetachedFromWindow(); 50 | } 51 | 52 | /** 53 | * @see android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable) 54 | */ 55 | @Override 56 | public void setImageDrawable(Drawable drawable) { 57 | // Keep hold of previous Drawable 58 | final Drawable previousDrawable = getDrawable(); 59 | 60 | // Call super to set new Drawable 61 | super.setImageDrawable(drawable); 62 | 63 | // Notify new Drawable that it is being displayed 64 | notifyDrawable(drawable, true); 65 | 66 | // Notify old Drawable so it is no longer being displayed 67 | notifyDrawable(previousDrawable, false); 68 | } 69 | 70 | /** 71 | * Notifies the drawable that it's displayed state has changed. 72 | * 73 | * @param drawable 74 | * @param isDisplayed 75 | */ 76 | private static void notifyDrawable(Drawable drawable, final boolean isDisplayed) { 77 | if (drawable instanceof RecyclingBitmapDrawable) { 78 | // The drawable is a CountingBitmapDrawable, so notify it 79 | ((RecyclingBitmapDrawable) drawable).setIsDisplayed(isDisplayed); 80 | } else if (drawable instanceof LayerDrawable) { 81 | // The drawable is a LayerDrawable, so recurse on each layer 82 | LayerDrawable layerDrawable = (LayerDrawable) drawable; 83 | for (int i = 0, z = layerDrawable.getNumberOfLayers(); i < z; i++) { 84 | notifyDrawable(layerDrawable.getDrawable(i), isDisplayed); 85 | } 86 | } 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/AsyncTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 The Android Open Source Project 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 com.example.android.displayingbitmaps.util; 18 | 19 | import android.annotation.TargetApi; 20 | import android.os.Handler; 21 | import android.os.Message; 22 | import android.os.Process; 23 | 24 | import java.util.ArrayDeque; 25 | import java.util.concurrent.BlockingQueue; 26 | import java.util.concurrent.Callable; 27 | import java.util.concurrent.CancellationException; 28 | import java.util.concurrent.ExecutionException; 29 | import java.util.concurrent.Executor; 30 | import java.util.concurrent.Executors; 31 | import java.util.concurrent.FutureTask; 32 | import java.util.concurrent.LinkedBlockingQueue; 33 | import java.util.concurrent.ThreadFactory; 34 | import java.util.concurrent.ThreadPoolExecutor; 35 | import java.util.concurrent.TimeUnit; 36 | import java.util.concurrent.TimeoutException; 37 | import java.util.concurrent.atomic.AtomicBoolean; 38 | import java.util.concurrent.atomic.AtomicInteger; 39 | 40 | /** 41 | * ************************************* 42 | * Copied from JB release framework: 43 | * https://android.googlesource.com/platform/frameworks/base/+/jb-release/core/java/android/os/AsyncTask.java 44 | * 45 | * so that threading behavior on all OS versions is the same and we can tweak behavior by using 46 | * executeOnExecutor() if needed. 47 | * 48 | * There are 3 changes in this copy of AsyncTask: 49 | * -pre-HC a single thread executor is used for serial operation 50 | * (Executors.newSingleThreadExecutor) and is the default 51 | * -the default THREAD_POOL_EXECUTOR was changed to use DiscardOldestPolicy 52 | * -a new fixed thread pool called DUAL_THREAD_EXECUTOR was added 53 | * ************************************* 54 | * 55 | *

AsyncTask enables proper and easy use of the UI thread. This class allows to 56 | * perform background operations and publish results on the UI thread without 57 | * having to manipulate threads and/or handlers.

58 | * 59 | *

AsyncTask is designed to be a helper class around {@link Thread} and {@link android.os.Handler} 60 | * and does not constitute a generic threading framework. AsyncTasks should ideally be 61 | * used for short operations (a few seconds at the most.) If you need to keep threads 62 | * running for long periods of time, it is highly recommended you use the various APIs 63 | * provided by the java.util.concurrent pacakge such as {@link java.util.concurrent.Executor}, 64 | * {@link java.util.concurrent.ThreadPoolExecutor} and {@link java.util.concurrent.FutureTask}.

65 | * 66 | *

An asynchronous task is defined by a computation that runs on a background thread and 67 | * whose result is published on the UI thread. An asynchronous task is defined by 3 generic 68 | * types, called Params, Progress and Result, 69 | * and 4 steps, called onPreExecute, doInBackground, 70 | * onProgressUpdate and onPostExecute.

71 | * 72 | *
73 | *

Developer Guides

74 | *

For more information about using tasks and threads, read the 75 | * Processes and 76 | * Threads developer guide.

77 | *
78 | * 79 | *

Usage

80 | *

AsyncTask must be subclassed to be used. The subclass will override at least 81 | * one method ({@link #doInBackground}), and most often will override a 82 | * second one ({@link #onPostExecute}.)

83 | * 84 | *

Here is an example of subclassing:

85 | *
 86 |  * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 87 |  *     protected Long doInBackground(URL... urls) {
 88 |  *         int count = urls.length;
 89 |  *         long totalSize = 0;
 90 |  *         for (int i = 0; i < count; i++) {
 91 |  *             totalSize += Downloader.downloadFile(urls[i]);
 92 |  *             publishProgress((int) ((i / (float) count) * 100));
 93 |  *             // Escape early if cancel() is called
 94 |  *             if (isCancelled()) break;
 95 |  *         }
 96 |  *         return totalSize;
 97 |  *     }
 98 |  *
 99 |  *     protected void onProgressUpdate(Integer... progress) {
100 |  *         setProgressPercent(progress[0]);
101 |  *     }
102 |  *
103 |  *     protected void onPostExecute(Long result) {
104 |  *         showDialog("Downloaded " + result + " bytes");
105 |  *     }
106 |  * }
107 |  * 
108 | * 109 | *

Once created, a task is executed very simply:

110 | *
111 |  * new DownloadFilesTask().execute(url1, url2, url3);
112 |  * 
113 | * 114 | *

AsyncTask's generic types

115 | *

The three types used by an asynchronous task are the following:

116 | *
    117 | *
  1. Params, the type of the parameters sent to the task upon 118 | * execution.
  2. 119 | *
  3. Progress, the type of the progress units published during 120 | * the background computation.
  4. 121 | *
  5. Result, the type of the result of the background 122 | * computation.
  6. 123 | *
124 | *

Not all types are always used by an asynchronous task. To mark a type as unused, 125 | * simply use the type {@link Void}:

126 | *
127 |  * private class MyTask extends AsyncTask<Void, Void, Void> { ... }
128 |  * 
129 | * 130 | *

The 4 steps

131 | *

When an asynchronous task is executed, the task goes through 4 steps:

132 | *
    133 | *
  1. {@link #onPreExecute()}, invoked on the UI thread immediately after the task 134 | * is executed. This step is normally used to setup the task, for instance by 135 | * showing a progress bar in the user interface.
  2. 136 | *
  3. {@link #doInBackground}, invoked on the background thread 137 | * immediately after {@link #onPreExecute()} finishes executing. This step is used 138 | * to perform background computation that can take a long time. The parameters 139 | * of the asynchronous task are passed to this step. The result of the computation must 140 | * be returned by this step and will be passed back to the last step. This step 141 | * can also use {@link #publishProgress} to publish one or more units 142 | * of progress. These values are published on the UI thread, in the 143 | * {@link #onProgressUpdate} step.
  4. 144 | *
  5. {@link #onProgressUpdate}, invoked on the UI thread after a 145 | * call to {@link #publishProgress}. The timing of the execution is 146 | * undefined. This method is used to display any form of progress in the user 147 | * interface while the background computation is still executing. For instance, 148 | * it can be used to animate a progress bar or show logs in a text field.
  6. 149 | *
  7. {@link #onPostExecute}, invoked on the UI thread after the background 150 | * computation finishes. The result of the background computation is passed to 151 | * this step as a parameter.
  8. 152 | *
153 | * 154 | *

Cancelling a task

155 | *

A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking 156 | * this method will cause subsequent calls to {@link #isCancelled()} to return true. 157 | * After invoking this method, {@link #onCancelled(Object)}, instead of 158 | * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} 159 | * returns. To ensure that a task is cancelled as quickly as possible, you should always 160 | * check the return value of {@link #isCancelled()} periodically from 161 | * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)

162 | * 163 | *

Threading rules

164 | *

There are a few threading rules that must be followed for this class to 165 | * work properly:

166 | * 176 | * 177 | *

Memory observability

178 | *

AsyncTask guarantees that all callback calls are synchronized in such a way that the following 179 | * operations are safe without explicit synchronizations.

180 | * 186 | * 187 | *

Order of execution

188 | *

When first introduced, AsyncTasks were executed serially on a single background 189 | * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed 190 | * to a pool of threads allowing multiple tasks to operate in parallel. Starting with 191 | * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single 192 | * thread to avoid common application errors caused by parallel execution.

193 | *

If you truly want parallel execution, you can invoke 194 | * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with 195 | * {@link #THREAD_POOL_EXECUTOR}.

196 | */ 197 | public abstract class AsyncTask { 198 | private static final String LOG_TAG = "AsyncTask"; 199 | 200 | private static final int CORE_POOL_SIZE = 5; 201 | private static final int MAXIMUM_POOL_SIZE = 128; 202 | private static final int KEEP_ALIVE = 1; 203 | 204 | private static final ThreadFactory sThreadFactory = new ThreadFactory() { 205 | private final AtomicInteger mCount = new AtomicInteger(1); 206 | 207 | public Thread newThread(Runnable r) { 208 | return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); 209 | } 210 | }; 211 | 212 | private static final BlockingQueue sPoolWorkQueue = 213 | new LinkedBlockingQueue(10); 214 | 215 | /** 216 | * An {@link java.util.concurrent.Executor} that can be used to execute tasks in parallel. 217 | */ 218 | public static final Executor THREAD_POOL_EXECUTOR 219 | = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 220 | TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory, 221 | new ThreadPoolExecutor.DiscardOldestPolicy()); 222 | 223 | /** 224 | * An {@link java.util.concurrent.Executor} that executes tasks one at a time in serial 225 | * order. This serialization is global to a particular process. 226 | */ 227 | public static final Executor SERIAL_EXECUTOR = Utils.hasHoneycomb() ? new SerialExecutor() : 228 | Executors.newSingleThreadExecutor(sThreadFactory); 229 | 230 | public static final Executor DUAL_THREAD_EXECUTOR = 231 | Executors.newFixedThreadPool(2, sThreadFactory); 232 | 233 | private static final int MESSAGE_POST_RESULT = 0x1; 234 | private static final int MESSAGE_POST_PROGRESS = 0x2; 235 | 236 | private static final InternalHandler sHandler = new InternalHandler(); 237 | 238 | private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; 239 | private final WorkerRunnable mWorker; 240 | private final FutureTask mFuture; 241 | 242 | private volatile Status mStatus = Status.PENDING; 243 | 244 | private final AtomicBoolean mCancelled = new AtomicBoolean(); 245 | private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); 246 | 247 | @TargetApi(11) 248 | private static class SerialExecutor implements Executor { 249 | final ArrayDeque mTasks = new ArrayDeque(); 250 | Runnable mActive; 251 | 252 | public synchronized void execute(final Runnable r) { 253 | mTasks.offer(new Runnable() { 254 | public void run() { 255 | try { 256 | r.run(); 257 | } finally { 258 | scheduleNext(); 259 | } 260 | } 261 | }); 262 | if (mActive == null) { 263 | scheduleNext(); 264 | } 265 | } 266 | 267 | protected synchronized void scheduleNext() { 268 | if ((mActive = mTasks.poll()) != null) { 269 | THREAD_POOL_EXECUTOR.execute(mActive); 270 | } 271 | } 272 | } 273 | 274 | /** 275 | * Indicates the current status of the task. Each status will be set only once 276 | * during the lifetime of a task. 277 | */ 278 | public enum Status { 279 | /** 280 | * Indicates that the task has not been executed yet. 281 | */ 282 | PENDING, 283 | /** 284 | * Indicates that the task is running. 285 | */ 286 | RUNNING, 287 | /** 288 | * Indicates that {@link AsyncTask#onPostExecute} has finished. 289 | */ 290 | FINISHED, 291 | } 292 | 293 | /** @hide Used to force static handler to be created. */ 294 | public static void init() { 295 | sHandler.getLooper(); 296 | } 297 | 298 | /** @hide */ 299 | public static void setDefaultExecutor(Executor exec) { 300 | sDefaultExecutor = exec; 301 | } 302 | 303 | /** 304 | * Creates a new asynchronous task. This constructor must be invoked on the UI thread. 305 | */ 306 | public AsyncTask() { 307 | mWorker = new WorkerRunnable() { 308 | public Result call() throws Exception { 309 | mTaskInvoked.set(true); 310 | 311 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 312 | //noinspection unchecked 313 | return postResult(doInBackground(mParams)); 314 | } 315 | }; 316 | 317 | mFuture = new FutureTask(mWorker) { 318 | @Override 319 | protected void done() { 320 | try { 321 | postResultIfNotInvoked(get()); 322 | } catch (InterruptedException e) { 323 | android.util.Log.w(LOG_TAG, e); 324 | } catch (ExecutionException e) { 325 | throw new RuntimeException("An error occured while executing doInBackground()", 326 | e.getCause()); 327 | } catch (CancellationException e) { 328 | postResultIfNotInvoked(null); 329 | } 330 | } 331 | }; 332 | } 333 | 334 | private void postResultIfNotInvoked(Result result) { 335 | final boolean wasTaskInvoked = mTaskInvoked.get(); 336 | if (!wasTaskInvoked) { 337 | postResult(result); 338 | } 339 | } 340 | 341 | private Result postResult(Result result) { 342 | @SuppressWarnings("unchecked") 343 | Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, 344 | new AsyncTaskResult(this, result)); 345 | message.sendToTarget(); 346 | return result; 347 | } 348 | 349 | /** 350 | * Returns the current status of this task. 351 | * 352 | * @return The current status. 353 | */ 354 | public final Status getStatus() { 355 | return mStatus; 356 | } 357 | 358 | /** 359 | * Override this method to perform a computation on a background thread. The 360 | * specified parameters are the parameters passed to {@link #execute} 361 | * by the caller of this task. 362 | * 363 | * This method can call {@link #publishProgress} to publish updates 364 | * on the UI thread. 365 | * 366 | * @param params The parameters of the task. 367 | * 368 | * @return A result, defined by the subclass of this task. 369 | * 370 | * @see #onPreExecute() 371 | * @see #onPostExecute 372 | * @see #publishProgress 373 | */ 374 | protected abstract Result doInBackground(Params... params); 375 | 376 | /** 377 | * Runs on the UI thread before {@link #doInBackground}. 378 | * 379 | * @see #onPostExecute 380 | * @see #doInBackground 381 | */ 382 | protected void onPreExecute() { 383 | } 384 | 385 | /** 386 | *

Runs on the UI thread after {@link #doInBackground}. The 387 | * specified result is the value returned by {@link #doInBackground}.

388 | * 389 | *

This method won't be invoked if the task was cancelled.

390 | * 391 | * @param result The result of the operation computed by {@link #doInBackground}. 392 | * 393 | * @see #onPreExecute 394 | * @see #doInBackground 395 | * @see #onCancelled(Object) 396 | */ 397 | @SuppressWarnings({"UnusedDeclaration"}) 398 | protected void onPostExecute(Result result) { 399 | } 400 | 401 | /** 402 | * Runs on the UI thread after {@link #publishProgress} is invoked. 403 | * The specified values are the values passed to {@link #publishProgress}. 404 | * 405 | * @param values The values indicating progress. 406 | * 407 | * @see #publishProgress 408 | * @see #doInBackground 409 | */ 410 | @SuppressWarnings({"UnusedDeclaration"}) 411 | protected void onProgressUpdate(Progress... values) { 412 | } 413 | 414 | /** 415 | *

Runs on the UI thread after {@link #cancel(boolean)} is invoked and 416 | * {@link #doInBackground(Object[])} has finished.

417 | * 418 | *

The default implementation simply invokes {@link #onCancelled()} and 419 | * ignores the result. If you write your own implementation, do not call 420 | * super.onCancelled(result).

421 | * 422 | * @param result The result, if any, computed in 423 | * {@link #doInBackground(Object[])}, can be null 424 | * 425 | * @see #cancel(boolean) 426 | * @see #isCancelled() 427 | */ 428 | @SuppressWarnings({"UnusedParameters"}) 429 | protected void onCancelled(Result result) { 430 | onCancelled(); 431 | } 432 | 433 | /** 434 | *

Applications should preferably override {@link #onCancelled(Object)}. 435 | * This method is invoked by the default implementation of 436 | * {@link #onCancelled(Object)}.

437 | * 438 | *

Runs on the UI thread after {@link #cancel(boolean)} is invoked and 439 | * {@link #doInBackground(Object[])} has finished.

440 | * 441 | * @see #onCancelled(Object) 442 | * @see #cancel(boolean) 443 | * @see #isCancelled() 444 | */ 445 | protected void onCancelled() { 446 | } 447 | 448 | /** 449 | * Returns true if this task was cancelled before it completed 450 | * normally. If you are calling {@link #cancel(boolean)} on the task, 451 | * the value returned by this method should be checked periodically from 452 | * {@link #doInBackground(Object[])} to end the task as soon as possible. 453 | * 454 | * @return true if task was cancelled before it completed 455 | * 456 | * @see #cancel(boolean) 457 | */ 458 | public final boolean isCancelled() { 459 | return mCancelled.get(); 460 | } 461 | 462 | /** 463 | *

Attempts to cancel execution of this task. This attempt will 464 | * fail if the task has already completed, already been cancelled, 465 | * or could not be cancelled for some other reason. If successful, 466 | * and this task has not started when cancel is called, 467 | * this task should never run. If the task has already started, 468 | * then the mayInterruptIfRunning parameter determines 469 | * whether the thread executing this task should be interrupted in 470 | * an attempt to stop the task.

471 | * 472 | *

Calling this method will result in {@link #onCancelled(Object)} being 473 | * invoked on the UI thread after {@link #doInBackground(Object[])} 474 | * returns. Calling this method guarantees that {@link #onPostExecute(Object)} 475 | * is never invoked. After invoking this method, you should check the 476 | * value returned by {@link #isCancelled()} periodically from 477 | * {@link #doInBackground(Object[])} to finish the task as early as 478 | * possible.

479 | * 480 | * @param mayInterruptIfRunning true if the thread executing this 481 | * task should be interrupted; otherwise, in-progress tasks are allowed 482 | * to complete. 483 | * 484 | * @return false if the task could not be cancelled, 485 | * typically because it has already completed normally; 486 | * true otherwise 487 | * 488 | * @see #isCancelled() 489 | * @see #onCancelled(Object) 490 | */ 491 | public final boolean cancel(boolean mayInterruptIfRunning) { 492 | mCancelled.set(true); 493 | return mFuture.cancel(mayInterruptIfRunning); 494 | } 495 | 496 | /** 497 | * Waits if necessary for the computation to complete, and then 498 | * retrieves its result. 499 | * 500 | * @return The computed result. 501 | * 502 | * @throws java.util.concurrent.CancellationException If the computation was cancelled. 503 | * @throws java.util.concurrent.ExecutionException If the computation threw an exception. 504 | * @throws InterruptedException If the current thread was interrupted 505 | * while waiting. 506 | */ 507 | public final Result get() throws InterruptedException, ExecutionException { 508 | return mFuture.get(); 509 | } 510 | 511 | /** 512 | * Waits if necessary for at most the given time for the computation 513 | * to complete, and then retrieves its result. 514 | * 515 | * @param timeout Time to wait before cancelling the operation. 516 | * @param unit The time unit for the timeout. 517 | * 518 | * @return The computed result. 519 | * 520 | * @throws java.util.concurrent.CancellationException If the computation was cancelled. 521 | * @throws java.util.concurrent.ExecutionException If the computation threw an exception. 522 | * @throws InterruptedException If the current thread was interrupted 523 | * while waiting. 524 | * @throws java.util.concurrent.TimeoutException If the wait timed out. 525 | */ 526 | public final Result get(long timeout, TimeUnit unit) throws InterruptedException, 527 | ExecutionException, TimeoutException { 528 | return mFuture.get(timeout, unit); 529 | } 530 | 531 | /** 532 | * Executes the task with the specified parameters. The task returns 533 | * itself (this) so that the caller can keep a reference to it. 534 | * 535 | *

Note: this function schedules the task on a queue for a single background 536 | * thread or pool of threads depending on the platform version. When first 537 | * introduced, AsyncTasks were executed serially on a single background thread. 538 | * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed 539 | * to a pool of threads allowing multiple tasks to operate in parallel. Starting 540 | * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being 541 | * executed on a single thread to avoid common application errors caused 542 | * by parallel execution. If you truly want parallel execution, you can use 543 | * the {@link #executeOnExecutor} version of this method 544 | * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings 545 | * on its use. 546 | * 547 | *

This method must be invoked on the UI thread. 548 | * 549 | * @param params The parameters of the task. 550 | * 551 | * @return This instance of AsyncTask. 552 | * 553 | * @throws IllegalStateException If {@link #getStatus()} returns either 554 | * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. 555 | * 556 | * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) 557 | * @see #execute(Runnable) 558 | */ 559 | public final AsyncTask execute(Params... params) { 560 | return executeOnExecutor(sDefaultExecutor, params); 561 | } 562 | 563 | /** 564 | * Executes the task with the specified parameters. The task returns 565 | * itself (this) so that the caller can keep a reference to it. 566 | * 567 | *

This method is typically used with {@link #THREAD_POOL_EXECUTOR} to 568 | * allow multiple tasks to run in parallel on a pool of threads managed by 569 | * AsyncTask, however you can also use your own {@link java.util.concurrent.Executor} for custom 570 | * behavior. 571 | * 572 | *

Warning: Allowing multiple tasks to run in parallel from 573 | * a thread pool is generally not what one wants, because the order 574 | * of their operation is not defined. For example, if these tasks are used 575 | * to modify any state in common (such as writing a file due to a button click), 576 | * there are no guarantees on the order of the modifications. 577 | * Without careful work it is possible in rare cases for the newer version 578 | * of the data to be over-written by an older one, leading to obscure data 579 | * loss and stability issues. Such changes are best 580 | * executed in serial; to guarantee such work is serialized regardless of 581 | * platform version you can use this function with {@link #SERIAL_EXECUTOR}. 582 | * 583 | *

This method must be invoked on the UI thread. 584 | * 585 | * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a 586 | * convenient process-wide thread pool for tasks that are loosely coupled. 587 | * @param params The parameters of the task. 588 | * 589 | * @return This instance of AsyncTask. 590 | * 591 | * @throws IllegalStateException If {@link #getStatus()} returns either 592 | * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. 593 | * 594 | * @see #execute(Object[]) 595 | */ 596 | public final AsyncTask executeOnExecutor(Executor exec, 597 | Params... params) { 598 | if (mStatus != Status.PENDING) { 599 | switch (mStatus) { 600 | case RUNNING: 601 | throw new IllegalStateException("Cannot execute task:" 602 | + " the task is already running."); 603 | case FINISHED: 604 | throw new IllegalStateException("Cannot execute task:" 605 | + " the task has already been executed " 606 | + "(a task can be executed only once)"); 607 | } 608 | } 609 | 610 | mStatus = Status.RUNNING; 611 | 612 | onPreExecute(); 613 | 614 | mWorker.mParams = params; 615 | exec.execute(mFuture); 616 | 617 | return this; 618 | } 619 | 620 | /** 621 | * Convenience version of {@link #execute(Object...)} for use with 622 | * a simple Runnable object. See {@link #execute(Object[])} for more 623 | * information on the order of execution. 624 | * 625 | * @see #execute(Object[]) 626 | * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) 627 | */ 628 | public static void execute(Runnable runnable) { 629 | sDefaultExecutor.execute(runnable); 630 | } 631 | 632 | /** 633 | * This method can be invoked from {@link #doInBackground} to 634 | * publish updates on the UI thread while the background computation is 635 | * still running. Each call to this method will trigger the execution of 636 | * {@link #onProgressUpdate} on the UI thread. 637 | * 638 | * {@link #onProgressUpdate} will note be called if the task has been 639 | * canceled. 640 | * 641 | * @param values The progress values to update the UI with. 642 | * 643 | * @see #onProgressUpdate 644 | * @see #doInBackground 645 | */ 646 | protected final void publishProgress(Progress... values) { 647 | if (!isCancelled()) { 648 | sHandler.obtainMessage(MESSAGE_POST_PROGRESS, 649 | new AsyncTaskResult(this, values)).sendToTarget(); 650 | } 651 | } 652 | 653 | private void finish(Result result) { 654 | if (isCancelled()) { 655 | onCancelled(result); 656 | } else { 657 | onPostExecute(result); 658 | } 659 | mStatus = Status.FINISHED; 660 | } 661 | 662 | private static class InternalHandler extends Handler { 663 | @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) 664 | @Override 665 | public void handleMessage(Message msg) { 666 | AsyncTaskResult result = (AsyncTaskResult) msg.obj; 667 | switch (msg.what) { 668 | case MESSAGE_POST_RESULT: 669 | // There is only one result 670 | result.mTask.finish(result.mData[0]); 671 | break; 672 | case MESSAGE_POST_PROGRESS: 673 | result.mTask.onProgressUpdate(result.mData); 674 | break; 675 | } 676 | } 677 | } 678 | 679 | private static abstract class WorkerRunnable implements Callable { 680 | Params[] mParams; 681 | } 682 | 683 | @SuppressWarnings({"RawUseOfParameterizedType"}) 684 | private static class AsyncTaskResult { 685 | final AsyncTask mTask; 686 | final Data[] mData; 687 | 688 | AsyncTaskResult(AsyncTask task, Data... data) { 689 | mTask = task; 690 | mData = data; 691 | } 692 | } 693 | } -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/ImageFetcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.util; 18 | 19 | import android.content.Context; 20 | import android.graphics.Bitmap; 21 | import android.net.ConnectivityManager; 22 | import android.net.NetworkInfo; 23 | import android.os.Build; 24 | import android.widget.Toast; 25 | 26 | import com.example.android.common.logger.Log; 27 | import com.example.android.displayingbitmaps.BuildConfig; 28 | import com.example.android.displayingbitmaps.R; 29 | 30 | import java.io.BufferedInputStream; 31 | import java.io.BufferedOutputStream; 32 | import java.io.File; 33 | import java.io.FileDescriptor; 34 | import java.io.FileInputStream; 35 | import java.io.IOException; 36 | import java.io.OutputStream; 37 | import java.net.HttpURLConnection; 38 | import java.net.URL; 39 | 40 | /** 41 | * A simple subclass of {@link ImageResizer} that fetches and resizes images fetched from a URL. 42 | */ 43 | public class ImageFetcher extends ImageResizer { 44 | private static final String TAG = "ImageFetcher"; 45 | private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB 46 | private static final String HTTP_CACHE_DIR = "http"; 47 | private static final int IO_BUFFER_SIZE = 8 * 1024; 48 | 49 | private DiskLruCache mHttpDiskCache; 50 | private File mHttpCacheDir; 51 | private boolean mHttpDiskCacheStarting = true; 52 | private final Object mHttpDiskCacheLock = new Object(); 53 | private static final int DISK_CACHE_INDEX = 0; 54 | 55 | /** 56 | * Initialize providing a target image width and height for the processing images. 57 | * 58 | * @param context 59 | * @param imageWidth 60 | * @param imageHeight 61 | */ 62 | public ImageFetcher(Context context, int imageWidth, int imageHeight) { 63 | super(context, imageWidth, imageHeight); 64 | init(context); 65 | } 66 | 67 | /** 68 | * Initialize providing a single target image size (used for both width and height); 69 | * 70 | * @param context 71 | * @param imageSize 72 | */ 73 | public ImageFetcher(Context context, int imageSize) { 74 | super(context, imageSize); 75 | init(context); 76 | } 77 | 78 | private void init(Context context) { 79 | checkConnection(context); 80 | mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR); 81 | } 82 | 83 | @Override 84 | protected void initDiskCacheInternal() { 85 | super.initDiskCacheInternal(); 86 | initHttpDiskCache(); 87 | } 88 | 89 | private void initHttpDiskCache() { 90 | if (!mHttpCacheDir.exists()) { 91 | mHttpCacheDir.mkdirs(); 92 | } 93 | synchronized (mHttpDiskCacheLock) { 94 | if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) { 95 | try { 96 | mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE); 97 | if (BuildConfig.DEBUG) { 98 | Log.d(TAG, "HTTP cache initialized"); 99 | } 100 | } catch (IOException e) { 101 | mHttpDiskCache = null; 102 | } 103 | } 104 | mHttpDiskCacheStarting = false; 105 | mHttpDiskCacheLock.notifyAll(); 106 | } 107 | } 108 | 109 | @Override 110 | protected void clearCacheInternal() { 111 | super.clearCacheInternal(); 112 | synchronized (mHttpDiskCacheLock) { 113 | if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) { 114 | try { 115 | mHttpDiskCache.delete(); 116 | if (BuildConfig.DEBUG) { 117 | Log.d(TAG, "HTTP cache cleared"); 118 | } 119 | } catch (IOException e) { 120 | Log.e(TAG, "clearCacheInternal - " + e); 121 | } 122 | mHttpDiskCache = null; 123 | mHttpDiskCacheStarting = true; 124 | initHttpDiskCache(); 125 | } 126 | } 127 | } 128 | 129 | @Override 130 | protected void flushCacheInternal() { 131 | super.flushCacheInternal(); 132 | synchronized (mHttpDiskCacheLock) { 133 | if (mHttpDiskCache != null) { 134 | try { 135 | mHttpDiskCache.flush(); 136 | if (BuildConfig.DEBUG) { 137 | Log.d(TAG, "HTTP cache flushed"); 138 | } 139 | } catch (IOException e) { 140 | Log.e(TAG, "flush - " + e); 141 | } 142 | } 143 | } 144 | } 145 | 146 | @Override 147 | protected void closeCacheInternal() { 148 | super.closeCacheInternal(); 149 | synchronized (mHttpDiskCacheLock) { 150 | if (mHttpDiskCache != null) { 151 | try { 152 | if (!mHttpDiskCache.isClosed()) { 153 | mHttpDiskCache.close(); 154 | mHttpDiskCache = null; 155 | if (BuildConfig.DEBUG) { 156 | Log.d(TAG, "HTTP cache closed"); 157 | } 158 | } 159 | } catch (IOException e) { 160 | Log.e(TAG, "closeCacheInternal - " + e); 161 | } 162 | } 163 | } 164 | } 165 | 166 | /** 167 | * Simple network connection check. 168 | * 169 | * @param context 170 | */ 171 | private void checkConnection(Context context) { 172 | final ConnectivityManager cm = 173 | (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 174 | final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 175 | if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) { 176 | Toast.makeText(context, R.string.no_network_connection_toast, Toast.LENGTH_LONG).show(); 177 | Log.e(TAG, "checkConnection - no connection found"); 178 | } 179 | } 180 | 181 | /** 182 | * The main process method, which will be called by the ImageWorker in the AsyncTask background 183 | * thread. 184 | * 185 | * @param data The data to load the bitmap, in this case, a regular http URL 186 | * @return The downloaded and resized bitmap 187 | */ 188 | private Bitmap processBitmap(String data) { 189 | if (BuildConfig.DEBUG) { 190 | Log.d(TAG, "processBitmap - " + data); 191 | } 192 | 193 | final String key = ImageCache.hashKeyForDisk(data); 194 | FileDescriptor fileDescriptor = null; 195 | FileInputStream fileInputStream = null; 196 | DiskLruCache.Snapshot snapshot; 197 | synchronized (mHttpDiskCacheLock) { 198 | // Wait for disk cache to initialize 199 | while (mHttpDiskCacheStarting) { 200 | try { 201 | mHttpDiskCacheLock.wait(); 202 | } catch (InterruptedException e) {} 203 | } 204 | 205 | if (mHttpDiskCache != null) { 206 | try { 207 | snapshot = mHttpDiskCache.get(key); 208 | if (snapshot == null) { 209 | if (BuildConfig.DEBUG) { 210 | Log.d(TAG, "processBitmap, not found in http cache, downloading..."); 211 | } 212 | DiskLruCache.Editor editor = mHttpDiskCache.edit(key); 213 | if (editor != null) { 214 | if (downloadUrlToStream(data, 215 | editor.newOutputStream(DISK_CACHE_INDEX))) { 216 | editor.commit(); 217 | } else { 218 | editor.abort(); 219 | } 220 | } 221 | snapshot = mHttpDiskCache.get(key); 222 | } 223 | if (snapshot != null) { 224 | fileInputStream = 225 | (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX); 226 | fileDescriptor = fileInputStream.getFD(); 227 | } 228 | } catch (IOException e) { 229 | Log.e(TAG, "processBitmap - " + e); 230 | } catch (IllegalStateException e) { 231 | Log.e(TAG, "processBitmap - " + e); 232 | } finally { 233 | if (fileDescriptor == null && fileInputStream != null) { 234 | try { 235 | fileInputStream.close(); 236 | } catch (IOException e) {} 237 | } 238 | } 239 | } 240 | } 241 | 242 | Bitmap bitmap = null; 243 | if (fileDescriptor != null) { 244 | bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, 245 | mImageHeight, getImageCache()); 246 | } 247 | if (fileInputStream != null) { 248 | try { 249 | fileInputStream.close(); 250 | } catch (IOException e) {} 251 | } 252 | return bitmap; 253 | } 254 | 255 | @Override 256 | protected Bitmap processBitmap(Object data) { 257 | return processBitmap(String.valueOf(data)); 258 | } 259 | 260 | /** 261 | * Download a bitmap from a URL and write the content to an output stream. 262 | * 263 | * @param urlString The URL to fetch 264 | * @return true if successful, false otherwise 265 | */ 266 | public boolean downloadUrlToStream(String urlString, OutputStream outputStream) { 267 | disableConnectionReuseIfNecessary(); 268 | HttpURLConnection urlConnection = null; 269 | BufferedOutputStream out = null; 270 | BufferedInputStream in = null; 271 | 272 | try { 273 | final URL url = new URL(urlString); 274 | urlConnection = (HttpURLConnection) url.openConnection(); 275 | in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); 276 | out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); 277 | 278 | int b; 279 | while ((b = in.read()) != -1) { 280 | out.write(b); 281 | } 282 | return true; 283 | } catch (final IOException e) { 284 | Log.e(TAG, "Error in downloadBitmap - " + e); 285 | } finally { 286 | if (urlConnection != null) { 287 | urlConnection.disconnect(); 288 | } 289 | try { 290 | if (out != null) { 291 | out.close(); 292 | } 293 | if (in != null) { 294 | in.close(); 295 | } 296 | } catch (final IOException e) {} 297 | } 298 | return false; 299 | } 300 | 301 | /** 302 | * Workaround for bug pre-Froyo, see here for more info: 303 | * http://android-developers.blogspot.com/2011/09/androids-http-clients.html 304 | */ 305 | public static void disableConnectionReuseIfNecessary() { 306 | // HTTP connection reuse which was buggy pre-froyo 307 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { 308 | System.setProperty("http.keepAlive", "false"); 309 | } 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/ImageResizer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.util; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.content.res.Resources; 22 | import android.graphics.Bitmap; 23 | import android.graphics.BitmapFactory; 24 | import android.os.Build; 25 | 26 | import com.example.android.common.logger.Log; 27 | import com.example.android.displayingbitmaps.BuildConfig; 28 | 29 | import java.io.FileDescriptor; 30 | 31 | /** 32 | * A simple subclass of {@link ImageWorker} that resizes images from resources given a target width 33 | * and height. Useful for when the input images might be too large to simply load directly into 34 | * memory. 35 | */ 36 | public class ImageResizer extends ImageWorker { 37 | private static final String TAG = "ImageResizer"; 38 | protected int mImageWidth; 39 | protected int mImageHeight; 40 | 41 | /** 42 | * Initialize providing a single target image size (used for both width and height); 43 | * 44 | * @param context 45 | * @param imageWidth 46 | * @param imageHeight 47 | */ 48 | public ImageResizer(Context context, int imageWidth, int imageHeight) { 49 | super(context); 50 | setImageSize(imageWidth, imageHeight); 51 | } 52 | 53 | /** 54 | * Initialize providing a single target image size (used for both width and height); 55 | * 56 | * @param context 57 | * @param imageSize 58 | */ 59 | public ImageResizer(Context context, int imageSize) { 60 | super(context); 61 | setImageSize(imageSize); 62 | } 63 | 64 | /** 65 | * Set the target image width and height. 66 | * 67 | * @param width 68 | * @param height 69 | */ 70 | public void setImageSize(int width, int height) { 71 | mImageWidth = width; 72 | mImageHeight = height; 73 | } 74 | 75 | /** 76 | * Set the target image size (width and height will be the same). 77 | * 78 | * @param size 79 | */ 80 | public void setImageSize(int size) { 81 | setImageSize(size, size); 82 | } 83 | 84 | /** 85 | * The main processing method. This happens in a background task. In this case we are just 86 | * sampling down the bitmap and returning it from a resource. 87 | * 88 | * @param resId 89 | * @return 90 | */ 91 | private Bitmap processBitmap(int resId) { 92 | if (BuildConfig.DEBUG) { 93 | Log.d(TAG, "processBitmap - " + resId); 94 | } 95 | return decodeSampledBitmapFromResource(mResources, resId, mImageWidth, 96 | mImageHeight, getImageCache()); 97 | } 98 | 99 | @Override 100 | protected Bitmap processBitmap(Object data) { 101 | return processBitmap(Integer.parseInt(String.valueOf(data))); 102 | } 103 | 104 | /** 105 | * Decode and sample down a bitmap from resources to the requested width and height. 106 | * 107 | * @param res The resources object containing the image data 108 | * @param resId The resource id of the image data 109 | * @param reqWidth The requested width of the resulting bitmap 110 | * @param reqHeight The requested height of the resulting bitmap 111 | * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap 112 | * @return A bitmap sampled down from the original with the same aspect ratio and dimensions 113 | * that are equal to or greater than the requested width and height 114 | */ 115 | public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 116 | int reqWidth, int reqHeight, ImageCache cache) { 117 | 118 | // BEGIN_INCLUDE (read_bitmap_dimensions) 119 | // First decode with inJustDecodeBounds=true to check dimensions 120 | final BitmapFactory.Options options = new BitmapFactory.Options(); 121 | options.inJustDecodeBounds = true; 122 | BitmapFactory.decodeResource(res, resId, options); 123 | 124 | // Calculate inSampleSize 125 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 126 | // END_INCLUDE (read_bitmap_dimensions) 127 | 128 | // If we're running on Honeycomb or newer, try to use inBitmap 129 | if (Utils.hasHoneycomb()) { 130 | addInBitmapOptions(options, cache); 131 | } 132 | 133 | // Decode bitmap with inSampleSize set 134 | options.inJustDecodeBounds = false; 135 | return BitmapFactory.decodeResource(res, resId, options); 136 | } 137 | 138 | /** 139 | * Decode and sample down a bitmap from a file to the requested width and height. 140 | * 141 | * @param filename The full path of the file to decode 142 | * @param reqWidth The requested width of the resulting bitmap 143 | * @param reqHeight The requested height of the resulting bitmap 144 | * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap 145 | * @return A bitmap sampled down from the original with the same aspect ratio and dimensions 146 | * that are equal to or greater than the requested width and height 147 | */ 148 | public static Bitmap decodeSampledBitmapFromFile(String filename, 149 | int reqWidth, int reqHeight, ImageCache cache) { 150 | 151 | // First decode with inJustDecodeBounds=true to check dimensions 152 | final BitmapFactory.Options options = new BitmapFactory.Options(); 153 | options.inJustDecodeBounds = true; 154 | BitmapFactory.decodeFile(filename, options); 155 | 156 | // Calculate inSampleSize 157 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 158 | 159 | // If we're running on Honeycomb or newer, try to use inBitmap 160 | if (Utils.hasHoneycomb()) { 161 | addInBitmapOptions(options, cache); 162 | } 163 | 164 | // Decode bitmap with inSampleSize set 165 | options.inJustDecodeBounds = false; 166 | return BitmapFactory.decodeFile(filename, options); 167 | } 168 | 169 | /** 170 | * Decode and sample down a bitmap from a file input stream to the requested width and height. 171 | * 172 | * @param fileDescriptor The file descriptor to read from 173 | * @param reqWidth The requested width of the resulting bitmap 174 | * @param reqHeight The requested height of the resulting bitmap 175 | * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap 176 | * @return A bitmap sampled down from the original with the same aspect ratio and dimensions 177 | * that are equal to or greater than the requested width and height 178 | */ 179 | public static Bitmap decodeSampledBitmapFromDescriptor( 180 | FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { 181 | 182 | // First decode with inJustDecodeBounds=true to check dimensions 183 | final BitmapFactory.Options options = new BitmapFactory.Options(); 184 | options.inJustDecodeBounds = true; 185 | BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); 186 | 187 | // Calculate inSampleSize 188 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 189 | 190 | // Decode bitmap with inSampleSize set 191 | options.inJustDecodeBounds = false; 192 | 193 | // If we're running on Honeycomb or newer, try to use inBitmap 194 | if (Utils.hasHoneycomb()) { 195 | addInBitmapOptions(options, cache); 196 | } 197 | 198 | return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); 199 | } 200 | 201 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 202 | private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { 203 | 204 | // inBitmap only works with mutable bitmaps so force the decoder to 205 | // return mutable bitmaps. 206 | options.inMutable = true; 207 | 208 | if (cache != null) { 209 | // Try and find a bitmap to use for inBitmap 210 | Bitmap inBitmap = cache.getBitmapFromReusableSet(options); 211 | 212 | if (inBitmap != null) { 213 | options.inBitmap = inBitmap; 214 | } 215 | } 216 | 217 | } 218 | 219 | /** 220 | * Calculate an inSampleSize for use in a {@link android.graphics.BitmapFactory.Options} object when decoding 221 | * bitmaps using the decode* methods from {@link android.graphics.BitmapFactory}. This implementation calculates 222 | * the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap 223 | * having a width and height equal to or larger than the requested width and height. 224 | * 225 | * @param options An options object with out* params already populated (run through a decode* 226 | * method with inJustDecodeBounds==true 227 | * @param reqWidth The requested width of the resulting bitmap 228 | * @param reqHeight The requested height of the resulting bitmap 229 | * @return The value to be used for inSampleSize 230 | */ 231 | public static int calculateInSampleSize(BitmapFactory.Options options, 232 | int reqWidth, int reqHeight) { 233 | // BEGIN_INCLUDE (calculate_sample_size) 234 | // Raw height and width of image 235 | final int height = options.outHeight; 236 | final int width = options.outWidth; 237 | int inSampleSize = 1; 238 | 239 | if (height > reqHeight || width > reqWidth) { 240 | 241 | final int halfHeight = height / 2; 242 | final int halfWidth = width / 2; 243 | 244 | // Calculate the largest inSampleSize value that is a power of 2 and keeps both 245 | // height and width larger than the requested height and width. 246 | while ((halfHeight / inSampleSize) > reqHeight 247 | && (halfWidth / inSampleSize) > reqWidth) { 248 | inSampleSize *= 2; 249 | } 250 | 251 | // This offers some additional logic in case the image has a strange 252 | // aspect ratio. For example, a panorama may have a much larger 253 | // width than height. In these cases the total pixels might still 254 | // end up being too large to fit comfortably in memory, so we should 255 | // be more aggressive with sample down the image (=larger inSampleSize). 256 | 257 | long totalPixels = width * height / inSampleSize; 258 | 259 | // Anything more than 2x the requested pixels we'll sample down further 260 | final long totalReqPixelsCap = reqWidth * reqHeight * 2; 261 | 262 | while (totalPixels > totalReqPixelsCap) { 263 | inSampleSize *= 2; 264 | totalPixels /= 2; 265 | } 266 | } 267 | return inSampleSize; 268 | // END_INCLUDE (calculate_sample_size) 269 | } 270 | } 271 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/ImageWorker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.util; 18 | 19 | import android.content.Context; 20 | import android.content.res.Resources; 21 | import android.graphics.Bitmap; 22 | import android.graphics.BitmapFactory; 23 | import android.graphics.drawable.BitmapDrawable; 24 | import android.graphics.drawable.ColorDrawable; 25 | import android.graphics.drawable.Drawable; 26 | import android.graphics.drawable.TransitionDrawable; 27 | import android.support.v4.app.FragmentActivity; 28 | import android.support.v4.app.FragmentManager; 29 | import android.widget.ImageView; 30 | 31 | import com.example.android.common.logger.Log; 32 | import com.example.android.displayingbitmaps.BuildConfig; 33 | 34 | import java.lang.ref.WeakReference; 35 | 36 | /** 37 | * This class wraps up completing some arbitrary long running work when loading a bitmap to an 38 | * ImageView. It handles things like using a memory and disk cache, running the work in a background 39 | * thread and setting a placeholder image. 40 | */ 41 | public abstract class ImageWorker { 42 | private static final String TAG = "ImageWorker"; 43 | private static final int FADE_IN_TIME = 200; 44 | 45 | private ImageCache mImageCache; 46 | private ImageCache.ImageCacheParams mImageCacheParams; 47 | private Bitmap mLoadingBitmap; 48 | private boolean mFadeInBitmap = true; 49 | private boolean mExitTasksEarly = false; 50 | protected boolean mPauseWork = false; 51 | private final Object mPauseWorkLock = new Object(); 52 | 53 | protected Resources mResources; 54 | 55 | private static final int MESSAGE_CLEAR = 0; 56 | private static final int MESSAGE_INIT_DISK_CACHE = 1; 57 | private static final int MESSAGE_FLUSH = 2; 58 | private static final int MESSAGE_CLOSE = 3; 59 | 60 | protected ImageWorker(Context context) { 61 | mResources = context.getResources(); 62 | } 63 | 64 | /** 65 | * Load an image specified by the data parameter into an ImageView (override 66 | * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and 67 | * disk cache will be used if an {@link ImageCache} has been added using 68 | * {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}. If the 69 | * image is found in the memory cache, it is set immediately, otherwise an {@link AsyncTask} 70 | * will be created to asynchronously load the bitmap. 71 | * 72 | * @param data The URL of the image to download. 73 | * @param imageView The ImageView to bind the downloaded image to. 74 | */ 75 | public void loadImage(Object data, ImageView imageView) { 76 | if (data == null) { 77 | return; 78 | } 79 | 80 | BitmapDrawable value = null; 81 | 82 | if (mImageCache != null) { 83 | value = mImageCache.getBitmapFromMemCache(String.valueOf(data)); 84 | } 85 | 86 | if (value != null) { 87 | // Bitmap found in memory cache 88 | imageView.setImageDrawable(value); 89 | } else if (cancelPotentialWork(data, imageView)) { 90 | 91 | final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView); 92 | final AsyncDrawable asyncDrawable = 93 | new AsyncDrawable(mResources, mLoadingBitmap, task); 94 | imageView.setImageDrawable(asyncDrawable); 95 | 96 | // NOTE: This uses a custom version of AsyncTask that has been pulled from the 97 | // framework and slightly modified. Refer to the docs at the top of the class 98 | // for more info on what was changed. 99 | task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR); 100 | 101 | } 102 | } 103 | 104 | /** 105 | * Set placeholder bitmap that shows when the the background thread is running. 106 | * 107 | * @param bitmap 108 | */ 109 | public void setLoadingImage(Bitmap bitmap) { 110 | mLoadingBitmap = bitmap; 111 | } 112 | 113 | /** 114 | * Set placeholder bitmap that shows when the the background thread is running. 115 | * 116 | * @param resId 117 | */ 118 | public void setLoadingImage(int resId) { 119 | mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId); 120 | } 121 | 122 | /** 123 | * Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap 124 | * caching. 125 | * @param fragmentManager 126 | * @param cacheParams The cache parameters to use for the image cache. 127 | */ 128 | public void addImageCache(FragmentManager fragmentManager, 129 | ImageCache.ImageCacheParams cacheParams) { 130 | mImageCacheParams = cacheParams; 131 | mImageCache = ImageCache.getInstance(fragmentManager, mImageCacheParams); 132 | new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE); 133 | } 134 | 135 | /** 136 | * Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap 137 | * caching. 138 | * @param activity 139 | * @param diskCacheDirectoryName See 140 | * {@link ImageCache.ImageCacheParams#ImageCacheParams(android.content.Context, String)}. 141 | */ 142 | public void addImageCache(FragmentActivity activity, String diskCacheDirectoryName) { 143 | mImageCacheParams = new ImageCache.ImageCacheParams(activity, diskCacheDirectoryName); 144 | mImageCache = ImageCache.getInstance(activity.getSupportFragmentManager(), mImageCacheParams); 145 | new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE); 146 | } 147 | 148 | /** 149 | * If set to true, the image will fade-in once it has been loaded by the background thread. 150 | */ 151 | public void setImageFadeIn(boolean fadeIn) { 152 | mFadeInBitmap = fadeIn; 153 | } 154 | 155 | public void setExitTasksEarly(boolean exitTasksEarly) { 156 | mExitTasksEarly = exitTasksEarly; 157 | setPauseWork(false); 158 | } 159 | 160 | /** 161 | * Subclasses should override this to define any processing or work that must happen to produce 162 | * the final bitmap. This will be executed in a background thread and be long running. For 163 | * example, you could resize a large bitmap here, or pull down an image from the network. 164 | * 165 | * @param data The data to identify which image to process, as provided by 166 | * {@link ImageWorker#loadImage(Object, android.widget.ImageView)} 167 | * @return The processed bitmap 168 | */ 169 | protected abstract Bitmap processBitmap(Object data); 170 | 171 | /** 172 | * @return The {@link ImageCache} object currently being used by this ImageWorker. 173 | */ 174 | protected ImageCache getImageCache() { 175 | return mImageCache; 176 | } 177 | 178 | /** 179 | * Cancels any pending work attached to the provided ImageView. 180 | * @param imageView 181 | */ 182 | public static void cancelWork(ImageView imageView) { 183 | final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); 184 | if (bitmapWorkerTask != null) { 185 | bitmapWorkerTask.cancel(true); 186 | if (BuildConfig.DEBUG) { 187 | final Object bitmapData = bitmapWorkerTask.mData; 188 | Log.d(TAG, "cancelWork - cancelled work for " + bitmapData); 189 | } 190 | } 191 | } 192 | 193 | /** 194 | * Returns true if the current work has been canceled or if there was no work in 195 | * progress on this image view. 196 | * Returns false if the work in progress deals with the same data. The work is not 197 | * stopped in that case. 198 | */ 199 | public static boolean cancelPotentialWork(Object data, ImageView imageView) { 200 | 201 | final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); 202 | 203 | if (bitmapWorkerTask != null) { 204 | final Object bitmapData = bitmapWorkerTask.mData; 205 | if (bitmapData == null || !bitmapData.equals(data)) { 206 | bitmapWorkerTask.cancel(true); 207 | if (BuildConfig.DEBUG) { 208 | Log.d(TAG, "cancelPotentialWork - cancelled work for " + data); 209 | } 210 | } else { 211 | // The same work is already in progress. 212 | return false; 213 | } 214 | } 215 | return true; 216 | 217 | } 218 | 219 | /** 220 | * @param imageView Any imageView 221 | * @return Retrieve the currently active work task (if any) associated with this imageView. 222 | * null if there is no such task. 223 | */ 224 | private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { 225 | if (imageView != null) { 226 | final Drawable drawable = imageView.getDrawable(); 227 | if (drawable instanceof AsyncDrawable) { 228 | final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; 229 | return asyncDrawable.getBitmapWorkerTask(); 230 | } 231 | } 232 | return null; 233 | } 234 | 235 | /** 236 | * The actual AsyncTask that will asynchronously process the image. 237 | */ 238 | private class BitmapWorkerTask extends AsyncTask { 239 | private Object mData; 240 | private final WeakReference imageViewReference; 241 | 242 | public BitmapWorkerTask(Object data, ImageView imageView) { 243 | mData = data; 244 | imageViewReference = new WeakReference(imageView); 245 | } 246 | 247 | /** 248 | * Background processing. 249 | */ 250 | @Override 251 | protected BitmapDrawable doInBackground(Void... params) { 252 | 253 | if (BuildConfig.DEBUG) { 254 | Log.d(TAG, "doInBackground - starting work"); 255 | } 256 | 257 | final String dataString = String.valueOf(mData); 258 | Bitmap bitmap = null; 259 | BitmapDrawable drawable = null; 260 | 261 | // Wait here if work is paused and the task is not cancelled 262 | synchronized (mPauseWorkLock) { 263 | while (mPauseWork && !isCancelled()) { 264 | try { 265 | mPauseWorkLock.wait(); 266 | } catch (InterruptedException e) {} 267 | } 268 | } 269 | 270 | // If the image cache is available and this task has not been cancelled by another 271 | // thread and the ImageView that was originally bound to this task is still bound back 272 | // to this task and our "exit early" flag is not set then try and fetch the bitmap from 273 | // the cache 274 | if (mImageCache != null && !isCancelled() && getAttachedImageView() != null 275 | && !mExitTasksEarly) { 276 | bitmap = mImageCache.getBitmapFromDiskCache(dataString); 277 | } 278 | 279 | // If the bitmap was not found in the cache and this task has not been cancelled by 280 | // another thread and the ImageView that was originally bound to this task is still 281 | // bound back to this task and our "exit early" flag is not set, then call the main 282 | // process method (as implemented by a subclass) 283 | if (bitmap == null && !isCancelled() && getAttachedImageView() != null 284 | && !mExitTasksEarly) { 285 | bitmap = processBitmap(mData); 286 | } 287 | 288 | // If the bitmap was processed and the image cache is available, then add the processed 289 | // bitmap to the cache for future use. Note we don't check if the task was cancelled 290 | // here, if it was, and the thread is still running, we may as well add the processed 291 | // bitmap to our cache as it might be used again in the future 292 | if (bitmap != null) { 293 | if (Utils.hasHoneycomb()) { 294 | // Running on Honeycomb or newer, so wrap in a standard BitmapDrawable 295 | drawable = new BitmapDrawable(mResources, bitmap); 296 | } else { 297 | // Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable 298 | // which will recycle automagically 299 | drawable = new RecyclingBitmapDrawable(mResources, bitmap); 300 | } 301 | 302 | if (mImageCache != null) { 303 | mImageCache.addBitmapToCache(dataString, drawable); 304 | } 305 | } 306 | 307 | if (BuildConfig.DEBUG) { 308 | Log.d(TAG, "doInBackground - finished work"); 309 | } 310 | 311 | return drawable; 312 | 313 | } 314 | 315 | /** 316 | * Once the image is processed, associates it to the imageView 317 | */ 318 | @Override 319 | protected void onPostExecute(BitmapDrawable value) { 320 | 321 | // if cancel was called on this task or the "exit early" flag is set then we're done 322 | if (isCancelled() || mExitTasksEarly) { 323 | value = null; 324 | } 325 | 326 | final ImageView imageView = getAttachedImageView(); 327 | if (value != null && imageView != null) { 328 | if (BuildConfig.DEBUG) { 329 | Log.d(TAG, "onPostExecute - setting bitmap"); 330 | } 331 | setImageDrawable(imageView, value); 332 | } 333 | 334 | } 335 | 336 | @Override 337 | protected void onCancelled(BitmapDrawable value) { 338 | super.onCancelled(value); 339 | synchronized (mPauseWorkLock) { 340 | mPauseWorkLock.notifyAll(); 341 | } 342 | } 343 | 344 | /** 345 | * Returns the ImageView associated with this task as long as the ImageView's task still 346 | * points to this task as well. Returns null otherwise. 347 | */ 348 | private ImageView getAttachedImageView() { 349 | final ImageView imageView = imageViewReference.get(); 350 | final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); 351 | 352 | if (this == bitmapWorkerTask) { 353 | return imageView; 354 | } 355 | 356 | return null; 357 | } 358 | } 359 | 360 | /** 361 | * A custom Drawable that will be attached to the imageView while the work is in progress. 362 | * Contains a reference to the actual worker task, so that it can be stopped if a new binding is 363 | * required, and makes sure that only the last started worker process can bind its result, 364 | * independently of the finish order. 365 | */ 366 | private static class AsyncDrawable extends BitmapDrawable { 367 | private final WeakReference bitmapWorkerTaskReference; 368 | 369 | public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) { 370 | super(res, bitmap); 371 | bitmapWorkerTaskReference = 372 | new WeakReference(bitmapWorkerTask); 373 | } 374 | 375 | public BitmapWorkerTask getBitmapWorkerTask() { 376 | return bitmapWorkerTaskReference.get(); 377 | } 378 | } 379 | 380 | /** 381 | * Called when the processing is complete and the final drawable should be 382 | * set on the ImageView. 383 | * 384 | * @param imageView 385 | * @param drawable 386 | */ 387 | private void setImageDrawable(ImageView imageView, Drawable drawable) { 388 | if (mFadeInBitmap) { 389 | // Transition drawable with a transparent drawable and the final drawable 390 | final TransitionDrawable td = 391 | new TransitionDrawable(new Drawable[] { 392 | new ColorDrawable(android.R.color.transparent), 393 | drawable 394 | }); 395 | // Set background to loading bitmap 396 | imageView.setBackgroundDrawable( 397 | new BitmapDrawable(mResources, mLoadingBitmap)); 398 | 399 | imageView.setImageDrawable(td); 400 | td.startTransition(FADE_IN_TIME); 401 | } else { 402 | imageView.setImageDrawable(drawable); 403 | } 404 | } 405 | 406 | /** 407 | * Pause any ongoing background work. This can be used as a temporary 408 | * measure to improve performance. For example background work could 409 | * be paused when a ListView or GridView is being scrolled using a 410 | * {@link android.widget.AbsListView.OnScrollListener} to keep 411 | * scrolling smooth. 412 | *

413 | * If work is paused, be sure setPauseWork(false) is called again 414 | * before your fragment or activity is destroyed (for example during 415 | * {@link android.app.Activity#onPause()}), or there is a risk the 416 | * background thread will never finish. 417 | */ 418 | public void setPauseWork(boolean pauseWork) { 419 | synchronized (mPauseWorkLock) { 420 | mPauseWork = pauseWork; 421 | if (!mPauseWork) { 422 | mPauseWorkLock.notifyAll(); 423 | } 424 | } 425 | } 426 | 427 | protected class CacheAsyncTask extends AsyncTask { 428 | 429 | @Override 430 | protected Void doInBackground(Object... params) { 431 | switch ((Integer)params[0]) { 432 | case MESSAGE_CLEAR: 433 | clearCacheInternal(); 434 | break; 435 | case MESSAGE_INIT_DISK_CACHE: 436 | initDiskCacheInternal(); 437 | break; 438 | case MESSAGE_FLUSH: 439 | flushCacheInternal(); 440 | break; 441 | case MESSAGE_CLOSE: 442 | closeCacheInternal(); 443 | break; 444 | } 445 | return null; 446 | } 447 | } 448 | 449 | protected void initDiskCacheInternal() { 450 | if (mImageCache != null) { 451 | mImageCache.initDiskCache(); 452 | } 453 | } 454 | 455 | protected void clearCacheInternal() { 456 | if (mImageCache != null) { 457 | mImageCache.clearCache(); 458 | } 459 | } 460 | 461 | protected void flushCacheInternal() { 462 | if (mImageCache != null) { 463 | mImageCache.flush(); 464 | } 465 | } 466 | 467 | protected void closeCacheInternal() { 468 | if (mImageCache != null) { 469 | mImageCache.close(); 470 | mImageCache = null; 471 | } 472 | } 473 | 474 | public void clearCache() { 475 | new CacheAsyncTask().execute(MESSAGE_CLEAR); 476 | } 477 | 478 | public void flushCache() { 479 | new CacheAsyncTask().execute(MESSAGE_FLUSH); 480 | } 481 | 482 | public void closeCache() { 483 | new CacheAsyncTask().execute(MESSAGE_CLOSE); 484 | } 485 | } 486 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/RecyclingBitmapDrawable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 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 com.example.android.displayingbitmaps.util; 18 | 19 | import android.content.res.Resources; 20 | import android.graphics.Bitmap; 21 | import android.graphics.drawable.BitmapDrawable; 22 | 23 | import com.example.android.common.logger.Log; 24 | import com.example.android.displayingbitmaps.BuildConfig; 25 | 26 | /** 27 | * A BitmapDrawable that keeps track of whether it is being displayed or cached. 28 | * When the drawable is no longer being displayed or cached, 29 | * {@link android.graphics.Bitmap#recycle() recycle()} will be called on this drawable's bitmap. 30 | */ 31 | public class RecyclingBitmapDrawable extends BitmapDrawable { 32 | 33 | static final String TAG = "CountingBitmapDrawable"; 34 | 35 | private int mCacheRefCount = 0; 36 | private int mDisplayRefCount = 0; 37 | 38 | private boolean mHasBeenDisplayed; 39 | 40 | public RecyclingBitmapDrawable(Resources res, Bitmap bitmap) { 41 | super(res, bitmap); 42 | } 43 | 44 | /** 45 | * Notify the drawable that the displayed state has changed. Internally a 46 | * count is kept so that the drawable knows when it is no longer being 47 | * displayed. 48 | * 49 | * @param isDisplayed - Whether the drawable is being displayed or not 50 | */ 51 | public void setIsDisplayed(boolean isDisplayed) { 52 | 53 | synchronized (this) { 54 | if (isDisplayed) { 55 | mDisplayRefCount++; 56 | mHasBeenDisplayed = true; 57 | } else { 58 | mDisplayRefCount--; 59 | } 60 | } 61 | 62 | // Check to see if recycle() can be called 63 | checkState(); 64 | 65 | } 66 | 67 | /** 68 | * Notify the drawable that the cache state has changed. Internally a count 69 | * is kept so that the drawable knows when it is no longer being cached. 70 | * 71 | * @param isCached - Whether the drawable is being cached or not 72 | */ 73 | public void setIsCached(boolean isCached) { 74 | 75 | synchronized (this) { 76 | if (isCached) { 77 | mCacheRefCount++; 78 | } else { 79 | mCacheRefCount--; 80 | } 81 | } 82 | 83 | // Check to see if recycle() can be called 84 | checkState(); 85 | 86 | } 87 | 88 | private synchronized void checkState() { 89 | 90 | // If the drawable cache and display ref counts = 0, and this drawable 91 | // has been displayed, then recycle 92 | if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed 93 | && hasValidBitmap()) { 94 | if (BuildConfig.DEBUG) { 95 | Log.d(TAG, "No longer being used or cached so recycling. " 96 | + toString()); 97 | } 98 | 99 | getBitmap().recycle(); 100 | } 101 | 102 | } 103 | 104 | private synchronized boolean hasValidBitmap() { 105 | Bitmap bitmap = getBitmap(); 106 | return bitmap != null && !bitmap.isRecycled(); 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 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 com.example.android.displayingbitmaps.util; 18 | 19 | import android.annotation.TargetApi; 20 | import android.os.Build; 21 | import android.os.Build.VERSION_CODES; 22 | import android.os.StrictMode; 23 | 24 | import com.example.android.displayingbitmaps.ui.ImageDetailActivity; 25 | import com.example.android.displayingbitmaps.ui.ImageGridActivity; 26 | 27 | /** 28 | * Class containing some static utility methods. 29 | */ 30 | public class Utils { 31 | private Utils() {}; 32 | 33 | 34 | @TargetApi(VERSION_CODES.HONEYCOMB) 35 | public static void enableStrictMode() { 36 | if (Utils.hasGingerbread()) { 37 | StrictMode.ThreadPolicy.Builder threadPolicyBuilder = 38 | new StrictMode.ThreadPolicy.Builder() 39 | .detectAll() 40 | .penaltyLog(); 41 | StrictMode.VmPolicy.Builder vmPolicyBuilder = 42 | new StrictMode.VmPolicy.Builder() 43 | .detectAll() 44 | .penaltyLog(); 45 | 46 | if (Utils.hasHoneycomb()) { 47 | threadPolicyBuilder.penaltyFlashScreen(); 48 | vmPolicyBuilder 49 | .setClassInstanceLimit(ImageGridActivity.class, 1) 50 | .setClassInstanceLimit(ImageDetailActivity.class, 1); 51 | } 52 | StrictMode.setThreadPolicy(threadPolicyBuilder.build()); 53 | StrictMode.setVmPolicy(vmPolicyBuilder.build()); 54 | } 55 | } 56 | 57 | public static boolean hasFroyo() { 58 | // Can use static final constants like FROYO, declared in later versions 59 | // of the OS since they are inlined at compile time. This is guaranteed behavior. 60 | return Build.VERSION.SDK_INT >= VERSION_CODES.FROYO; 61 | } 62 | 63 | public static boolean hasGingerbread() { 64 | return Build.VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD; 65 | } 66 | 67 | public static boolean hasHoneycomb() { 68 | return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB; 69 | } 70 | 71 | public static boolean hasHoneycombMR1() { 72 | return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1; 73 | } 74 | 75 | public static boolean hasJellyBean() { 76 | return Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN; 77 | } 78 | 79 | public static boolean hasKitKat() { 80 | return Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Application/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/Application/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-hdpi/tile.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/Application/src/main/res/drawable-hdpi/tile.9.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/Application/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-nodpi/empty_photo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/Application/src/main/res/drawable-nodpi/empty_photo.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/Application/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/Application/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /Application/src/main/res/drawable/photogrid_list_selector.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Application/src/main/res/layout/image_detail_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 21 | 22 | 27 | 28 | 33 | 34 | -------------------------------------------------------------------------------- /Application/src/main/res/layout/image_detail_pager.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 22 | 23 | -------------------------------------------------------------------------------- /Application/src/main/res/layout/image_grid_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 28 | 29 | -------------------------------------------------------------------------------- /Application/src/main/res/menu/main_menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 |

18 | 19 | 24 | 25 | -------------------------------------------------------------------------------- /Application/src/main/res/values-large/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 148dp 21 | 2dp 22 | 23 | -------------------------------------------------------------------------------- /Application/src/main/res/values-sw600dp/template-dimens.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | @dimen/margin_huge 22 | @dimen/margin_medium 23 | 24 | 25 | -------------------------------------------------------------------------------- /Application/src/main/res/values-sw600dp/template-styles.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Application/src/main/res/values-v11/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 25 | 26 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Application/src/main/res/values-v11/template-styles.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Application/src/main/res/values-xlarge/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 198dp 21 | 2dp 22 | 23 | -------------------------------------------------------------------------------- /Application/src/main/res/values/base-strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | DisplayingBitmaps 20 | 21 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Application/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | #1Affffff 21 | #80000000 22 | 23 | 24 | -------------------------------------------------------------------------------- /Application/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 100dp 21 | 1dp 22 | 23 | -------------------------------------------------------------------------------- /Application/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | Clear Caches 21 | Caches have been cleared 22 | Image Thumbnail 23 | No network connection found 24 | 25 | -------------------------------------------------------------------------------- /Application/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 28 | 29 | -------------------------------------------------------------------------------- /Application/src/main/res/values/template-dimens.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 4dp 22 | 8dp 23 | 16dp 24 | 32dp 25 | 64dp 26 | 27 | 28 | 29 | @dimen/margin_medium 30 | @dimen/margin_medium 31 | 32 | 33 | -------------------------------------------------------------------------------- /Application/src/main/res/values/template-styles.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 34 | 35 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Application/tests/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 35 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Application/tests/src/com/example/android/displayingbitmaps/tests/SampleTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 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 com.example.android.displayingbitmaps.tests; 17 | 18 | import com.example.android.displayingbitmaps.ui.ImageGridActivity; 19 | 20 | import android.test.ActivityInstrumentationTestCase2; 21 | 22 | /** 23 | * Tests for DisplayingBitmaps sample. 24 | */ 25 | public class SampleTests extends ActivityInstrumentationTestCase2 { 26 | 27 | private ImageGridActivity mTestActivity; 28 | 29 | public SampleTests() { 30 | super(ImageGridActivity.class); 31 | } 32 | 33 | @Override 34 | protected void setUp() throws Exception { 35 | super.setUp(); 36 | 37 | // Starts the activity under test using the default Intent with: 38 | // action = {@link Intent#ACTION_MAIN} 39 | // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK} 40 | // All other fields are null or empty. 41 | mTestActivity = getActivity(); 42 | } 43 | 44 | /** 45 | * Test if the test fixture has been set up correctly. 46 | */ 47 | public void testPreconditions() { 48 | //Try to add a message to add context to your assertions. These messages will be shown if 49 | //a tests fails and make it easy to understand why a test failed 50 | assertNotNull("mTestActivity is null", mTestActivity); 51 | } 52 | 53 | /** 54 | * Add more tests below. 55 | */ 56 | 57 | } 58 | -------------------------------------------------------------------------------- /CONTRIB.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 9 | 10 | * If you are an individual writing original source code and you're sure you 11 | own the intellectual property, then you'll need to sign an [individual CLA] 12 | (https://developers.google.com/open-source/cla/individual). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA] 15 | (https://developers.google.com/open-source/cla/corporate). 16 | 17 | Follow either of the two links above to access the appropriate CLA and 18 | instructions for how to sign and return it. Once we receive it, we'll be able to 19 | accept your pull requests. 20 | 21 | ## Contributing A Patch 22 | 23 | 1. Submit an issue describing your proposed change to the repo in question. 24 | 1. The repo owner will respond to your issue promptly. 25 | 1. If your proposed change is accepted, and you haven't already done so, sign a 26 | Contributor License Agreement (see details above). 27 | 1. Fork the desired repo, develop and test your code changes. 28 | 1. Ensure that your code adheres to the existing style in the sample to which 29 | you are contributing. Refer to the 30 | [Android Code Style Guide] 31 | (https://source.android.com/source/code-style.html) for the 32 | recommended coding standards for this organization. 33 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 34 | 1. Submit a pull request. 35 | 36 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 9 | 10 | * If you are an individual writing original source code and you're sure you 11 | own the intellectual property, then you'll need to sign an [individual CLA] 12 | (https://cla.developers.google.com). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA] 15 | (https://cla.developers.google.com). 16 | 17 | Follow either of the two links above to access the appropriate CLA and 18 | instructions for how to sign and return it. Once we receive it, we'll be able to 19 | accept your pull requests. 20 | 21 | ## Contributing A Patch 22 | 23 | 1. Submit an issue describing your proposed change to the repo in question. 24 | 1. The repo owner will respond to your issue promptly. 25 | 1. If your proposed change is accepted, and you haven't already done so, sign a 26 | Contributor License Agreement (see details above). 27 | 1. Fork the desired repo, develop and test your code changes. 28 | 1. Ensure that your code adheres to the existing style in the sample to which 29 | you are contributing. Refer to the 30 | [Android Code Style Guide] 31 | (https://source.android.com/source/code-style.html) for the 32 | recommended coding standards for this organization. 33 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 34 | 1. Submit a pull request. 35 | 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Android DisplayingBitmaps Sample 3 | =================================== 4 | 5 | Sample demonstrating how to load large bitmaps efficiently off the main UI thread, 6 | caching bitmaps (both in memory and on disk), managing bitmap memory and displaying 7 | bitmaps in UI elements such as ViewPager and ListView/GridView. 8 | 9 | Introduction 10 | ------------ 11 | 12 | This is a sample application for the Android Training class [Displaying Bitmaps Efficiently][1]. 13 | 14 | It demonstrates how to load large bitmaps efficiently off the main UI thread, caching 15 | bitmaps (both in memory and on disk), managing bitmap memory and displaying bitmaps 16 | in UI elements such as ViewPager and ListView/GridView. 17 | 18 | [1]: http://developer.android.com/training/displaying-bitmaps/ 19 | 20 | Pre-requisites 21 | -------------- 22 | 23 | - Android SDK v22 24 | - Android Build Tools v22.0.1 25 | - Android Support Repository 26 | 27 | Screenshots 28 | ------------- 29 | 30 | Screenshot Screenshot 31 | 32 | Getting Started 33 | --------------- 34 | 35 | This sample uses the Gradle build system. To build this project, use the 36 | "gradlew build" command or use "Import Project" in Android Studio. 37 | 38 | Support 39 | ------- 40 | 41 | - Google+ Community: https://plus.google.com/communities/105153134372062985968 42 | - Stack Overflow: http://stackoverflow.com/questions/tagged/android 43 | 44 | If you've found an error in this sample, please file an issue: 45 | https://github.com/googlesamples/android-DisplayingBitmaps 46 | 47 | Patches are encouraged, and may be submitted by forking this project and 48 | submitting a pull request through GitHub. Please see CONTRIBUTING.md for more details. 49 | 50 | License 51 | ------- 52 | 53 | Copyright 2014 The Android Open Source Project, Inc. 54 | 55 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 56 | license agreements. See the NOTICE file distributed with this work for 57 | additional information regarding copyright ownership. The ASF licenses this 58 | file to you under the Apache License, Version 2.0 (the "License"); you may not 59 | use this file except in compliance with the License. You may obtain a copy of 60 | the License at 61 | 62 | http://www.apache.org/licenses/LICENSE-2.0 63 | 64 | Unless required by applicable law or agreed to in writing, software 65 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 66 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 67 | License for the specific language governing permissions and limitations under 68 | the License. 69 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taisukeoe/DL4J-Android-Example/6327e1edef4c1bc34fb5881571a981c29fa9bc0e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /packaging.yaml: -------------------------------------------------------------------------------- 1 | # GOOGLE SAMPLE PACKAGING DATA 2 | # 3 | # This file is used by Google as part of our samples packaging process. 4 | # End users may safely ignore this file. It has no relevance to other systems. 5 | --- 6 | 7 | status: PUBLISHED 8 | technologies: [Android] 9 | categories: [UI] 10 | languages: [Java] 11 | solutions: [Mobile] 12 | github: googlesamples/android-DisplayingBitmaps 13 | level: BEGINNER 14 | icon: DisplayingBitmapsSample/src/main/res/drawable-xxhdpi/ic_launcher.png 15 | license: apache2-android 16 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include 'Application' 2 | --------------------------------------------------------------------------------