コード例 #1
0
  /** 先从缓存中找,有则返回图片,没有则从网络获取 */
  @Override
  public Bitmap getBitmap(String url) {
    /** 先从缓存中找,有则返回,没有则返回null */
    Bitmap bitmap = mCache.get(url);

    if (bitmap == null) {
      String fileName = url.substring(url.lastIndexOf("/") + 1);
      /** 如果为null,则缓存中没有,从本地SD卡缓存中找 */
      File cacheDir = new File(Constants.IMG_CACHE_DIR_PATH);
      File[] cacheFiles = cacheDir.listFiles();
      if (cacheFiles != null) {
        int i = 0;
        for (; i < cacheFiles.length; i++) {
          if (TextUtils.equals(fileName, cacheFiles[i].getName())) break;
        }
        /** 若找到则返回bitmap否则返回null */
        if (i < cacheFiles.length) {
          bitmap = getSDBitmap(Constants.IMG_CACHE_DIR_PATH + "/" + fileName);
          /** 将从SD卡中获取的bitmap放入缓存中 */
          mCache.put(url, bitmap);
        }
      }
    }
    /** 是否下载图片 */
    if (Constants.network_type != ConnectivityManager.TYPE_WIFI && !Constants.isLoadImg) {
      LogUtils.d("ImageLoad", "不下载图片");
      return BitmapFactory.decodeStream(getClass().getResourceAsStream("/assets/img_book_no.png"));
    }
    return bitmap;
  }
コード例 #2
0
 /**
  * Try to continue chat conversation
  *
  * @param continueChat the intent to continue the chat conversation
  * @param chatId the chat ID
  * @return the unique ID to be used to create the pending intent if chat conversation is not on
  *     foreground or null if continuing the conversation succeeded
  */
 public Integer tryContinueChatConversation(Intent continueChat, String chatId) {
   if (mForegroundInfo.isConversationOnForeground(chatId)) {
     /*
      * Do not display notification if activity is on foreground for this chatId
      */
     Integer pendingIntentId = mPendingNotificationIdCache.get(chatId);
     if (pendingIntentId != null) {
       mPendingNotificationIdCache.remove(chatId);
       mNotifManager.cancel(pendingIntentId);
     }
     /* This will trigger onNewIntent for the target activity */
     mCtx.startActivity(continueChat);
     return null;
   }
   Integer uniquePendingIntentId = mPendingNotificationIdCache.get(chatId);
   if (uniquePendingIntentId == null) {
     /*
      * If the PendingIntent has the same operation, action, data, categories, components,
      * and flags it will be replaced. Invitation should be notified individually so we use a
      * random generator to provide a unique request code and reuse it for the notification.
      */
     uniquePendingIntentId = Utils.getUniqueIdForPendingIntent();
     mPendingNotificationIdCache.put(chatId, uniquePendingIntentId);
   }
   return uniquePendingIntentId;
 }
コード例 #3
0
 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
     throws FileNotFoundException {
   final String uuid = message.getUuid();
   final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
   Bitmap thumbnail = cache.get(uuid);
   if ((thumbnail == null) && (!cacheOnly)) {
     synchronized (cache) {
       thumbnail = cache.get(uuid);
       if (thumbnail != null) {
         return thumbnail;
       }
       DownloadableFile file = getFile(message);
       if (file.getMimeType().startsWith("video/")) {
         thumbnail = getVideoPreview(file, size);
       } else {
         Bitmap fullsize = getFullsizeImagePreview(file, size);
         if (fullsize == null) {
           throw new FileNotFoundException();
         }
         thumbnail = resize(fullsize, size);
         thumbnail = rotate(thumbnail, getRotation(file));
       }
       this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
     }
   }
   return thumbnail;
 }
コード例 #4
0
  boolean update(ScanResult result) {
    if (matches(result)) {
      /* Update the LRU timestamp, if BSSID exists */
      mScanResultCache.get(result.BSSID);

      /* Add or update the scan result for the BSSID */
      mScanResultCache.put(result.BSSID, result);

      int oldLevel = getLevel();
      int oldRssi = getRssi();
      mSeen = getSeen();
      mRssi = (getRssi() + oldRssi) / 2;
      int newLevel = getLevel();

      if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
        mAccessPointListener.onLevelChanged(this);
      }
      // This flag only comes from scans, is not easily saved in config
      if (security == SECURITY_PSK) {
        pskType = getPskType(result);
      }

      if (mAccessPointListener != null) {
        mAccessPointListener.onAccessPointChanged(this);
      }

      return true;
    }
    return false;
  }
コード例 #5
0
 public AccessPoint(Context context, Bundle savedState) {
   mContext = context;
   mConfig = savedState.getParcelable(KEY_CONFIG);
   if (mConfig != null) {
     loadConfig(mConfig);
   }
   if (savedState.containsKey(KEY_SSID)) {
     ssid = savedState.getString(KEY_SSID);
   }
   if (savedState.containsKey(KEY_SECURITY)) {
     security = savedState.getInt(KEY_SECURITY);
   }
   if (savedState.containsKey(KEY_PSKTYPE)) {
     pskType = savedState.getInt(KEY_PSKTYPE);
   }
   mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
   if (savedState.containsKey(KEY_NETWORKINFO)) {
     mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
   }
   if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
     ArrayList<ScanResult> scanResultArrayList =
         savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
     mScanResultCache.evictAll();
     for (ScanResult result : scanResultArrayList) {
       mScanResultCache.put(result.BSSID, result);
     }
   }
   update(mConfig, mInfo, mNetworkInfo);
   mRssi = getRssi();
   mSeen = getSeen();
 }
コード例 #6
0
 /**
  * If values are passed in, replaces any cached cursor with one containing new values, and then
  * closes the previously cached one (if any, and if not in use) If values are not passed in,
  * removes the row from cache If the row was locked, unlock it
  *
  * @param id the id of the row
  * @param values new ContentValues for the row (or null if row should simply be removed)
  * @param wasLocked whether or not the row was locked; if so, the lock will be removed
  */
 private void unlockImpl(String id, ContentValues values, boolean wasLocked) {
   Cursor c = get(id);
   if (c != null) {
     if (MailActivityEmail.DEBUG && DEBUG_CACHE) {
       LogUtils.d(mLogTag, "=========== Unlocking cache for: " + id);
     }
     if (values != null && !sLockCache) {
       MatrixCursor cursor = getMatrixCursor(id, mBaseProjection, values);
       if (cursor != null) {
         if (MailActivityEmail.DEBUG && DEBUG_CACHE) {
           LogUtils.d(mLogTag, "=========== Recaching with new values: " + id);
         }
         cursor.moveToFirst();
         mLruCache.put(id, cursor);
       } else {
         mLruCache.remove(id);
       }
     } else {
       mLruCache.remove(id);
     }
     // If there are no cursors using the old cached cursor, close it
     if (!sActiveCursors.contains(c)) {
       c.close();
     }
   }
   if (wasLocked) {
     mLockMap.subtract(id);
   }
 }
コード例 #7
0
  @Override
  protected LinkedList<RT> doInBackground(Object... params) {
    String url = null;

    // Only cache
    if (!query.isIgnoreCache()) {
      try {
        url = query.createUrl();
      } catch (Exception e) {
        JLog.wtf("Trying to get query url", e);
      }

      synchronized (cachedQueries) {
        Object result = cachedQueries.get(url);
        if (result != null) {
          JLog.v("Cached query returned: " + url);
          return (LinkedList<RT>) result;
        }
      }
    }

    try {
      LinkedList<RT> result = query.get(header, clazz);
      if (result != null && url != null) {
        synchronized (cachedQueries) {
          cachedQueries.put(url, result);
        }
      }
      return result;
    } catch (Exception e) {
      JLog.e(query.getClass().getSimpleName() + ".get()", e);
    }
    return null;
  }
コード例 #8
0
ファイル: Storage.java プロジェクト: salvprest/Camera2
 /**
  * Add or replace placeholder for a new image that does not exist yet.
  *
  * @param uri the uri of the placeholder to replace, or null if this is a new one
  * @param placeholder the placeholder image
  * @return A URI used to reference this placeholder
  */
 public static void replacePlaceholder(Uri uri, Bitmap placeholder) {
   Log.v(TAG, "session bitmap cache size: " + sSessionsToPlaceholderBitmap.size());
   Point size = new Point(placeholder.getWidth(), placeholder.getHeight());
   sSessionsToSizes.put(uri, size);
   sSessionsToPlaceholderBitmap.put(uri, placeholder);
   Integer currentVersion = sSessionsToPlaceholderVersions.get(uri);
   sSessionsToPlaceholderVersions.put(uri, currentVersion == null ? 0 : currentVersion + 1);
 }
