List of usage examples for android.graphics.drawable BitmapDrawable getBitmap
public final Bitmap getBitmap()
From source file:com.utils.ImageCache.java
/** * Get from memory cache./*w ww . j av a2 s . co m*/ * * @param data Unique identifier for which item to get * @return The bitmap drawable if found in cache, null otherwise */ public BitmapDrawable getBitmapFromMemCache(String data) { BitmapDrawable memValue = null; if (mMemoryCache != null) { memValue = mMemoryCache.get(data); } if (memValue != null && memValue.getBitmap().isRecycled()) { memValue = null; Log.d(TAG, "Bitmap was recycled :)"); } if (BuildConfig.DEBUG && memValue != null) { Log.d(TAG, "Memory cache hit"); } return memValue; }
From source file:io.indy.seni.util.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *//*from w w w .j a va 2 s . co m*/ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; // Set up memory cache if (mCacheParams.memoryCacheEnabled) { if (BuildConfig.DEBUG) { Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")"); } // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be // populated into the inBitmap field of BitmapFactory.Options. Note that the set is // of SoftReferences which will actually not be very effective due to the garbage // collector being aggressive clearing Soft/WeakReferences. A better approach // would be to use a strongly references bitmaps, however this would require some // balancing of memory usage between this set and the bitmap LruCache. It would also // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean // the size would need to be precise, from KitKat onward the size would just need to // be the upper bound (due to changes in how inBitmap can re-use bitmaps). mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { /** * Notify the removed entry that is no longer being cached */ @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { // The removed entry is a standard BitmapDrawable // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap())); } /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, BitmapDrawable value) { final int bitmapSize = getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } }
From source file:com.radicaldynamic.groupinform.activities.LauncherActivity.java
private void displaySplash() { // Don't show the splash screen if this app appears to be registered if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString(InformOnlineState.DEVICE_ID, null) instanceof String) { return;//from w ww. j a va 2 s .com } // Fetch the splash screen Drawable Drawable image = null; try { // Attempt to load the configured default splash screen // The following code only works in 1.6+ // BitmapDrawable bitImage = new BitmapDrawable(getResources(), FileUtils.SPLASH_SCREEN_FILE_PATH); BitmapDrawable bitImage = new BitmapDrawable( FileUtilsExtended.EXTERNAL_FILES + File.separator + FileUtilsExtended.SPLASH_SCREEN_FILE); if (bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) { image = bitImage; } } catch (Exception e) { // TODO: log exception for debugging? } // TODO: rework if (image == null) { // no splash provided... // if (FileUtils.storageReady() && !((new File(FileUtils.DEFAULT_CONFIG_PATH)).exists())) { // Show the built-in splash image if the config directory // does not exist. Otherwise, suppress the icon. image = getResources().getDrawable(R.drawable.gc_color); // } if (image == null) return; } // Create ImageView to hold the Drawable... ImageView view = new ImageView(getApplicationContext()); // Initialise it with Drawable and full-screen layout parameters view.setImageDrawable(image); int width = getWindowManager().getDefaultDisplay().getWidth(); int height = getWindowManager().getDefaultDisplay().getHeight(); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width, height, 0); view.setLayoutParams(lp); view.setScaleType(ScaleType.CENTER); view.setBackgroundColor(Color.WHITE); // And wrap the image view in a frame layout so that the full-screen layout parameters are honoured FrameLayout layout = new FrameLayout(getApplicationContext()); layout.addView(view); // Create the toast and set the view to be that of the FrameLayout mSplashToast = Toast.makeText(getApplicationContext(), "splash screen", Toast.LENGTH_LONG); mSplashToast.setView(layout); mSplashToast.setGravity(Gravity.CENTER, 0, 0); mSplashToast.show(); }
From source file:com.yooiistudios.newskit.core.cache.volley.ImageCache.java
@Override public Bitmap getBitmap(String url) { BitmapDrawable bitmapDrawable = getBitmapFromMemCache(url); Bitmap bitmap;//from w ww . ja v a2 s . co m if (bitmapDrawable != null) { bitmap = bitmapDrawable.getBitmap(); } else { bitmap = getBitmapFromDiskCache(url); } return bitmap; }
From source file:net.sourceforge.servestream.bitmap.ImageWorker.java
/** * Load an image specified by the data parameter into an ImageView (override * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and * disk cache will be used if an {@link ImageCache} has been added using * {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}. If the * image is found in the memory cache, it is set immediately, otherwise an {@link AsyncTask} * will be created to asynchronously load the bitmap. * * @param data The URL of the image to download. * @param imageView The ImageView to bind the downloaded image to. *///from w w w . j av a 2s. c om public Bitmap loadImage(Object data) { if (data == null) { return null; } BitmapDrawable value = null; if (mImageCache != null) { value = mImageCache.getBitmapFromMemCache(String.valueOf(data)); } if (value != null) { // Bitmap found in memory cache return value.getBitmap(); } else { //BEGIN_INCLUDE(load_bitmap_in_background) if (BuildConfig.DEBUG) { Log.d(TAG, "doInBackground - starting work"); } final String dataString = String.valueOf(data); Bitmap bitmap = null; BitmapDrawable drawable = null; // Wait here if work is paused and the task is not cancelled synchronized (mPauseWorkLock) { while (mPauseWork) { try { mPauseWorkLock.wait(); } catch (InterruptedException e) { } } } // If the image cache is available and this task has not been cancelled by another // thread and the ImageView that was originally bound to this task is still bound back // to this task and our "exit early" flag is not set then try and fetch the bitmap from // the cache if (mImageCache != null && !mExitTasksEarly) { bitmap = mImageCache.getBitmapFromDiskCache(dataString); } // If the bitmap was not found in the cache and this task has not been cancelled by // another thread and the ImageView that was originally bound to this task is still // bound back to this task and our "exit early" flag is not set, then call the main // process method (as implemented by a subclass) if (bitmap == null && !mExitTasksEarly) { bitmap = processBitmap(data); } // If the bitmap was processed and the image cache is available, then add the processed // bitmap to the cache for future use. Note we don't check if the task was cancelled // here, if it was, and the thread is still running, we may as well add the processed // bitmap to our cache as it might be used again in the future if (bitmap != null) { if (Utils.hasHoneycomb()) { // Running on Honeycomb or newer, so wrap in a standard BitmapDrawable drawable = new BitmapDrawable(mResources, bitmap); } else { // Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable // which will recycle automagically drawable = new RecyclingBitmapDrawable(mResources, bitmap); } if (mImageCache != null) { mImageCache.addBitmapToCache(dataString, drawable); } if (BuildConfig.DEBUG) { Log.d(TAG, "doInBackground - finished work"); } return drawable.getBitmap(); //END_INCLUDE(load_bitmap_in_background) } else { if (BuildConfig.DEBUG) { Log.d(TAG, "doInBackground - finished work"); } return null; //END_INCLUDE(load_bitmap_in_background) } } }
From source file:com.acceleratedio.pac_n_zoom.AnimActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anm); orgnlImageView = (ImageView) findViewById(R.id.imageView); orgnlImageView.setMaxHeight(800);//from w ww. j a va 2 s . co m orgnlImageView.setMaxWidth(600); crt_ctx = this; BitmapFactory.Options bmp_opt = new BitmapFactory.Options(); bmp_opt.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT; // - Now we need to set the GUI ImageView data with data read from the picked file. DcodRszdBmpFil dcodRszdBmpFil = new DcodRszdBmpFil(); Bitmap bmp = dcodRszdBmpFil.DcodRszdBmpFil(SelectImageActivity.orgFil, bmp_opt); // Now we need to set the GUI ImageView data with the orginal file selection. orgnlImageView.setImageBitmap(bmp); orgnl_iv_wdth = bmp.getWidth(); orgnl_iv_hght = bmp.getHeight(); final RelativeLayout rel_anm_lo = (RelativeLayout) findViewById(R.id.activity_anm_lo); scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener()); orgnlImageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getPointerCount() > 1 || flgInScale) { scaleGestureDetector.onTouchEvent(event); return true; } int end_hrz; int end_vrt; final int pointerIndex; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: pointerIndex = MotionEventCompat.getActionIndex(event); bgn_hrz = (int) MotionEventCompat.getX(event, pointerIndex); bgn_vrt = (int) MotionEventCompat.getY(event, pointerIndex); String log_str = "Beginning coordinates: Horz = " + String.valueOf(bgn_hrz) + "; Vert = " + String.valueOf(bgn_vrt); Log.d("OnTouchListener", log_str); orlp = (RelativeLayout.LayoutParams) orgnlImageView.getLayoutParams(); bgn_top = (int) orlp.topMargin; bgn_lft = (int) orlp.leftMargin; // To prevent an initial jump of the magnifier, aposX and aPosY must // have the values from the magnifier frame if (aPosX == 0) aPosX = orgnlImageView.getX(); if (aPosY == 0) aPosY = orgnlImageView.getY(); break; case MotionEvent.ACTION_MOVE: pointerIndex = MotionEventCompat.getActionIndex(event); float crt_hrz = MotionEventCompat.getX(event, pointerIndex); float crt_vrt = MotionEventCompat.getY(event, pointerIndex); final float dx = crt_hrz - bgn_hrz; final float dy = crt_vrt - bgn_vrt; aPosX += dx; aPosY += dy; orgnlImageView.setX(aPosX); orgnlImageView.setY(aPosY); log_str = "Current Position: Horz = " + String.valueOf(crt_hrz) + "; Vert = " + String.valueOf(crt_vrt); Log.d("OnTouchListener", log_str); break; case MotionEvent.ACTION_UP: pointerIndex = MotionEventCompat.getActionIndex(event); end_hrz = (int) MotionEventCompat.getX(event, pointerIndex); end_vrt = (int) MotionEventCompat.getY(event, pointerIndex); } rel_anm_lo.invalidate(); return true; } }); sav_anm_btn = (Button) findViewById(R.id.sav_btn); sav_anm_btn.setOnClickListener(new View.OnClickListener() { public void onClick(View vw) { onClickFlg = 1; RelativeLayout rel_anm_lo = (RelativeLayout) findViewById(R.id.activity_anm_lo); rel_anm_lo.removeView(vw); Bitmap tnBmp = getWrtBmp("thumbnail", rel_anm_lo, 40); tnBmp.recycle(); int vw_nmbr = anmViews.size(); for (int vw_mbr = 1; vw_mbr < vw_nmbr; vw_mbr += 1) { anim_view = anmViews.get(vw_mbr); if (anim_view != null) { Animation crt_anm = anim_view.getAnimation(); if (crt_anm != null) crt_anm.cancel(); anim_view.setAnimation(null); rel_anm_lo.removeView(anim_view); // Garbage collect the bitmap Drawable drawable = anim_view.getDrawable(); if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap anim_bmp = bitmapDrawable.getBitmap(); anim_bmp.recycle(); } } } Bitmap orgnlImageBmp = getWrtBmp("bgimg", rel_anm_lo, 90); orgnlImageWdth = Integer.toString(orgnlImageBmp.getWidth()); orgnlImageHght = Integer.toString(orgnlImageBmp.getHeight()); anmViews.clear(); unbindDrawables(rel_anm_lo); ((RelativeLayout) rel_anm_lo).removeAllViews(); orgnlImageBmp.recycle(); crt_ctx = null; orgnlImageView = null; Intent intent = new Intent(AnimActivity.this, com.acceleratedio.pac_n_zoom.SaveAnmActivity.class); startActivity(intent); } }); progress = ProgressDialog.show(crt_ctx, "Loading the animation", "dialog message", true); GetRequest get_svg_img = new GetRequest(); get_svg_img.execute(""); }
From source file:com.example.zayankovsky.homework.ui.ImageDetailActivity.java
private Uri getUriForImage() { BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable(); if (drawable == null) { return null; }//from w w w . j a va 2 s .com // Get the files/images subdirectory of internal storage File imagesDir = new File(getFilesDir(), "images"); if (!imagesDir.mkdirs() && !imagesDir.isDirectory()) { return null; } File imageFile = new File(imagesDir, ImageWorker.getTitle() + ".png"); OutputStream outputStream = null; try { try { outputStream = new FileOutputStream(imageFile); drawable.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, outputStream); } finally { if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return null; } // Use the FileProvider to get a content URI try { return FileProvider.getUriForFile(this, "com.example.zayankovsky.homework.fileprovider", imageFile); } catch (IllegalArgumentException e) { return null; } }
From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java
/** * updateNotification is *the* main function for building the actual notification handed to * the NotificationManager/*from w w w.jav a 2 s . c om*/ * @param context * @param isNew if we've got a new message, show the ticker * @param uniqueThreadCount */ private static void updateNotification(Context context, boolean isNew, int uniqueThreadCount) { // TDH Log.d("NotificationDebug", "updateNotification()"); // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } // TDH Log.d("NotificationDebug", "Notifications not enabled!"); return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. int messageCount = sNotificationSet.size(); // TDH: Log.d("NotificationDebug", "messageCount: " + messageCount); if (messageCount == 0) { Log.d("NotificationDebug", "WTF. Should have at least one message."); return; } NotificationInfo mostRecentNotification = sNotificationSet.first(); // TDH: Use NotificationCompat2 (and in other places but it is obvious where). final NotificationCompat2.Builder noti = new NotificationCompat2.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } // TDH Log.d("NotificationDebug", "Creating TaskStackBuilder"); TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // TDH Log.d("NotificationDebug", "Created TaskStackBuilder. UniqueThreadCount: " + uniqueThreadCount); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable) mostRecentNotification.mSender.getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap(avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // TDH Log.d("NotificationDebug", "title: " + title); // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent(taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)); // TDH: Can't do these yet. // .addKind(Notification.KIND_MESSAGE) // .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // // from a favorite. int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String vibrateWhen; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false) ? context.getString(R.string.prefDefault_vibrate_true) : context.getString(R.string.prefDefault_vibrate_false); } else { vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen); } boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; if (vibrateAlways || vibrateSilent && nowSilent) { defaults |= Notification.DEFAULT_VIBRATE; } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); final Notification notification; if (messageCount == 1) { // We've got a single message // TDH Log.d("NotificationDebug", "Single message, with text: " + mostRecentNotification.formatBigMessage(context)); // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new NotificationCompat2.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)).build(); } else { // Show a single notification -- big style with the text of the whole message notification = new NotificationCompat2.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)).build(); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new NotificationCompat2.BigTextStyle(noti).bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ").build(); } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size()); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = sNotificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); NotificationCompat2.InboxStyle inboxStyle = new NotificationCompat2.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } // TDH Log.d("NotificationDebug", "Showing notification: " + notification); nm.notify(NOTIFICATION_ID, notification); }
From source file:com.github.programmerr47.vkgroups.imageloading.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *//*from w ww .j av a 2 s. co m*/ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; //BEGIN_INCLUDE(init_memory_cache) // Set up memory cache if (mCacheParams.memoryCacheEnabled) { // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be // populated into the inBitmap field of BitmapFactory.Options. Note that the set is // of SoftReferences which will actually not be very effective due to the garbage // collector being aggressive clearing Soft/WeakReferences. A better approach // would be to use a strongly references bitmaps, however this would require some // balancing of memory usage between this set and the bitmap LruCache. It would also // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean // the size would need to be precise, from KitKat onward the size would just need to // be the upper bound (due to changes in how inBitmap can re-use bitmaps). mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { /** * Notify the removed entry that is no longer being cached */ @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later mReusableBitmaps.add(new SoftReference<>(oldValue.getBitmap())); } /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, BitmapDrawable value) { final int bitmapSize = getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } //END_INCLUDE(init_memory_cache) // By default the disk cache is not initialized here as it should be initialized // on a separate thread due to disk access. if (cacheParams.initDiskCacheOnCreate) { // Set up disk cache initDiskCache(); } }
From source file:com.amachikhin.vkmachikhin.utils.image_cache.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *//* w w w. jav a 2s . c o m*/ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; //BEGIN_INCLUDE(init_memory_cache) // Set up memory cache if (mCacheParams.memoryCacheEnabled) { if (BuildConfig.DEBUG) { Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")"); } // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be // populated into the inBitmap field of BitmapFactory.Options. Note that the set is // of SoftReferences which will actually not be very effective due to the garbage // collector being aggressive clearing Soft/WeakReferences. A better approach // would be to use a strongly references bitmaps, however this would require some // balancing of memory usage between this set and the bitmap LruCache. It would also // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean // the size would need to be precise, from KitKat onward the size would just need to // be the upper bound (due to changes in how inBitmap can re-use bitmaps). mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { /** * Notify the removed entry that is no longer being cached */ @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { // The removed entry is a standard BitmapDrawable // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap())); } /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, BitmapDrawable value) { final int bitmapSize = getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } //END_INCLUDE(init_memory_cache) // By default the disk cache is not initialized here as it should be initialized // on a separate thread due to disk access. if (cacheParams.initDiskCacheOnCreate) { // Set up disk cache initDiskCache(); } }