package com.tz.volleylrucache.cache.libcore.io;

import java.io.File;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;

import com.tsgame.tsgame_niuniu.system.Myapplication;

public class Filecache {
	private static String CACHE_DIR_NAME = "imagecache";
	private static DiskLruCache mDiskLruCache;
	private static final int MEMORY_CACHE_MAX_SIZE = 1024 * 1024 * ((ActivityManager) Myapplication.application
			.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() / 8;

	public Filecache() {
		try {
			if (mDiskLruCache == null) {
				// 打开缓存目录
				mDiskLruCache = DiskLruCache.open(
						getDiskCacheDir(Myapplication.application,
								CACHE_DIR_NAME),
						getAppVersion(Myapplication.application), // 版本号，跟app的版本号一直
						1, // 缓存一个文件是否允许同一个文件缓存两个
						MEMORY_CACHE_MAX_SIZE);// 缓存的最大限制、
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private int getAppVersion(Context context) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 1;
	}

	private File getDiskCacheDir(Context context, String appLabel) {

		String path;// /mnt/sdcard/cache/appLabel
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sd卡存储（/mnt/sdcard/cache）
			path = context.getExternalCacheDir().getPath();
		} else {
			// 没有SD卡，缓存到系统存储
			path = context.getCacheDir().getPath();
		}
		return new File(path + File.separator + appLabel);
	}
	
	
}