コード例 #9
0
  public void removeCache(String url) {
    Log.v("마이볼리 캐쉬 사이즈", String.valueOf(cache.size()));
    Log.v("마이볼리 캐쉬", String.valueOf(cache));
    Log.v("url name", url);

    if (cache.remove(url) == null) {
      Log.v("url", "null");
    }

    Log.v("마이볼리 캐쉬 사이즈", String.valueOf(cache.size()));
    Log.v("마이볼리 캐쉬", String.valueOf(cache));
  }
コード例 #10
0
ファイル: TypefaceSpan.java プロジェクト: qiminl/Lifary_oldb
  /** Load the {@link Typeface} and apply to a {@link Spannable}. */
  public TypefaceSpan(Context context, String typefaceName) {
    mTypeface = sTypefaceCache.get(typefaceName);

    if (mTypeface == null) {
      mTypeface =
          Typeface.createFromAsset(
              context.getApplicationContext().getAssets(), String.format("fonts/%s", typefaceName));

      // Cache the loaded Typeface
      sTypefaceCache.put(typefaceName, mTypeface);
    }
  }
コード例 #11
0
  private Loader getInstanceUncheckedLocked(String documentId) throws FileNotFoundException {
    try {
      final ParsedDocumentId id = ParsedDocumentId.fromDocumentId(documentId, mIdDelimiter);
      if (mArchives.get(id.mArchiveId) != null) {
        return mArchives.get(id.mArchiveId);
      }

      final Cursor cursor =
          mProvider.queryDocument(
              id.mArchiveId, new String[] {Document.COLUMN_MIME_TYPE, COLUMN_LOCAL_FILE_PATH});
      cursor.moveToFirst();
      final String mimeType = cursor.getString(cursor.getColumnIndex(Document.COLUMN_MIME_TYPE));
      Preconditions.checkArgument(isSupportedArchiveType(mimeType), "Unsupported archive type.");
      final int columnIndex = cursor.getColumnIndex(COLUMN_LOCAL_FILE_PATH);
      final String localFilePath = columnIndex != -1 ? cursor.getString(columnIndex) : null;
      final File localFile = localFilePath != null ? new File(localFilePath) : null;
      final Uri notificationUri = cursor.getNotificationUri();
      final Loader loader = new Loader(mProvider, localFile, id, mIdDelimiter, notificationUri);

      // Remove the instance from mArchives collection once the archive file changes.
      if (notificationUri != null) {
        final LruCache<String, Loader> finalArchives = mArchives;
        mProvider
            .getContext()
            .getContentResolver()
            .registerContentObserver(
                notificationUri,
                false,
                new ContentObserver(null) {
                  @Override
                  public void onChange(boolean selfChange, Uri uri) {
                    synchronized (mArchives) {
                      final Loader currentLoader = mArchives.get(id.mArchiveId);
                      if (currentLoader == loader) {
                        mArchives.remove(id.mArchiveId);
                      }
                    }
                  }
                });
      }

      mArchives.put(id.mArchiveId, loader);
      return loader;
    } catch (IOException e) {
      // DocumentsProvider doesn't use IOException. For consistency convert it to
      // IllegalStateException.
      throw new IllegalStateException(e);
    }
  }
コード例 #12
0
 public V get(K key) {
   V val = permanent.get(key);
   if (val == null) {
     return evictable.get(key);
   }
   return val;
 }
コード例 #13
0
 @Override
 public void putBitmap(final String url, final Bitmap bitmap) {
   if (isCache) {
     mMemoryCache.put(url, bitmap);
     setDiskCache(url, bitmap);
   }
 }
