类android.util.LruCache源码实例Demo

下面列出了怎么用android.util.LruCache的API类实例代码及写法,或者点击链接到github查看源代码。

public void initialize(Context context, NotificationUsageStats usageStats) {
    if (DEBUG) Slog.d(TAG, "Initializing  " + getClass().getSimpleName() + ".");
    mUserToContextMap = new ArrayMap<>();
    mBaseContext = context;
    mUsageStats = usageStats;
    mPeopleCache = new LruCache<String, LookupResult>(PEOPLE_CACHE_SIZE);
    mEnabled = ENABLE_PEOPLE_VALIDATOR && 1 == Settings.Global.getInt(
            mBaseContext.getContentResolver(), SETTING_ENABLE_PEOPLE_VALIDATOR, 1);
    if (mEnabled) {
        mHandler = new Handler();
        mObserver = new ContentObserver(mHandler) {
            @Override
            public void onChange(boolean selfChange, Uri uri, int userId) {
                super.onChange(selfChange, uri, userId);
                if (DEBUG || mEvictionCount % 100 == 0) {
                    if (VERBOSE) Slog.i(TAG, "mEvictionCount: " + mEvictionCount);
                }
                mPeopleCache.evictAll();
                mEvictionCount++;
            }
        };
        mBaseContext.getContentResolver().registerContentObserver(Contacts.CONTENT_URI, true,
                mObserver, UserHandle.USER_ALL);
    }
}
 
源代码2 项目: AudioAnchor   文件: AlbumCursorAdapter.java
AlbumCursorAdapter(Context context, Cursor c) {
    super(context, c, 0);
    mContext = context;
    // Get the base directory from the shared preferences.
    mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    // Set up the image cache
    // See https://developer.android.com/topic/performance/graphics/cache-bitmap
    // Get max available Java VM memory. Stored in kilobytes as LruCache takes an int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use fraction of the available memory for this memory cache.
    final int cacheSize = maxMemory / 12;

    mImageCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size is measured in kilobytes rather than number of items.
            return bitmap.getByteCount() / 1024;
        }
    };


}
 
源代码3 项目: imsdk-android   文件: ConnectionUtil.java
/**
     * 获取最新用户配置后更新本地数据
     *
     * @param newRemoteConfig
     */
    public static void refreshTheConfig(NewRemoteConfig newRemoteConfig) {
        IMDatabaseManager.getInstance().insertUserConfigVersion(newRemoteConfig.getData().getVersion());
        IMDatabaseManager.getInstance().bulkUserConfig(newRemoteConfig);


        for (int i = 0; i < newRemoteConfig.getData().getClientConfigInfos().size(); i++) {
            if (newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kCollectionCacheKey)) {
//                ConnectionUtil.getInstance().handleMyEmotion(newRemoteConfig.getData().getClientConfigInfos().get(i));
            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kMarkupNames)){
                LruCache<String,String> markups = ConnectionUtil.getInstance().selectMarkupNames();
//                Logger.i("initreload map:" + JsonUtils.getGson().toJson(markups));
                CurrentPreference.getInstance().setMarkupNames(markups);
//                IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.Show_List);
            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kStickJidDic)){
                IMDatabaseManager.getInstance().setConversationTopSession(newRemoteConfig.getData().getClientConfigInfos().get(i));

            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kNoticeStickJidDic)){
                IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.Update_ReMind);
            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kQuickResponse)) {
                IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.UPDATE_QUICK_REPLY);
            }
        }
        IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.Show_List);
    }
 
源代码4 项目: Conversations   文件: AvatarService.java
public void clear(Conversation conversation) {
	if (conversation.getMode() == Conversation.MODE_SINGLE) {
		clear(conversation.getContact());
	} else {
		clear(conversation.getMucOptions());
		synchronized (this.conversationDependentKeys) {
			Set<String> keys = this.conversationDependentKeys.get(conversation.getUuid());
			if (keys == null) {
				return;
			}
			LruCache<String, Bitmap> cache = this.mXmppConnectionService.getBitmapCache();
			for (String key : keys) {
				cache.remove(key);
			}
			keys.clear();
		}
	}
}
 
