/** * 开启线程检测软件可用内存情况,软件退出后, 调用System.exit(0)该线程才会停止 * * * @param sleep * 每隔一段时间检测内存 * @param standard * 内存超过多少比例报警 */ public static void memoryWatch(final int sleep, final int standard) { if (sleep <= 0) { Log.e(TAG, "memoryWatch, invalid sleep = 0!"); return; } if (standard <= 0 && standard > 100) { Log.e(TAG, "memoryWatch, invalid standard percent = " + standard); return; } new Thread(new Runnable() { @Override public void run() { Log.d(TAG, "memoryWatch, start thread!"); while (true) { long divisor = 1024 * 1024; long maxMem = Runtime.getRuntime().maxMemory(); long totalMem = Runtime.getRuntime().totalMemory(); long freeMem = Runtime.getRuntime().freeMemory(); int percent = (int) (totalMem * 100 / maxMem); Log.d(TAG, "memoryWatch" + ", app maxMem = " + maxMem / divisor + "M, totalMem = " + totalMem / divisor + "M, freeMem = " + freeMem / divisor + "M, percent = " + percent); if (standard <= percent) { if (freeMem / divisor <= 2) { Log.e(TAG, "memoryWatch" + ", app maxMem = " + maxMem / divisor + "M, totalMem = " + totalMem / divisor + "M, freeMem = " + freeMem / divisor + "M, percent = " + percent); } else if (freeMem / divisor >= totalMem / (divisor * 2)) { Log.e(TAG, "memoryWatch" + ", app maxMem = " + maxMem / divisor + "M, totalMem = " + totalMem / divisor + "M, freeMem = " + freeMem / divisor + "M, percent = " + percent + "%" + ", reset memory warn flag = true!"); } } try { Thread.sleep(sleep); } catch (InterruptedException e) { Log.e(TAG, "memoryWatch, thread sleep exception : " + e); } } } }).start(); }
时间: 2024-10-29 04:56:40