android內存檢測

 /**
     * 開啟線程檢測軟件可用內存情況,軟件退出後, 調用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  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 pisor = 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
                            / pisor + "M, totalMem = " + totalMem / pisor
                            + "M, freeMem = " + freeMem / pisor
                            + "M, percent = " + percent);
                    if (standard <= percent)
                    {
                        if (freeMem / pisor = totalMem / (pisor * 2))
                        {
                            Log.e(TAG, "memoryWatch" + ", app maxMem = "
                                    + maxMem / pisor + "M, totalMem = "
                                    + totalMem / pisor + "M, freeMem = "
                                    + freeMem / pisor + "M, percent = "
                                    + percent + "%"
                                    + ", reset memory warn flag = true!");
                        }
                    }

                    try
                    {
                        Thread.sleep(sleep);
                    }
                    catch (InterruptedException e)
                    {
                        Log.e(TAG, "memoryWatch, thread sleep exception : " + e);
                    }
                }
            }
        }).start();
    }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。