コード例 #14
0
 public synchronized Cursor putCursorImpl(
     Cursor c, String id, String[] projection, CacheToken token) {
   try {
     if (!token.isValid()) {
       if (MailActivityEmail.DEBUG && DEBUG_CACHE) {
         LogUtils.d(mLogTag, "============ Stale token for " + id);
       }
       mStats.mStaleCount++;
       return c;
     }
     if (c != null && Arrays.equals(projection, mBaseProjection) && !sLockCache) {
       if (MailActivityEmail.DEBUG && DEBUG_CACHE) {
         LogUtils.d(mLogTag, "============ Caching cursor for: " + id);
       }
       // If we've already cached this cursor, invalidate the older one
       Cursor existingCursor = get(id);
       if (existingCursor != null) {
         unlockImpl(id, null, false);
       }
       mLruCache.put(id, c);
       return new CachedCursor(c, this, id);
     }
     return c;
   } finally {
     mTokenList.remove(token);
   }
 }
コード例 #15
0
 @Override
 public void putBitmap(String url, Bitmap bitmap) {
   /** 放入缓存中 */
   mCache.put(url, bitmap);
   /** 存到本地SD中 */
   putSDBitmap(url.substring(url.lastIndexOf("/") + 1), bitmap);
 }
コード例 #16
0
 /**
  * 向缓存列表中添加一个bitmap
  *
  * @param key
  * @param bitmap
  * @return
  */
 private boolean addBitmapToMemoryCache(String key, Bitmap bitmap) {
   if (mCache != null) {
     mCache.put(key, bitmap);
     return true;
   } else {
     return false;
   }
 }
コード例 #17
0
ファイル: BitmapCache.java プロジェクト: jjjyrki/FlickrSample
  public Bitmap getBitmapFromMemCache(String key) {
    Bitmap bitmap = mMemoryCache.get(key);

    if (bitmap != null) {
      return bitmap;
    }
    return null;
  }
コード例 #18
0
 /** Add the bitmap to the LRU cache. */
 protected void addBitmapToMemoryCache(String key, Bitmap bitmap) {
   if (key != null && bitmap != null) {
     if (key.startsWith(RecentPanelView.TASK_PACKAGE_IDENTIFIER)) {
       mKeys.add(key);
     }
     mMemoryCache.put(key, bitmap);
   }
 }
コード例 #19
0
 public void clearCache() {
   Log.v("마이볼리 캐쉬 사이즈", String.valueOf(cache.size()));
   Log.v("마이볼리 캐쉬", String.valueOf(cache));
   /*
   ClearCacheRequest ccr = new ClearCacheRequest(requestQueue.getCache(),
           new Runnable() {
               @Override
               public void run() {
               }
           });
   ccr.setTag(this);
   Log.v("캐쉬","클리어");
   requestQueue.add(ccr);*/
   cache.evictAll();
   Log.v("캐쉬", "클리어");
   Log.v("마이볼리 캐쉬 사이즈", String.valueOf(cache.size()));
   Log.v("마이볼리 캐쉬", String.valueOf(cache));
 }
コード例 #20
0
ファイル: Storage.java プロジェクト: salvprest/Camera2
 /**
  * Creates an empty placeholder.
  *
  * @param size the size of the placeholder in pixels.
  * @return A new URI used to reference this placeholder
  */
 @Nonnull
 public static Uri addEmptyPlaceholder(@Nonnull Size size) {
   Uri uri = generateUniquePlaceholderUri();
   sSessionsToSizes.put(uri, new Point(size.getWidth(), size.getHeight()));
   sSessionsToPlaceholderBitmap.remove(uri);
   Integer currentVersion = sSessionsToPlaceholderVersions.get(uri);
   sSessionsToPlaceholderVersions.put(uri, currentVersion == null ? 0 : currentVersion + 1);
   return uri;
 }
コード例 #21
0
 /** Remove a bitmap from the LRU cache. */
 protected Bitmap removeBitmapFromMemCache(String key) {
   if (key == null) {
     return null;
   }
   if (key.startsWith(RecentPanelView.TASK_PACKAGE_IDENTIFIER)) {
     mKeys.remove(key);
   }
   return mMemoryCache.remove(key);
 }
コード例 #22
0
  public long getSeen() {
    long seen = 0;
    for (ScanResult result : mScanResultCache.snapshot().values()) {
      if (result.timestamp > seen) {
        seen = result.timestamp;
      }
    }

    return seen;
  }
