/**
  * 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;
 }
Esempio n. 2
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;
 }
Esempio n. 3
0
  @Test
  public void shouldLru() throws Exception {
    LruCache<Integer, String> lruCache = new LruCache<Integer, String>(2);
    lruCache.put(1, "one");
    lruCache.put(2, "two");
    lruCache.put(3, "three");

    assertThat(lruCache.size()).isEqualTo(2);
    assertThat(lruCache.get(1)).isNull();
    assertThat(lruCache.get(2)).isEqualTo("two");
    assertThat(lruCache.get(3)).isEqualTo("three");
  }
  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);
    }
  }
Esempio n. 5
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;
  }
Esempio n. 6
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;
  }
  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;
  }
 public V get(K key) {
   V val = permanent.get(key);
   if (val == null) {
     return evictable.get(key);
   }
   return val;
 }
Esempio n. 9
0
  public Bitmap getBitmapFromMemCache(String key) {
    Bitmap bitmap = mMemoryCache.get(key);

    if (bitmap != null) {
      return bitmap;
    }
    return null;
  }
Esempio n. 10
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));
    }
  }
 @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;
 }
Esempio n. 12
0
  /** 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);
    }
  }
Esempio n. 13
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;
 }
 private void tryFetchPhoto(final RecipientEntry entry) {
   final Uri photoThumbnailUri = entry.getPhotoThumbnailUri();
   if (photoThumbnailUri != null) {
     final byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
     if (photoBytes != null) {
       entry.setPhotoBytes(photoBytes);
       // notifyDataSetChanged() should be called by a caller.
     } else {
       if (DEBUG) {
         Log.d(TAG, "No photo cache for " + entry.getDisplayName() + ". Fetch one asynchronously");
       }
       fetchPhotoAsync(entry, photoThumbnailUri);
     }
   }
 }
Esempio n. 15
0
  /**
   * extraerImagenEn: Extrae el bitmap de la ruta especificada con el tamano necesario para situarlo
   * en el contenedor que se especifique, de forma optima para el ahorro de recursos.
   *
   * @param activity contexto donde se ubica el contenedor.
   * @param contenedor_imagen ImageView que contendra a la imagen una vez cargada.
   * @param ruta String con la ruta del almacenamiento externo donde se ubica el bitmap.
   */
  public void extraerImagenListaEn(Activity activity, ImageView contenedor_imagen, String ruta) {
    if (cancelarExtractorInnecesario(ruta, contenedor_imagen)) {
      final Bitmap bitmap_cache = memoria_cache.get(ruta);
      if (bitmap_cache != null) {
        contenedor_imagen.setImageBitmap(bitmap_cache);
      } else {
        // si ya se libero el extractor innecesario se inicia uno nuevo con la nueva imagen
        HiloExtractorBitmap extractor = new HiloExtractorBitmap(contenedor_imagen);
        contenedor_imagen.setImageDrawable(
            new AsyncDrawable(activity.getResources(), imagen_cargando, extractor));

        String parametros[] = {ruta};
        extractor.execute(parametros);
      }
    }
  }
 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();
     }
   }
 }
Esempio n. 17
0
 public static Bitmap getBitmap(String key) {
   return sMemoryCache.get(key);
 }
Esempio n. 18
0
 @Override
 public Bitmap get(String stringResource) {
   return mCache.get(stringResource);
 }
 @VisibleForTesting
 Cursor get(String id) {
   return mLruCache.get(id);
 }
Esempio n. 20
0
 /**
  * 从缓存列表中取出一个bitmap
  *
  * @param key
  * @return
  */
 private Bitmap getBitmapFromMemCache(String key) {
   return mCache.get(key);
 }
Esempio n. 21
0
 /**
  * Returns the jpeg bytes for a placeholder session
  *
  * @param uri the session uri to look up
  * @return The bitmap or null
  */
 public static Optional<Bitmap> getPlaceholderForSession(Uri uri) {
   return Optional.fromNullable(sSessionsToPlaceholderBitmap.get(uri));
 }