源代码5 项目: Presentation   文件: BitmapLruCache.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public BitmapLruCache(Context context) {
    mContext = context;
    mLruCache = new LruCache<>((int) EnvironmentHelper.getMemoryCacheSize());
    mHuabanApp = Huaban.getInstance();

    try {
        mDiskLruCache = new BitmapDiskLruCache(
                EnvironmentHelper.getCacheDir(mContext),
                EnvironmentHelper.getDiskCacheSize(mContext));
    } catch (IOException e) {
        e.printStackTrace();
    }

    mNotAvailableBitmap = getDefaultBitmap();
}
 
源代码6 项目: FontProvider   文件: FontManager.java
public static void init(Context context) {
    if (sFonts != null) {
        return;
    }

    sCache = new LruCache<String, MemoryFile>(FontProviderSettings.getMaxCache()) {
        @Override
        protected void entryRemoved(boolean evicted, String key, MemoryFile oldValue, MemoryFile newValue) {
            if (evicted) {
                oldValue.close();
            }
        }

        @Override
        protected int sizeOf(String key, MemoryFile value) {
            return value.length();
        }
    };

    sFonts = new ArrayList<>();

    for (int res : FONTS_RES) {
        FontInfo font = new Gson().fromJson(new InputStreamReader(context.getResources().openRawResource(res)), FontInfo.class);
        sFonts.add(font);
    }
}
 
源代码7 项目: ImageFrame   文件: ImageCache.java
public ImageCache() {
  mReusableBitmaps =
      Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
  long memCacheSize = Runtime.getRuntime().freeMemory() / 8;
  if (memCacheSize <= 0) {
    memCacheSize = 1;
  }
  // If you're running on Honeycomb or newer, create a
  // synchronized HashSet of references to reusable bitmaps.
  mMemoryCache = new LruCache<String, BitmapDrawable>((int) memCacheSize) {

    // // Notify the removed entry that is no longer being cached.
    // @Override
    // protected void entryRemoved(boolean evicted, String key,
    // BitmapDrawable oldValue, BitmapDrawable newValue) {
    // //Log.i("TAG","mReusableBitmaps add2");
    // //mReusableBitmaps.add(new SoftReference<>(oldValue.getBitmap()));
    // }
    @Override
    protected int sizeOf(String key, BitmapDrawable value) {
      return value.getBitmap().getByteCount();
    }
  };
}
 
源代码8 项目: PhotoPicker   文件: ImageLoader.java
/**
 * 初始化内存缓存
 */
public void initMemoryCache() {

    // Set up memory cache
    if (mMemoryCache != null) {
        try {
            clearMemoryCache();
        } catch (Throwable e) {
        }
    }
    // find the max memory size of the system
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {

        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            if (bitmap == null) return 0;
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    };
}
 
源代码9 项目: DaVinci   文件: DaVinci.java
/**
 * Initialise DaVinci, muse have a googleApiClient to retrieve Bitmaps from Smartphone
 *
 * @param context the application context
 * @param size    the number of entry on the cache
 */
private DaVinci(Context context, int size) {

    Log.d(TAG, "====================================");

    this.mSize = size;
    this.mContext = context;
    this.mImagesCache = new LruCache<>(mSize);
    this.mDiskImageCache= new DiskLruImageCache(mContext, TAG, cacheSize, Bitmap.CompressFormat.PNG, 100);

    this.mPlaceHolder = new ColorDrawable(Color.TRANSPARENT);

    mApiClient = new GoogleApiClient.Builder(context)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    mApiClient.connect();
    //TODO disconnect when the application close
}
 
源代码10 项目: delion   文件: InterestsItemView.java
/**
 * @param context The view context in which this item will be shown.
 * @param interest The interest to display.
 * @param listener Callback object for when a view is pressed.
 * @param imageCache A cache to store downloaded images.
 * @param drawingData Information about the view size.
 */
