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:net.microtrash.clapcamera.Preview.java

/**
 * find the best resolution for both: picture and preview size by following
 * rules ISSUES: 1. on each device you have several different camera picture
 * sizes and camera preview sizes 2. the picture size and the camera size
 * have to match in terms of their width to height relation (=aspect ratio)
 * 3. we want to make sure the area of the display is used as efficient as
 * possible, therefore we should try to match the aspect ratios of display
 * and image as well 4. you never know how much RAM you will have available,
 * once the user switches the app and returnes, memory might not be enough
 * anymore//from   w  w  w .j a  v a  2 s  .  c  o m
 * 
 * VERY NEW: 1. find all preview sizes which match a image size (same aspect
 * ratio) -> resolution-settings 2. preselect the highest
 * resolution-settings which fits twice into memory 3. generate UI for
 * selecting other resolutions-settings-> let the user decide which
 * resolution fits best for his/her device
 * 
 * NEW: 1. calculate targetRato = device display aspect ratio 2. find a
 * matching preview image size and set it as bestPictureSize (matching: the
 * picture and preview aspect ratios have to match) 3. if a another
 * pictureSize-previewSize match is found, which has a better targetRatio
 * match and the picture size > bestPictureSize - 20% -> set this one as
 * bestPictureSize 4. try to find a downscaling factor which allows us to
 * keep 2-3 layers (bitmap instances) of that resolution in memory
 * 
 * OLD: 1. try to find the best matching picture resolution for targetRatio
 * 2. only allow resolutions above 800px width 3. look for an exactly
 * matching preview resolution. if not found: 4. try to find the second best
 * matching picture resolution for targetRatio and start all over again 5.
 * if nothing matching was found: use first picture and first preview
 * resolution
 * 
 * @param targetRatio
 */
private void calculateOptimalPictureAndPreviewSizes() {

    /*
     * double fullWidth = (double) cameraActivity.display.getWidth(); double
     * fullHeight = (double) cameraActivity.display.getHeight();
     */
    double targetRatio = (fullWidth - 2 * (double) padding) / (fullHeight - 2 * (double) padding);
    Log.v(TAG, "calculateOptimalPictureAndPreviewSizes() width targetRatio: " + targetRatio + " fullWidth:"
            + fullWidth + " fullHeight:" + fullHeight);

    if (bestPreviewSize == null) {
        allResolutions = "";
        List<Size> pictureSizes = this.camera.getParameters().getSupportedPictureSizes();
        List<Size> previewSizes = this.camera.getParameters().getSupportedPreviewSizes();
        Collections.sort(pictureSizes, new Comparator<Size>() {
            public int compare(Size s1, Size s2) {
                return s2.width - s1.width;
            }
        });

        Collections.sort(previewSizes, new Comparator<Size>() {
            public int compare(Size s1, Size s2) {
                return s2.width - s1.width;
            }
        });

        allResolutions += "picture sizes:\n";
        for (Size size : pictureSizes) {
            allResolutions += String.valueOf(size.width) + 'x' + String.valueOf(size.height) + ", ratio: "
                    + ((double) size.width / (double) size.height) + ";\n";
        }

        allResolutions += "preview sizes:\n";
        for (Size size : previewSizes) {
            allResolutions += String.valueOf(size.width) + 'x' + String.valueOf(size.height) + ", ratio: "
                    + ((double) size.width / (double) size.height) + ";\n";
        }
        Log.v(TAG, "allResolutions: \n" + allResolutions);
        double bestRatio = 0;
        boolean matchingFinished = false;
        Log.v(TAG, "start matching picture and preview size...");
        for (Size pictureSize : pictureSizes) {
            double pictureRatio = (double) pictureSize.width / (double) pictureSize.height;
            Log.v(TAG, "size: " + pictureSize.width + "x" + pictureSize.height + " " + pictureRatio);
            double previewRatio;
            for (Size previewSize : previewSizes) {
                previewRatio = (double) previewSize.width / (double) previewSize.height;
                if (previewRatio == pictureRatio) {

                    if (bestPreviewSize == null) {
                        bestPreviewSize = previewSize;
                        bestPictureSize = pictureSize;
                        bestRatio = pictureRatio;
                        Log.v(TAG,
                                "found picture size:" + bestPictureSize.width + "x" + bestPictureSize.height
                                        + " ratio: "
                                        + ((double) bestPictureSize.width / (double) bestPictureSize.height));
                        Log.v(TAG, "...continue searching...");
                        break;
                    } else {
                        Log.v(TAG, "  pixels: " + pictureSize.width * pictureSize.height);
                        Log.v(TAG, "  thresh: "
                                + (double) bestPictureSize.width * (double) bestPictureSize.height * 0.75D);
                        if (Math.abs(targetRatio - bestRatio) > Math.abs(targetRatio - pictureRatio)
                                && pictureSize.width * pictureSize.height > (double) bestPictureSize.width
                                        * (double) bestPictureSize.height * 0.75D) {
                            bestPreviewSize = previewSize;
                            bestPictureSize = pictureSize;
                            bestRatio = pictureRatio;
                            matchingFinished = true;
                            Log.v(TAG, "found even better match:" + bestPictureSize.width + "x"
                                    + bestPictureSize.height + " ratio: "
                                    + ((double) bestPictureSize.width / (double) bestPictureSize.height));
                        }
                    }
                }
            }
            if (matchingFinished) {
                break;
            }
        }

        if (bestPreviewSize == null) {
            bestPictureSize = pictureSizes.get(0);
            bestPreviewSize = previewSizes.get(0);
            Log.v(TAG, "no match found!");
        }

        downscalingFactor = Tools.getDownscalingFactor(bestPictureSize.width, bestPictureSize.height);

        Log.v(TAG, "choosen picture size:" + bestPictureSize.width + "x" + bestPictureSize.height + " ratio: "
                + ((double) bestPictureSize.width / (double) bestPictureSize.height));
        Log.v(TAG, "choosen preview size:" + bestPreviewSize.width + "x" + bestPreviewSize.height + " ratio: "
                + ((double) bestPreviewSize.width / (double) bestPreviewSize.height));
        Log.v(TAG, "choosen downScalingFactor: " + downscalingFactor);
        // instantiate metadata json object
        JSONObject metadata = new JSONObject();
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        final long mb = 1024L * 1024L;
        try {
            metadata.put("totalMemory", Runtime.getRuntime().totalMemory() / mb);
            metadata.put("freeMemory", Runtime.getRuntime().freeMemory() / mb);
            metadata.put("maxMemory", Runtime.getRuntime().maxMemory() / mb);
            metadata.put("availableMemory", mi.availMem / mb);
            metadata.put("nativeHeapAllocatedSize", Debug.getNativeHeapAllocatedSize() / mb);
            metadata.put("heapPad", Tools.getHeapPad() / mb);
            metadata.put("bestPictureSize", bestPictureSize.width + "x" + bestPictureSize.height);
            metadata.put("bestPreviewSize", bestPreviewSize.width + "x" + bestPreviewSize.height);
            metadata.put("workingPictureSize", (int) bestPictureSize.width / downscalingFactor + "x"
                    + (int) bestPictureSize.height / downscalingFactor);
            metadata.put("downscalingFactor", downscalingFactor);
            metadata.put("requiredSize", (bestPictureSize.width / downscalingFactor)
                    * (bestPictureSize.height / downscalingFactor) * 4 * 2 / mb); // 4 channels * 2 layers
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Crittercism.setMetadata(metadata);

    }

}

From source file:com.hmatalonga.greenhub.ui.TaskListActivity.java

private double getAvailableMemory() {
    ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(info);

    return Math.round(info.availMem / 1048576.0 * 100.0) / 100.0;
}

From source file:com.att.arocollector.AROCollectorActivity.java

public void handleUncaughtException(Thread thread, Throwable e) {

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

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

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;/*from w w  w  .  j  av  a2 s  . c o  m*/

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.prey.PreyPhone.java

@TargetApi(16)
private void initMemory() {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
    MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(memoryInfo);
    long totalMemory = totalMemory();

    long freeMemory = memoryInfo.availMem / 1048576L;
    long usageMemory = totalMemory - freeMemory;
    hardware.setTotalMemory(totalMemory);
    hardware.setFreeMemory(totalMemory);
    hardware.setBusyMemory(usageMemory);
}

From source file:com.prey.PreyPhone.java

private long getMemoryRamSize() {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(mInfo);
    return (mInfo.threshold >> 20);
}

From source file:com.prey.PreyPhone.java

private Map<String, String> getProcessorData() {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(mInfo);

    String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
    ProcessBuilder pb = new ProcessBuilder(args);

    Process process;//from  w  ww .j  a  va2s. c o m
    Map<String, String> mapData = new HashMap<String, String>();
    try {
        process = pb.start();
        InputStream in = process.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String aLine;
        while ((aLine = br.readLine()) != null) {
            String[] data = aLine.split(":");
            try {
                mapData.put(data[0].trim(), data[1].trim());
            } catch (Exception e) {
            }
        }
        if (br != null) {
            br.close();
        }
    } catch (IOException e) {
    }
    return mapData;
}

From source file:com.softminds.matrixcalculator.MainActivity.java

private ActivityManager.MemoryInfo getAvailableMemory() {
    ActivityManager manager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    if (manager != null) {
        manager.getMemoryInfo(memoryInfo);
        return memoryInfo;
    }/*from   w ww  .  j ava  2  s  . c  om*/
    return null;

}

From source file:tk.eatheat.omnisnitch.ui.SwitchLayout.java

@SuppressWarnings("rawtypes")
public SwitchLayout(Context context) {
    mContext = context;//w ww .  j ava2 s .com
    mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    mConfiguration = SwitchConfiguration.getInstance(mContext);

    mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mLoadedTasks = new ArrayList<TaskDescription>();
    mRecentListAdapter = new RecentListAdapter(mContext, android.R.layout.simple_list_item_multiple_choice,
            mLoadedTasks);
    mFavoriteList = new ArrayList<String>();
    mFavoriteListAdapter = new FavoriteListAdapter(mContext, android.R.layout.simple_list_item_multiple_choice,
            mFavoriteList);

    final ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    am.getMemoryInfo(mMemInfo);
    String sClassName = "android.app.ActivityManager";
    try {
        Class classToInvestigate = Class.forName(sClassName);
        Class[] classes = classToInvestigate.getDeclaredClasses();
        for (int i = 0; i < classes.length; i++) {
            Class c = classes[i];
            if (c.getName().equals("android.app.ActivityManager$MemoryInfo")) {
                String strNewFieldName = "secondaryServerThreshold";
                Field field = c.getField(strNewFieldName);
                mSecServerMem = field.getLong(mMemInfo);
                break;
            }
        }
    } catch (ClassNotFoundException e) {
    } catch (NoSuchFieldException e) {
    } catch (Exception e) {
    }
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Log the memory statuses.//  www . j a  v a 2 s .c om
 *
 * @param activity the calling activity
 * @return if the device is running on low memory.
 */
public static boolean displayMemoryInformation(Activity activity, String title) {
    long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = -1L;
    try {
        Runtime info = Runtime.getRuntime();
        freeSize = info.freeMemory();
        totalSize = info.totalMemory();
        usedSize = totalSize - freeSize;
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
    Log.e(LOW_MEMORY_LOG_TAG, "----------- " + title + " -----------------");
    Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
    Log.e(LOW_MEMORY_LOG_TAG, "usedSize   " + (usedSize / 1048576L) + " MB");
    Log.e(LOW_MEMORY_LOG_TAG, "freeSize   " + (freeSize / 1048576L) + " MB");
    Log.e(LOW_MEMORY_LOG_TAG, "totalSize  " + (totalSize / 1048576L) + " MB");
    Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");

    if (null != activity) {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        Log.e(LOW_MEMORY_LOG_TAG, "availMem   " + (mi.availMem / 1048576L) + " MB");
        Log.e(LOW_MEMORY_LOG_TAG, "totalMem   " + (mi.totalMem / 1048576L) + " MB");
        Log.e(LOW_MEMORY_LOG_TAG, "threshold  " + (mi.threshold / 1048576L) + " MB");
        Log.e(LOW_MEMORY_LOG_TAG, "lowMemory  " + (mi.lowMemory));
        Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
        return mi.lowMemory;
    } else {
        return false;
    }
}