How to Detect Lowmemory in android?

前端 未结 7 1658
-上瘾入骨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

    As explained at android developers is hard to determine how much memory we have available for our app since: The exact heap size limit varies between devices based on how much RAM the device has available overall. So is a better approach to ask if we are running in a lowMemory environment using ActivityManager.MemoryInfo before doing a memory heavy operation like downloading an image or trying to load an image into memory, by doing this you will prevent OutOfMemoryExceptions

    public void doSomethingMemoryIntensive() {
    
        // Before doing something that requires a lot of memory,
        // check to see whether the device is in a low memory state.
        ActivityManager.MemoryInfo memoryInfo = getAvailableMemory();
    
        if (!memoryInfo.lowMemory) {
           // Do memory intensive work ...
        }
    }
    // Get a MemoryInfo object for the device's current memory status.
    private ActivityManager.MemoryInfo getAvailableMemory() {
        ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo;
    }
    

提交回复
热议问题