InterestsItemView(Context context, Interest interest, InterestsClickListener listener,
        LruCache<String, Promise<Drawable>> imageCache, DrawingData drawingData) {
    super(context);

    mContext = context;
    mListener = listener;
    mImageCache = imageCache;
    mDrawingData = drawingData;

    setTextSize(TypedValue.COMPLEX_UNIT_PX, mDrawingData.mTextSize);
    setMinimumHeight(mDrawingData.mMinHeight);
    setGravity(Gravity.CENTER);
    setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

    setOnClickListener(this);

    reset(interest);
}
 
源代码11 项目: android-cluster-marker   文件: ClusterOverlay.java
/**
     * 构造函数,批量添加聚合元素时,调用此构造函数
     *
     * @param amap
     * @param clusterItems 聚合元素
     * @param clusterSize
     * @param context
     */
    public ClusterOverlay(AMap amap, List<ClusterItem> clusterItems,
                          int clusterSize, Context context) {
//默认最多会缓存80张图片作为聚合显示元素图片,根据自己显示需求和app使用内存情况,可以修改数量
        mLruCache = new LruCache<Integer, BitmapDescriptor>(80) {
            protected void entryRemoved(boolean evicted, Integer key, BitmapDescriptor oldValue, BitmapDescriptor newValue) {
                oldValue.getBitmap().recycle();
            }
        };
        if (clusterItems != null) {
            mClusterItems = clusterItems;
        } else {
            mClusterItems = new ArrayList<ClusterItem>();
        }
        mContext = context;
        mClusters = new ArrayList<Cluster>();
        this.mAMap = amap;
        mClusterSize = clusterSize;
        mPXInMeters = mAMap.getScalePerPixel();
        mClusterDistance = mPXInMeters * mClusterSize;
        amap.setOnCameraChangeListener(this);
        amap.setOnMarkerClickListener(this);
        initThreadHandler();
        assignClusters();
    }
 
源代码12 项目: aurora-imui   文件: BrowserImageActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_browser);
    mPathList = getIntent().getStringArrayListExtra("pathList");
    mMsgIdList = getIntent().getStringArrayListExtra("idList");
    mViewPager = (ImgBrowserViewPager) findViewById(R.id.img_browser_viewpager);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    mWidth = dm.widthPixels;
    mHeight = dm.heightPixels;

    int maxMemory = (int) (Runtime.getRuntime().maxMemory());
    int cacheSize = maxMemory / 4;
    mCache = new LruCache<>(cacheSize);
    mViewPager.setAdapter(pagerAdapter);
    initCurrentItem();
}
 
源代码13 项目: sa-sdk-android   文件: WebNodesManager.java
@SuppressLint("NewApi")
void handlerFailure(String webViewUrl, String message) {
    Dispatch.getInstance().removeCallbacksAndMessages();
    if (!VisualizedAutoTrackService.getInstance().isVisualizedAutoTrackRunning()) {
        return;
    }
    if (TextUtils.isEmpty(message)) {
        return;
    }
    SALog.i(TAG, "handlerFailure url " + webViewUrl + ",msg: " + message);
    mHasH5AlertInfo = true;
    mLastWebNodeMsg = message;
    List<WebNodeInfo.AlertInfo> list = parseAlertResult(message);
    if (list != null && list.size() > 0) {
        if (sWebNodesCache == null) {
            sWebNodesCache = new LruCache<>(LRU_CACHE_MAX_SIZE);
        }
        sWebNodesCache.put(webViewUrl, WebNodeInfo.createWebAlertInfo(list));
    }
}
 
源代码14 项目: android-movies-demo   文件: BitmapCache.java
public static void init(Context context) {
	sAppContext = context.getApplicationContext();

	// Use 1/4th of the available memory for this memory cache.
	final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / SCALE);
	final int cacheSize = maxMemory / 4;

	Log.i("MovieDemo", "Creating Bitmap cache size of: " + cacheSize + " (total memory " + maxMemory + ")");

	sCache = new LruCache<Integer, Bitmap>(cacheSize) {
		@Override
		protected int sizeOf(Integer key, Bitmap bitmap) {
			return bitmap.getByteCount() / SCALE;
		}
	};
}
 
源代码15 项目: sa-sdk-android   文件: ViewUtil.java
/**
 * 获取 class name
 */
