Detect application heap size in Android

后端 未结 9 1957
-上瘾入骨i
-上瘾入骨i 2020-11-22 07:38

How do you programmatically detect the application heap size available to an Android app?

I heard there\'s a function that does this in later versions of the SDK. In

9条回答
  •  情歌与酒
    2020-11-22 08:06

    Some operations are quicker than java heap space manager. Delaying operations for some time can free memory space. You can use this method to escape heap size error:

    waitForGarbageCollector(new Runnable() {
      @Override
      public void run() {
    
        // Your operations.
      }
    });
    
    /**
     * Measure used memory and give garbage collector time to free up some
     * space.
     *
     * @param callback Callback operations to be done when memory is free.
     */
    public static void waitForGarbageCollector(final Runnable callback) {
    
      Runtime runtime;
      long maxMemory;
      long usedMemory;
      double availableMemoryPercentage = 1.0;
      final double MIN_AVAILABLE_MEMORY_PERCENTAGE = 0.1;
      final int DELAY_TIME = 5 * 1000;
    
      runtime =
        Runtime.getRuntime();
    
      maxMemory =
        runtime.maxMemory();
    
      usedMemory =
        runtime.totalMemory() -
        runtime.freeMemory();
    
      availableMemoryPercentage =
        1 -
        (double) usedMemory /
        maxMemory;
    
      if (availableMemoryPercentage < MIN_AVAILABLE_MEMORY_PERCENTAGE) {
    
        try {
          Thread.sleep(DELAY_TIME);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    
        waitForGarbageCollector(
          callback);
      } else {
    
        // Memory resources are availavle, go to next operation:
    
        callback.run();
      }
    }
    

提交回复
热议问题