Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android內存管理工具類

android內存管理工具類

編輯:關於Android編程

public class MemoryManager {
	private static final String TAG = "MemoryManager";
	private static final int MAXMEMORY=50*1024*1024;//程序運行的最大內存
	/**
	 * 判斷系統是否在低內存下運行
	 * @param context
	 * @return
	 */
	public static boolean hasAcailMemory() {
		// 獲取手機內部空間大小
		long memory = getAvailableInternalMemorySize();
		Log.i(TAG, memory+"");
		if (memory < MAXMEMORY) {
			//應用將處於低內存狀態下運行
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 獲取手機內部可用空間大小
	 * 
	 * @return
	 */
	public static long getAvailableInternalMemorySize() {
		File path = Environment.getDataDirectory();// 獲取 Android 數據目錄
		StatFs stat = new StatFs(path.getPath());// 一個模擬linux的df命令的一個類,獲得SD卡和手機內存的使用情況
		long blockSize = stat.getBlockSize();// 返回 Int ,大小,以字節為單位,一個文件系統
		long availableBlocks = stat.getAvailableBlocks();// 返回 Int ,獲取當前可用的存儲空間
		return availableBlocks * blockSize;
	}

	/**
	 * 獲取手機內部空間大小
	 * 
	 * @return
	 */
	public static long getTotalInternalMemorySize() {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();// 獲取該區域可用的文件系統數
		return totalBlocks * blockSize;
	}

	/**
	 * 獲取手機外部可用空間大小
	 * 
	 * @return
	 */
	public static long getAvailableExternalMemorySize() {
		if (externalMemoryAvailable()) {
			File path = Environment.getExternalStorageDirectory();
			StatFs stat = new StatFs(path.getPath());
			long blockSize = stat.getBlockSize();
			long availableBlocks = stat.getAvailableBlocks();
			return availableBlocks * blockSize;
		} else {
			throw new RuntimeException("Don't have sdcard.");
		}
	}

	/**
	 * 獲取手機外部空間大小
	 * 
	 * @return
	 */
	public static long getTotalExternalMemorySize() {
		if (externalMemoryAvailable()) {
			File path = Environment.getExternalStorageDirectory();// 獲取外部存儲目錄即 SDCard
			StatFs stat = new StatFs(path.getPath());
			long blockSize = stat.getBlockSize();
			long totalBlocks = stat.getBlockCount();
			return totalBlocks * blockSize;
		} else {
			throw new RuntimeException("Don't have sdcard.");
		}
	}

	/**
	 * 外部存儲是否可用
	 * 
	 * @return
	 */
	public static boolean externalMemoryAvailable() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved