MemInfoReader.java revision 8e69257a9c7e9c1781e1f53d8856358ada38921d
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.util;
18
19import java.io.FileInputStream;
20
21import android.os.Debug;
22import android.os.StrictMode;
23
24public class MemInfoReader {
25    byte[] mBuffer = new byte[1024];
26
27    private long mTotalSize;
28    private long mFreeSize;
29    private long mCachedSize;
30
31    private boolean matchText(byte[] buffer, int index, String text) {
32        int N = text.length();
33        if ((index+N) >= buffer.length) {
34            return false;
35        }
36        for (int i=0; i<N; i++) {
37            if (buffer[index+i] != text.charAt(i)) {
38                return false;
39            }
40        }
41        return true;
42    }
43
44    private long extractMemValue(byte[] buffer, int index) {
45        while (index < buffer.length && buffer[index] != '\n') {
46            if (buffer[index] >= '0' && buffer[index] <= '9') {
47                int start = index;
48                index++;
49                while (index < buffer.length && buffer[index] >= '0'
50                    && buffer[index] <= '9') {
51                    index++;
52                }
53                String str = new String(buffer, 0, start, index-start);
54                return ((long)Integer.parseInt(str)) * 1024;
55            }
56            index++;
57        }
58        return 0;
59    }
60
61    public void readMemInfo() {
62        // Permit disk reads here, as /proc/meminfo isn't really "on
63        // disk" and should be fast.  TODO: make BlockGuard ignore
64        // /proc/ and /sys/ files perhaps?
65        StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
66        try {
67            long[] infos = new long[Debug.MEMINFO_COUNT];
68            Debug.getMemInfo(infos);
69            mTotalSize = infos[Debug.MEMINFO_TOTAL] * 1024;
70            mFreeSize = infos[Debug.MEMINFO_FREE] * 1024;
71            mCachedSize = infos[Debug.MEMINFO_CACHED] * 1024;
72        } finally {
73            StrictMode.setThreadPolicy(savedPolicy);
74        }
75    }
76
77    public long getTotalSize() {
78        return mTotalSize;
79    }
80
81    public long getFreeSize() {
82        return mFreeSize;
83    }
84
85    public long getCachedSize() {
86        return mCachedSize;
87    }
88}
89