コード例 #23
0
  /**
   * 构造不带时间的新闻
   *
   * @param storiesEntity 消息实体类
   * @param holder View控件
   */
  public void bindSimpleItem(
      LatestNewsEntity.StoriesEntity storiesEntity, RecyclerView.ViewHolder holder) {
    ((SimpleItemHolder) holder).getTextView_title().setText(storiesEntity.getTitle());
    ((SimpleItemHolder) holder).itemView.setTag(storiesEntity.getId());
    ((SimpleItemHolder) holder).getImageView_image().setImageResource(R.drawable.image_start);

    if (lruCache.get(storiesEntity.getImages().get(0)) != null) {
      ((SimpleItemHolder) holder)
          .getImageView_image()
          .setImageBitmap(lruCache.get(storiesEntity.getImages().get(0)));
    } else if (aCache.getAsBitmap(storiesEntity.getImages().get(0)) != null) {
      ((SimpleItemHolder) holder)
          .getImageView_image()
          .setImageBitmap(aCache.getAsBitmap(storiesEntity.getImages().get(0)));
    } else {
      new DownloadImageTask(((SimpleItemHolder) holder).getImageView_image())
          .execute(storiesEntity.getImages().get(0));
    }
  }
コード例 #24
0
  public int getRssi() {
    int rssi = Integer.MIN_VALUE;
    for (ScanResult result : mScanResultCache.snapshot().values()) {
      if (result.level > rssi) {
        rssi = result.level;
      }
    }

    return rssi;
  }
コード例 #25
0
 @Override
 public Bitmap getBitmap(String url) {
   Bitmap bitmap = null;
   if (mMemoryCache.get(url) != null) {
     bitmap = mMemoryCache.get(url);
   } else {
     String key = CommonUtils.encryptionWithMD5(url);
     try {
       if (mDiskLruCache.get(key) != null) {
         CommonUtils.log("hehe");
         DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
         InputStream is = snapShot.getInputStream(0);
         bitmap = BitmapFactory.decodeStream(is);
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return bitmap;
 }
コード例 #26
0
 protected void fetchPhoto(final RecipientEntry entry, final Uri photoThumbnailUri) {
   byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
   if (photoBytes != null) {
     entry.setPhotoBytes(photoBytes);
     return;
   }
   final Cursor photoCursor =
       mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null, null, null);
   if (photoCursor != null) {
     try {
       if (photoCursor.moveToFirst()) {
         photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
         entry.setPhotoBytes(photoBytes);
         mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
       }
     } finally {
       photoCursor.close();
     }
   }
 }
コード例 #27
0
 public void addToCache(String url, Bitmap bitmap, boolean lruCache, boolean diskLruCache) {
   if (url == null || bitmap == null) {
     return;
   }
   String key = MD5Util.getMD5String(url);
   if (lruCache) {
     memoryCache.put(key, bitmap);
   }
   if (diskLruCache) {
     mDiskCache.put(key + ".png", bitmap);
   }
 }
コード例 #28
0
 public final Bitmap get(String data) {
   if (data == null) {
     return null;
   }
   if (mLruCache != null) {
     final Bitmap mBitmap = mLruCache.get(data);
     if (mBitmap != null) {
       return mBitmap;
     }
   }
   return null;
 }
コード例 #29
0
 /**
  * Invalidate the entire cache; the arguments are used for logging only, and indicate the write
  * operation that caused the invalidation
  *
  * @param operation a string describing the operation causing the invalidate (or null)
  * @param uri the uri causing the invalidate (or null)
  * @param selection the selection used with the uri (or null)
  */
 public synchronized void invalidate(String operation, Uri uri, String selection) {
   if (DEBUG_CACHE && (operation != null)) {
     LogUtils.d(
         mLogTag,
         "============ INVALIDATED BY " + operation + ": " + uri + ", SELECTION: " + selection);
   }
   mStats.mInvalidateCount++;
   // Close all cached cursors that are no longer in use
   mLruCache.evictAll();
   // Invalidate all current tokens
   mTokenList.invalidate();
 }
コード例 #30
0
 public void saveWifiState(Bundle savedState) {
   if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
   savedState.putInt(KEY_SECURITY, security);
   savedState.putInt(KEY_PSKTYPE, pskType);
   if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
   savedState.putParcelable(KEY_WIFIINFO, mInfo);
   savedState.putParcelableArrayList(
       KEY_SCANRESULTCACHE, new ArrayList<ScanResult>(mScanResultCache.snapshot().values()));
   if (mNetworkInfo != null) {
     savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
   }
 }