summaryrefslogtreecommitdiffstats
path: root/src/com/android/settings/deviceinfo/MemoryMeasurement.java
blob: 1aef20234d2b5b75cda21b674b468d02c9aa4bb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package com.android.settings.deviceinfo;

import com.android.internal.app.IMediaContainerService;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Measure the memory for various systems.
 *
 * TODO: This class should ideally have less knowledge about what the context
 * it's measuring is. In the future, reduce the amount of stuff it needs to
 * know about by just keeping an array of measurement types of the following
 * properties:
 *
 *   Filesystem stats (using StatFs)
 *   Directory measurements (using DefaultContainerService.measureDir)
 *   Applicaiton measurements (using PackageManager)
 *
 * Then the calling application would just specify the type and an argument.
 * This class would keep track of it while the calling application would
 * decide on how to use it.
 */
public class MemoryMeasurement {
    private static final String TAG = "MemoryMeasurement";

    public static final String TOTAL_SIZE = "total_size";

    public static final String AVAIL_SIZE = "avail_size";

    public static final String APPS_USED = "apps_used";

    public static final String MEDIA_USED = "media_used";

    private static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";

    private static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
            DEFAULT_CONTAINER_PACKAGE, "com.android.defcontainer.DefaultContainerService");

    private final MeasurementHandler mHandler;

    private static volatile MemoryMeasurement sInstance;

    private volatile WeakReference<MeasurementReceiver> mReceiver;

    // Internal memory fields
    private long mInternalTotalSize;
    private long mInternalAvailSize;
    private long mInternalMediaSize;
    private long mInternalAppsSize;

    // External memory fields
    private long mExternalTotalSize;

    private long mExternalAvailSize;

    private MemoryMeasurement(Context context) {
        // Start the thread that will measure the disk usage.
        final HandlerThread t = new HandlerThread("MemoryMeasurement");
        t.start();
        mHandler = new MeasurementHandler(context, t.getLooper());
    }

    /**
     * Get the singleton of the MemoryMeasurement class. The application
     * context is used to avoid leaking activities.
     */
    public static MemoryMeasurement getInstance(Context context) {
        if (sInstance == null) {
            synchronized (MemoryMeasurement.class) {
                if (sInstance == null) {
                    sInstance = new MemoryMeasurement(context.getApplicationContext());
                }
            }
        }

        return sInstance;
    }

    public void setReceiver(MeasurementReceiver receiver) {
        mReceiver = new WeakReference<MeasurementReceiver>(receiver);
    }

    public void measureExternal() {
        if (!mHandler.hasMessages(MeasurementHandler.MSG_MEASURE_EXTERNAL)) {
            mHandler.sendEmptyMessage(MeasurementHandler.MSG_MEASURE_EXTERNAL);
        }
    }

    public void measureInternal() {
        if (!mHandler.hasMessages(MeasurementHandler.MSG_MEASURE_INTERNAL)) {
            mHandler.sendEmptyMessage(MeasurementHandler.MSG_MEASURE_INTERNAL);
        }
    }

    public void cleanUp() {
        mReceiver = null;
        mHandler.cleanUp();
    }

    private void sendInternalApproximateUpdate() {
        MeasurementReceiver receiver = (mReceiver != null) ? mReceiver.get() : null;
        if (receiver == null) {
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putLong(TOTAL_SIZE, mInternalTotalSize);
        bundle.putLong(AVAIL_SIZE, mInternalAvailSize);

        receiver.updateApproximateInternal(bundle);
    }

    private void sendInternalExactUpdate() {
        MeasurementReceiver receiver = (mReceiver != null) ? mReceiver.get() : null;
        if (receiver == null) {
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putLong(TOTAL_SIZE, mInternalTotalSize);
        bundle.putLong(AVAIL_SIZE, mInternalAvailSize);
        bundle.putLong(APPS_USED, mInternalAppsSize);
        bundle.putLong(MEDIA_USED, mInternalMediaSize);

        receiver.updateExactInternal(bundle);
    }

    private void sendExternalApproximateUpdate() {
        MeasurementReceiver receiver = (mReceiver != null) ? mReceiver.get() : null;
        if (receiver == null) {
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putLong(TOTAL_SIZE, mExternalTotalSize);
        bundle.putLong(AVAIL_SIZE, mExternalAvailSize);

        receiver.updateApproximateExternal(bundle);
    }

    public interface MeasurementReceiver {
        public void updateApproximateInternal(Bundle bundle);

        public void updateExactInternal(Bundle bundle);

        public void updateApproximateExternal(Bundle bundle);
    }

    private class MeasurementHandler extends Handler {
        public static final int MSG_MEASURE_INTERNAL = 1;

        public static final int MSG_MEASURE_EXTERNAL = 2;

        public static final int MSG_CONNECTED = 3;

        public static final int MSG_DISCONNECT = 4;

        public static final int MSG_COMPLETED = 5;

        public static final int MSG_INVALIDATE = 6;

        private Object mLock = new Object();

        private IMediaContainerService mDefaultContainer;

        private volatile boolean mBound = false;

        private volatile boolean mMeasured = false;

        private StatsObserver mStatsObserver;

        private final WeakReference<Context> mContext;

        final private ServiceConnection mDefContainerConn = new ServiceConnection() {
            public void onServiceConnected(ComponentName name, IBinder service) {
                final IMediaContainerService imcs = IMediaContainerService.Stub
                        .asInterface(service);
                mDefaultContainer = imcs;
                mBound = true;
                sendMessage(obtainMessage(MSG_CONNECTED, imcs));
            }

            public void onServiceDisconnected(ComponentName name) {
                mBound = false;
                removeMessages(MSG_CONNECTED);
            }
        };

        public MeasurementHandler(Context context, Looper looper) {
            super(looper);
            mContext = new WeakReference<Context>(context);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_MEASURE_EXTERNAL: {
                    if (mMeasured) {
                        sendExternalApproximateUpdate();
                        break;
                    }

                    measureApproximateExternalStorage();
                    break;
                }
                case MSG_MEASURE_INTERNAL: {
                    if (mMeasured) {
                        sendInternalExactUpdate();
                        break;
                    }

                    final Context context = (mContext != null) ? mContext.get() : null;
                    if (context == null) {
                        return;
                    }

                    measureApproximateInternalStorage();

                    synchronized (mLock) {
                        if (mBound) {
                            removeMessages(MSG_DISCONNECT);
                            sendMessage(obtainMessage(MSG_CONNECTED, mDefaultContainer));
                        } else {
                            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
                            context.bindService(service, mDefContainerConn,
                                    Context.BIND_AUTO_CREATE);
                        }
                    }
                    break;
                }
                case MSG_CONNECTED: {
                    IMediaContainerService imcs = (IMediaContainerService) msg.obj;
                    measureExactInternalStorage(imcs);
                }
                case MSG_DISCONNECT: {
                    synchronized (mLock) {
                        if (mBound) {
                            final Context context = (mContext != null) ? mContext.get() : null;
                            if (context == null) {
                                return;
                            }

                            mBound = false;
                            context.unbindService(mDefContainerConn);
                        }
                    }
                }
                case MSG_COMPLETED: {
                    mMeasured = true;
                    sendInternalExactUpdate();
                    break;
                }
                case MSG_INVALIDATE: {
                    mMeasured = false;
                    break;
                }
            }
        }

        public void cleanUp() {
            removeMessages(MSG_MEASURE_INTERNAL);
            removeMessages(MSG_MEASURE_EXTERNAL);

            sendEmptyMessage(MSG_DISCONNECT);
        }

        /**
         * Request measurement of each package.
         *
         * @param pm PackageManager instance to query
         */
        public void requestQueuedMeasurementsLocked(PackageManager pm) {
            final List<String> appsList = mStatsObserver.getAppsList();
            final int N = appsList.size();
            for (int i = 0; i < N; i++) {
                pm.getPackageSizeInfo(appsList.get(i), mStatsObserver);
            }
        }

        private class StatsObserver extends IPackageStatsObserver.Stub {
            private long mAppsSizeForThisStatsObserver = 0;
            private final List<String> mAppsList = new ArrayList<String>();
            public void onGetStatsCompleted(PackageStats stats, boolean succeeded) {
                if (!mStatsObserver.equals(this)) {
                    // this callback's class object is no longer in use. ignore this callback.
                    return;
                }
                if (succeeded) {
                    mAppsSizeForThisStatsObserver += stats.codeSize + stats.dataSize +
                            stats.externalCacheSize + stats.externalDataSize +
                            stats.externalMediaSize + stats.externalObbSize;
                }

                synchronized (mAppsList) {
                    mAppsList.remove(stats.packageName);

                    if (mAppsList.size() == 0) {
                        mInternalAppsSize = mAppsSizeForThisStatsObserver;

                        onInternalMeasurementComplete();
                    }
                }
            }

            public void queuePackageMeasurementLocked(String packageName) {
                mAppsList.add(packageName);
            }
            public List<String> getAppsList() {
                return mAppsList;
            }
        }

        private void onInternalMeasurementComplete() {
            sendEmptyMessage(MSG_COMPLETED);
        }

        private void measureApproximateInternalStorage() {
            final File dataPath = Environment.getDataDirectory();
            final StatFs stat = new StatFs(dataPath.getPath());
            final long blockSize = stat.getBlockSize();
            final long totalBlocks = stat.getBlockCount();
            final long availableBlocks = stat.getAvailableBlocks();

            final long totalSize = totalBlocks * blockSize;
            final long availSize = availableBlocks * blockSize;

            mInternalTotalSize = totalSize;
            mInternalAvailSize = availSize;

            sendInternalApproximateUpdate();
        }

        private void measureExactInternalStorage(IMediaContainerService imcs) {
            Context context = mContext != null ? mContext.get() : null;
            if (context == null) {
                return;
            }

            // We have to get installd to measure the package sizes.
            PackageManager pm = context.getPackageManager();
            if (pm == null) {
                return;
            }

            long mediaSize;
            try {
                mediaSize = imcs.calculateDirectorySize(
                        Environment.getExternalStorageDirectory().getAbsolutePath());
            } catch (Exception e) {
                Log.i(TAG, "Could not read memory from default container service");
                return;
            }

            mInternalMediaSize = mediaSize;

            final List<ApplicationInfo> apps = pm
                    .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES
                            | PackageManager.GET_DISABLED_COMPONENTS);
            if (apps != null) {
                // initiate measurement of all package sizes. need new StatsObserver object.
                mStatsObserver = new StatsObserver();
                synchronized (mStatsObserver.mAppsList) {
                    for (int i = 0; i < apps.size(); i++) {
                        final ApplicationInfo info = apps.get(i);
                        mStatsObserver.queuePackageMeasurementLocked(info.packageName);
                    }

                    requestQueuedMeasurementsLocked(pm);
                }
            }

            // Sending of the message back to the MeasurementReceiver is
            // completed in the PackageObserver
        }

        public void measureApproximateExternalStorage() {
            File path = Environment.getExternalStorageDirectory();

            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            long availableBlocks = stat.getAvailableBlocks();

            mExternalTotalSize = totalBlocks * blockSize;
            mExternalAvailSize = availableBlocks * blockSize;

            sendExternalApproximateUpdate();
        }
    }

    public void invalidate() {
        mHandler.sendEmptyMessage(MeasurementHandler.MSG_INVALIDATE);
    }
}