private static String getCanonicalName(Class clazz) {
    String name = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
        if (sClassNameCache == null) {
            sClassNameCache = new LruCache<Class, String>(100);
        }
        name = sClassNameCache.get(clazz);
    }
    if (TextUtils.isEmpty(name)) {
        name = clazz.getCanonicalName();
        if (TextUtils.isEmpty(name)) {
            name = "Anonymous";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            synchronized (ViewUtil.class) {
                sClassNameCache.put(clazz, name);
            }
        }
        checkCustomRecyclerView(clazz, name);
    }
    return name;
}
 
源代码16 项目: Pix-Art-Messenger   文件: AvatarService.java
public void clear(Conversation conversation) {
    if (conversation.getMode() == Conversation.MODE_SINGLE) {
        clear(conversation.getContact());
    } else {
        clear(conversation.getMucOptions());
        synchronized (this.conversationDependentKeys) {
            Set<String> keys = this.conversationDependentKeys.get(conversation.getUuid());
            if (keys == null) {
                return;
            }
            LruCache<String, Bitmap> cache = this.mXmppConnectionService.getBitmapCache();
            for (String key : keys) {
                cache.remove(key);
            }
            keys.clear();
        }
    }
}
 
源代码17 项目: clevertap-android-sdk   文件: ImageCache.java
public static void init(){
    synchronized (ImageCache.class) {
        if(mMemoryCache == null) {
            Logger.v("CleverTap.ImageCache: init with max device memory: " + maxMemory + "KB and allocated cache size: " + cacheSize + "KB");
            try {
                mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
                    @Override
                    protected int sizeOf(String key, Bitmap bitmap) {
                        // The cache size will be measured in kilobytes rather than
                        // number of items.
                        int size = getImageSizeInKB(bitmap);
                        Logger.v( "CleverTap.ImageCache: have image of size: "+size + "KB for key: " + key);
                        return size;
                    }
                };
            } catch (Throwable t) {
                Logger.v( "CleverTap.ImageCache: unable to initialize cache: ", t.getCause());
            }
        }
    }
}
 
源代码18 项目: android-job   文件: JobExecutor.java
@VisibleForTesting
@SuppressLint("UseSparseArrays")
/*package*/ void cleanUpRoutine(LruCache<Integer, WeakReference<Job>> cache) {
    Map<Integer, WeakReference<Job>> snapshot = new HashMap<>(cache.snapshot());
    for (Integer key : snapshot.keySet()) {
        if (snapshot.get(key) == null || snapshot.get(key).get() == null) {
            cache.remove(key);
        }
    }
}
 
源代码19 项目: Noyze   文件: ImageListPreference.java
public ImageListPreferenceScreenAdapter(Context context,
                                        int layout, List<Pair<CharSequence, Integer>> items) {
    super(context, layout, items);
    skus = new CharSequence[items.size()];
    cache = new LruCache<Integer, Drawable>(items.size());
    this.layout = layout;
    preload();
}
 
源代码20 项目: imsdk-android   文件: TabMainActivity.java
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atom_ui_activity_tabmainactivity);
        connectionUtil = ConnectionUtil.getInstance();

        isShowWorkWorld = ConnectionUtil.getInstance().SelectWorkWorldPremissions();
        //在页面创建之出,初始化备注
        LruCache<String,String> markups = ConnectionUtil.getInstance().selectMarkupNames();
        CurrentPreference.getInstance().setMarkupNames(markups);
        if (GlobalConfigManager.isQtalkPlat() && isShowWorkWorld) {
            mTitles = getResources().getStringArray(R.array.atom_ui_tab_title_qtalk);
        } else {
            mTitles = getResources().getStringArray(R.array.atom_ui_tab_title);
        }


//        initAction();
        initViewPager();
        initView();
        initActionBar();
        initMyCommTabLayout();

        initData();

        mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(this);
    }
 
