How to Detect Lowmemory in android?

前端 未结 7 1648
-上瘾入骨i
-上瘾入骨i 2021-02-13 14:34

My application has a lot of images and sometimes it crashes due to low memory. I wrote this function that I found on the developer site.

public void onLowM         


        
7条回答
  •  离开以前
    2021-02-13 15:26

    Along with onLowMemory() and onTrimMemory(), which monitor system memory, here's a way to monitor app memory. It uses Zsolt Safrany's answer at it's core.

    private final float CHECK_MEMORY_FREQ_SECONDS = 3.0f;
    private final float LOW_MEMORY_THRESHOLD_PERCENT = 5.0f; // Available %
    private Handler memoryHandler_;
    
    public void onCreate( Bundle savedInstanceState ) {
    
    // Do Stuff...
    
     // Start Monitoring App Memory Availablity
        memoryHandler_ = new Handler();
        checkAppMemory();
    }
    
    public void checkAppMemory(){
        // Get app memory info
        long available = Runtime.getRuntime().maxMemory();
        long used = Runtime.getRuntime().totalMemory();
    
        // Check for & and handle low memory state
        float percentAvailable = 100f * (1f - ((float) used / available ));
        if( percentAvailable <= LOW_MEMORY_THRESHOLD_PERCENT )
            handleLowMemory();
    
        // Repeat after a delay
        memoryHandler_.postDelayed( new Runnable(){ public void run() {
            checkAppMemory();
        }}, (int)(CHECK_MEMORY_FREQ_SECONDS * 1000) );
    }
    
    public void handleLowMemory(){ 
        // Free Memory Here
    }
    

提交回复
热议问题