Search code examples
androidandroid-memorybatterylevel

How to retrieve available system ram and battery level


Im currently working on an app that I really need help with and I've come to the stage where I need a bit of help. Ok so I am trying to get the amount of free system memory/Ram and the battery level of the device and I want to display them in my app activity.

here is what I have so far.

MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;

Solution

  • Register for this action in your activity Intent.ACTION_BATTERY_CHANGED

    And write below code to get battery level from the broadcast receiver.

    BroadcastReceiver mReceiver = new BroadcastReceiver() 
    {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            } 
        }
    };
    

    level value gives the battery level of your device.