Example usage for android.app ActivityManager getMemoryInfo

List of usage examples for android.app ActivityManager getMemoryInfo

Introduction

In this page you can find the example usage for android.app ActivityManager getMemoryInfo.

Prototype

public void getMemoryInfo(MemoryInfo outInfo) 

Source Link

Document

Return general information about the memory state of the system.

Usage

From source file:pandroid.agent.PandroidAgentListener.java

private void getMemoryStatus() {
    String memoryStatus = getSharedData("PANDROID_DATA", "memoryStatus", Core.defaultMemoryStatus, "string");
    long availableRamKb = 0;
    long totalRamKb = 0;

    if (memoryStatus.equals("enabled")) {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        availableRamKb = mi.availMem / 1024;
        totalRamKb = 0;//from w w  w .  jav  a2  s.c o m

        try {
            RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");

            String line = reader.readLine();
            reader.close();
            line = line.replaceAll("[ ]+", " ");
            String[] tokens = line.split(" ");

            totalRamKb = Long.valueOf(tokens[1]);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    putSharedData("PANDROID_DATA", "availableRamKb", "" + availableRamKb, "long");
    putSharedData("PANDROID_DATA", "totalRamKb", "" + totalRamKb, "long");
}

From source file:org.metawatch.manager.MetaWatchService.java

@Override
public void onLowMemory() {
    MemoryInfo mi = new MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    long availableMegs = mi.availMem / 1048576L;

    if (Preferences.logging)
        Log.d(MetaWatchStatus.TAG, "MetaWatchService.onLowMemory(): " + availableMegs + "Mb free");

    super.onLowMemory();
}

From source file:com.androchill.call411.MainActivity.java

private Phone getHardwareSpecs() {
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    PhoneBuilder pb = new PhoneBuilder();
    pb.setModelNumber(Build.MODEL);// w  w w. j a  v  a  2 s.co m
    pb.setManufacturer(Build.MANUFACTURER);

    Process p = null;
    String board_platform = "No data available";
    try {
        p = new ProcessBuilder("/system/bin/getprop", "ro.chipname").redirectErrorStream(true).start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            board_platform = line;
        }
        p.destroy();
    } catch (IOException e) {
        e.printStackTrace();
        board_platform = "No data available";
    }

    pb.setProcessor(board_platform);
    ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(mInfo);
    pb.setRam((int) (mInfo.totalMem / 1048576L));
    pb.setBatteryCapacity(getBatteryCapacity());
    pb.setTalkTime(-1);
    pb.setDimensions("No data available");

    WindowManager mWindowManager = getWindowManager();
    Display mDisplay = mWindowManager.getDefaultDisplay();
    Point mPoint = new Point();
    mDisplay.getSize(mPoint);
    pb.setScreenResolution(mPoint.x + " x " + mPoint.y + " pixels");

    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    mDisplay.getMetrics(mDisplayMetrics);
    int mDensity = mDisplayMetrics.densityDpi;
    pb.setScreenSize(
            Math.sqrt(Math.pow(mPoint.x / (double) mDensity, 2) + Math.pow(mPoint.y / (double) mDensity, 2)));

    Camera camera = Camera.open(0);
    android.hardware.Camera.Parameters params = camera.getParameters();
    List sizes = params.getSupportedPictureSizes();
    Camera.Size result = null;

    ArrayList<Integer> arrayListForWidth = new ArrayList<Integer>();
    ArrayList<Integer> arrayListForHeight = new ArrayList<Integer>();

    for (int i = 0; i < sizes.size(); i++) {
        result = (Camera.Size) sizes.get(i);
        arrayListForWidth.add(result.width);
        arrayListForHeight.add(result.height);
    }
    if (arrayListForWidth.size() != 0 && arrayListForHeight.size() != 0) {
        pb.setCameraMegapixels(
                Collections.max(arrayListForHeight) * Collections.max(arrayListForWidth) / (double) 1000000);
    } else {
        pb.setCameraMegapixels(-1);
    }
    camera.release();

    pb.setPrice(-1);
    pb.setWeight(-1);
    pb.setSystem("Android " + Build.VERSION.RELEASE);

    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    StatFs statInternal = new StatFs(Environment.getRootDirectory().getAbsolutePath());
    double storageSize = ((stat.getBlockSizeLong() * stat.getBlockCountLong())
            + (statInternal.getBlockSizeLong() * statInternal.getBlockCountLong())) / 1073741824L;
    pb.setStorageOptions(storageSize + " GB");
    TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
    String operatorName = telephonyManager.getNetworkOperatorName();
    if (operatorName.length() == 0)
        operatorName = "No data available";
    pb.setCarrier(operatorName);
    pb.setNetworkFrequencies("No data available");
    pb.setImage(null);
    return pb.createPhone();
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

/**
 * @return [total, idle, free]//w w w  . ja va2s. c  o m
 */
static long[] getMemState(Context ctx) {
    BufferedReader reader = null;

    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(F_MEM_INFO))), 1024);

        String line;
        String totalMsg = null;
        String freeMsg = null;

        while ((line = reader.readLine()) != null) {
            if (line.startsWith("MemTotal")) //$NON-NLS-1$
            {
                totalMsg = line;
            } else if (line.startsWith("MemFree")) //$NON-NLS-1$
            {
                freeMsg = line;
            }

            if (totalMsg != null && freeMsg != null) {
                break;
            }
        }

        long[] mem = new long[3];

        mem[0] = extractMemCount(totalMsg);
        mem[1] = extractMemCount(freeMsg);

        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);
        mem[2] = mi.availMem;

        return mem;
    } catch (Exception e) {
        Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ie) {
                Log.e(SiragonManager.class.getName(), ie.getLocalizedMessage(), ie);
            }
        }
    }

    return null;
}

From source file:com.landenlabs.all_devtool.SystemFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*w  ww.  j  a v  a 2s.  c o m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public long GetMemoryConfig() {
    ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
    aMgr.getMemoryInfo(outInfo);
    long lMem = outInfo.availMem;

    return (lMem);
}

From source file:com.skytree.epubtest.BookViewActivity.java

public void reportMemory() {
    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();

    //      Log.v("EPub", "maxMemory:" + Long.toString(maxMemory));

    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    int memoryClass = am.getMemoryClass();
    //      Log.v("EPub", "memoryClass:" + Integer.toString(memoryClass));   

    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    MemoryInfo memoryInfo = new MemoryInfo();
    activityManager.getMemoryInfo(memoryInfo);
    //      Log.i("EPub", "AvailMem" + memoryInfo.availMem);

    long memoryAvail = memoryInfo.availMem;
    long memoryAlloc = maxMemory - memoryAvail;

    String message = String.format("Max :%d Avail:%d", maxMemory, memoryAvail);
    showToast(message);/*from w w  w . j ava 2 s . c  o  m*/
}