Esempio n. 22
0
 public Bitmap getBitmapFromMemory(String url) {
   String key = MD5Util.getMD5String(url);
   Bitmap bitmap = memoryCache.get(key);
   return bitmap;
 }
Esempio n. 23
0
 /**
  * 把图片从缓存中取出来
  *
  * @param url
  * @return bitmap
  */
 public Bitmap getBitmapFromCache(String url) {
   return mCaches.get(url);
 }
Esempio n. 24
0
 @Override
 public Bitmap getBitmap(String url) {
   return cache.get(url);
 }
 /** Get the bitmap from the LRU cache. */
 protected Bitmap getBitmapFromMemCache(String key) {
   if (key == null) {
     return null;
   }
   return mMemoryCache.get(key);
 }
  /**
   * Determine whether a word is a distracter to words in dictionaries.
   *
   * @param prevWordsInfo the information of previous words. Not used for now.
   * @param testedWord the word that will be tested to see whether it is a distracter to words in
   *     dictionaries.
   * @param locale the locale of word.
   * @return true if testedWord is a distracter, otherwise false.
   */
  @Override
  public boolean isDistracterToWordsInDictionaries(
      final PrevWordsInfo prevWordsInfo, final String testedWord, final Locale locale) {
    if (locale == null) {
      return false;
    }
    if (!locale.equals(mDictionaryFacilitator.getLocale())) {
      synchronized (mLock) {
        if (!mLocaleToSubtypeMap.containsKey(locale)) {
          Log.e(TAG, "Locale " + locale + " is not enabled.");
          // TODO: Investigate what we should do for disabled locales.
          return false;
        }
        loadKeyboardForLocale(locale);
        // Reset dictionaries for the locale.
        try {
          mDistractersCache.evictAll();
          loadDictionariesForLocale(locale);
        } catch (final InterruptedException e) {
          Log.e(TAG, "Interrupted while waiting for loading dicts in DistracterFilter", e);
          return false;
        }
      }
    }

    if (DEBUG) {
      Log.d(TAG, "testedWord: " + testedWord);
    }
    final Boolean isCachedDistracter = mDistractersCache.get(testedWord);
    if (isCachedDistracter != null && isCachedDistracter) {
      if (DEBUG) {
        Log.d(TAG, "isDistracter: true (cache hit)");
      }
      return true;
    }

    final boolean isDistracterCheckedByGetMaxFreqencyOfExactMatches =
        checkDistracterUsingMaxFreqencyOfExactMatches(testedWord);
    if (isDistracterCheckedByGetMaxFreqencyOfExactMatches) {
      // Add the word to the cache.
      mDistractersCache.put(testedWord, Boolean.TRUE);
      return true;
    }
    final boolean isValidWord =
        mDictionaryFacilitator.isValidWord(testedWord, false /* ignoreCase */);
    if (isValidWord) {
      // Valid word is not a distractor.
      if (DEBUG) {
        Log.d(TAG, "isDistracter: false (valid word)");
      }
      return false;
    }

    final boolean isDistracterCheckedByGetSuggestion =
        checkDistracterUsingGetSuggestions(testedWord);
    if (isDistracterCheckedByGetSuggestion) {
      // Add the word to the cache.
      mDistractersCache.put(testedWord, Boolean.TRUE);
      return true;
    }
    return false;
  }
Esempio n. 27
0
 public static Bitmap getBitmapFromMemoryCache(LruCache<String, Bitmap> lruCache, String key) {
   return lruCache.get(key);
 }
Esempio n. 28
0
 /**
  * 从LruCache中获取一张图片,如果不存在就返回null�?
  *
  * @param key LruCache的键,这里传入图片的URL地址�?
  * @return 对应传入键的Bitmap对象,或者null�?
  */
 public Bitmap getBitmapFromMemoryCache(String key) {
   return mMemoryCache.get(key);
 }
 /**
  * 从Lru缓存中获取key对应的Bitmap对象,如果key不存在那么返回null
  *
  * @param key
  * @return
  */
 public Bitmap getBitmap(String key) {
   return mLruCache.get(key);
 }