private AlbumArtCache() {
    // Holds no more than MAX_ALBUM_ART_CACHE_SIZE bytes, bounded by maxmemory/4 and
    // Integer.MAX_VALUE:
    int maxSize = Math.min(MAX_ALBUM_ART_CACHE_SIZE,
        (int) (Math.min(Integer.MAX_VALUE, Runtime.getRuntime().maxMemory()/4)));
    mCache = new LruCache<String, Bitmap[]>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap[] value) {
            return value[BIG_BITMAP_INDEX].getByteCount()
                + value[ICON_BITMAP_INDEX].getByteCount();
        }
    };
}
 
源代码22 项目: FirefoxReality   文件: BitmapCache.java
void initMemoryCache() {
    // Get  available VM memory in KB.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // Use KB as the size of the item
            return bitmap.getByteCount() / 1024;
        }
    };
}
 
源代码23 项目: volley_demo   文件: BitmapCache.java
public BitmapCache()
{
    cache = new LruCache<String, Bitmap>(max){
        @Override
        protected int sizeOf(String key, Bitmap value)
        {
            return value.getRowBytes() * value.getHeight();
        }
    };
}
 
源代码24 项目: android-tv-launcher   文件: BitmapUtil.java
private BitmapUtil(Context context) {
	mContext = context;
	// init memoryCache
	memoryCache = new LruCache<String, Bitmap>(MEMORY_CACHE_SIZE);
	// init DiskCache
	File cacheDir = new File(mContext.getCacheDir(), DISK_CACHE_SUBDIR);
	mDiskCache = DiskLruCache
			.openCache(mContext, cacheDir, DISK_CACHE_SIZE);
}
 
源代码25 项目: commcare-android   文件: CachingAsyncImageLoader.java
public CachingAsyncImageLoader(Context context) {
    ActivityManager am = (ActivityManager)context.getSystemService(
            Context.ACTIVITY_SERVICE);
    int memoryClass = (am.getMemoryClass() * 1024 * 1024) / CACHE_DIVISOR;        //basically, set the heap to be everything we can get
    this.context = context;
    this.cache = new LruCache<>(memoryClass);
}
 
源代码26 项目: stynico   文件: ImageLoader.java
private void init(int threadCount, Type type) {
    mPoolThread = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            mPoolThreadHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    mThreadPool.execute(getTask());
                    try {
                        mSemaphoreThreadPool.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            mSemaphorePoolThreadHandler.release();
            Looper.loop();
        }
    };
    mPoolThread.start();
    
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheMemory = maxMemory / 8;
    mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };

    mThreadPool = Executors.newFixedThreadPool(threadCount);
    mTaskQueue = new LinkedList<Runnable>();
    mType = type;
    mSemaphoreThreadPool = new Semaphore(threadCount);

}
 
源代码27 项目: android-advanced-light   文件: BitmapCache.java
public BitmapCache() {
    int maxSize = 8 * 1024 * 1024;
    mCache = new LruCache<String, Bitmap>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    };
}
 
/**
 * 需要调用{@link #setEmptyAdapter(EmptyEntityAdapter)}
 * 如果不想设置{@link EmptyEntityAdapter},请调用{@link #notifyModuleEmptyChanged(MultiTypeEntity, int)}
 *
 * @param level level
 */
public void notifyModuleEmptyChanged(int level) {
    if (mSingleCache == null) {
        mSingleCache = new LruCache<>(mMaxSingleCacheCount);
    }

    T emptyEntity = mSingleCache.get(getEmptyKey(level));
    if (emptyEntity == null) {
        checkEmptyAdapterBind();
        emptyEntity = mEmptyEntityAdapter.createEmptyEntity(level - EMPTY_TYPE_DIFFER, level);
    }
    notifyModuleEmptyChanged(emptyEntity, level);
}
 
源代码29 项目: VMLibrary   文件: VMBitmapCache.java
/**
 * 构造函数,初始化缓存
 */
private VMBitmapCache() {
    cache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
}
 
源代码30 项目: StickyDecoration   文件: CacheUtil.java
private void initLruCache() {
    mLruCache = new LruCache<Integer, T>(2 * 1024 * 1024) {
        @Override
        protected void entryRemoved(boolean evicted, Integer key, T oldValue, T newValue) {
            super.entryRemoved(evicted, key, oldValue, newValue);
        }
    };
}