summaryrefslogtreecommitdiff
path: root/Settings/src/com/android/tv/settings/device/storage/StorageFragment.java
blob: b3e16b757041626c8a4ac984d0990fbdbae1c515 (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
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.tv.settings.device.storage;

import static com.android.tv.settings.util.InstrumentationUtils.logEntrySelected;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.tvsettings.TvSettingsEnums;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.text.TextUtils;
import android.util.Log;

import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;

import com.android.settingslib.deviceinfo.StorageMeasurement;
import com.android.tv.settings.R;
import com.android.tv.settings.SettingsPreferenceFragment;
import com.android.tv.settings.device.apps.AppsFragment;
import com.android.tv.twopanelsettings.TwoPanelSettingsFragment;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * The screen in TV settings that lets users manage external storage devices and that shows the
 * usage summary by data type such as apps, music, download and so on.
 */
public class StorageFragment extends SettingsPreferenceFragment {
    private static final String TAG = "StorageFragment";

    private static final String KEY_MIGRATE = "migrate";
    private static final String KEY_EJECT = "eject";
    private static final String KEY_ERASE = "erase";
    private static final String KEY_APPS_USAGE = "apps_usage";
    private static final String KEY_DCIM_USAGE = "dcim_usage";
    private static final String KEY_MUSIC_USAGE = "music_usage";
    private static final String KEY_DOWNLOADS_USAGE = "downloads_usage";
    private static final String KEY_CACHE_USAGE = "cache_usage";
    private static final String KEY_MISC_USAGE = "misc_usage";
    private static final String KEY_AVAILABLE = "available";

    private StorageManager mStorageManager;
    private PackageManager mPackageManager;

    private VolumeInfo mVolumeInfo;

    private StorageMeasurement mMeasure;
    private final StorageMeasurement.MeasurementReceiver mMeasurementReceiver =
            new MeasurementReceiver();
    private final StorageEventListener mStorageEventListener = new StorageEventListener();

    private Preference mMigratePref;
    private Preference mEjectPref;
    private Preference mErasePref;
    private StoragePreference mAppsUsagePref;
    private StoragePreference mDcimUsagePref;
    private StoragePreference mMusicUsagePref;
    private StoragePreference mDownloadsUsagePref;
    private StoragePreference mCacheUsagePref;
    private StoragePreference mMiscUsagePref;
    private StoragePreference mAvailablePref;

    public static void prepareArgs(Bundle bundle, VolumeInfo volumeInfo) {
        bundle.putString(VolumeInfo.EXTRA_VOLUME_ID, volumeInfo.getId());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mStorageManager = getContext().getSystemService(StorageManager.class);
        mPackageManager = getContext().getPackageManager();

        mVolumeInfo = mStorageManager.findVolumeById(
                getArguments().getString(VolumeInfo.EXTRA_VOLUME_ID));

        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        mStorageManager.registerListener(mStorageEventListener);
        startMeasurement();
    }

    @Override
    public void onResume() {
        super.onResume();
        mVolumeInfo = mStorageManager.findVolumeById(
                getArguments().getString(VolumeInfo.EXTRA_VOLUME_ID));
        if (mVolumeInfo == null || !mVolumeInfo.isMountedReadable()) {
            navigateBack();
        } else {
            refresh();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mStorageManager.unregisterListener(mStorageEventListener);
        stopMeasurement();
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.storage, null);

        final PreferenceScreen screen = getPreferenceScreen();
        screen.setTitle(mStorageManager.getBestVolumeDescription(mVolumeInfo));

        mMigratePref = findPreference(KEY_MIGRATE);
        mEjectPref = findPreference(KEY_EJECT);
        mErasePref = findPreference(KEY_ERASE);

        mAppsUsagePref = (StoragePreference) findPreference(KEY_APPS_USAGE);
        mDcimUsagePref = (StoragePreference) findPreference(KEY_DCIM_USAGE);
        mMusicUsagePref = (StoragePreference) findPreference(KEY_MUSIC_USAGE);
        mDownloadsUsagePref = (StoragePreference) findPreference(KEY_DOWNLOADS_USAGE);
        mCacheUsagePref = (StoragePreference) findPreference(KEY_CACHE_USAGE);
        mMiscUsagePref = (StoragePreference) findPreference(KEY_MISC_USAGE);
        mAvailablePref = (StoragePreference) findPreference(KEY_AVAILABLE);
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        switch (preference.getKey()) {
            case KEY_APPS_USAGE:
                logEntrySelected(TvSettingsEnums.SYSTEM_STORAGE_INTERNAL_STORAGE_APPS);
                break;
            case KEY_CACHE_USAGE:
                logEntrySelected(TvSettingsEnums.SYSTEM_STORAGE_INTERNAL_STORAGE_CACHED);
                break;
        }
        return super.onPreferenceTreeClick(preference);
    }

    private void refresh() {
        boolean showMigrate = false;
        final VolumeInfo currentExternal = mPackageManager.getPrimaryStorageCurrentVolume();
        // currentExternal will be null if the drive is not mounted. Don't offer the option to
        // migrate if so.
        if (currentExternal != null
                && !TextUtils.equals(currentExternal.getId(), mVolumeInfo.getId())) {
            final List<VolumeInfo> candidates =
                    mPackageManager.getPrimaryStorageCandidateVolumes();
            for (final VolumeInfo candidate : candidates) {
                if (TextUtils.equals(candidate.getId(), mVolumeInfo.getId())) {
                    showMigrate = true;
                    break;
                }
            }
        }

        mMigratePref.setVisible(showMigrate);
        mMigratePref.setIntent(
                MigrateStorageActivity.getLaunchIntent(getContext(), mVolumeInfo.getId(), true));

        final String description = mStorageManager.getBestVolumeDescription(mVolumeInfo);

        final boolean privateInternal = VolumeInfo.ID_PRIVATE_INTERNAL.equals(mVolumeInfo.getId());
        final boolean isPrivate = mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;

        mEjectPref.setVisible(!privateInternal);
        mEjectPref.setIntent(UnmountActivity.getIntent(getContext(), mVolumeInfo.getId(),
                description));
        mErasePref.setVisible(!privateInternal);
        if (isPrivate) {
            mErasePref.setIntent(
                    FormatActivity.getFormatAsPublicIntent(getContext(), mVolumeInfo.getDiskId()));
            mErasePref.setTitle(R.string.storage_format_as_public);
        } else {
            mErasePref.setIntent(
                    FormatActivity.getFormatAsPrivateIntent(getContext(), mVolumeInfo.getDiskId()));
            mErasePref.setTitle(R.string.storage_format_as_private);
        }

        mAppsUsagePref.setVisible(isPrivate);
        mAppsUsagePref.setFragment(AppsFragment.class.getName());
        AppsFragment.prepareArgs(mAppsUsagePref.getExtras(), mVolumeInfo.fsUuid, description);
        mDcimUsagePref.setVisible(isPrivate);
        mMusicUsagePref.setVisible(isPrivate);
        mDownloadsUsagePref.setVisible(isPrivate);
        mCacheUsagePref.setVisible(isPrivate);
        mCacheUsagePref.setFragment(ConfirmClearCacheFragment.class.getName());
    }

    private void startMeasurement() {
        if (mVolumeInfo != null && mVolumeInfo.isMountedReadable()) {
            final VolumeInfo sharedVolume = mStorageManager.findEmulatedForPrivate(mVolumeInfo);
            mMeasure = new StorageMeasurement(getContext(), mVolumeInfo, sharedVolume);
            mMeasure.setReceiver(mMeasurementReceiver);
            mMeasure.forceMeasure();
        }
    }

    private void stopMeasurement() {
        if (mMeasure != null) {
            mMeasure.onDestroy();
        }
    }

    private void updateDetails(StorageMeasurement.MeasurementDetails details) {
        final int currentUser = ActivityManager.getCurrentUser();
        final long dcimSize = totalValues(details.mediaSize.get(currentUser),
                Environment.DIRECTORY_DCIM,
                Environment.DIRECTORY_MOVIES, Environment.DIRECTORY_PICTURES);

        final long musicSize = totalValues(details.mediaSize.get(currentUser),
                Environment.DIRECTORY_MUSIC,
                Environment.DIRECTORY_ALARMS, Environment.DIRECTORY_NOTIFICATIONS,
                Environment.DIRECTORY_RINGTONES, Environment.DIRECTORY_PODCASTS);

        final long downloadsSize = totalValues(details.mediaSize.get(currentUser),
                Environment.DIRECTORY_DOWNLOADS);

        try {
            mAvailablePref.setSize(mStorageManager.getAllocatableBytes(
                    StorageManager.convert(mVolumeInfo.fsUuid)));
        } catch (IOException | IllegalArgumentException e) {
            mAvailablePref.setSize(details.availSize);
        }
        mAppsUsagePref.setSize(details.appsSize.get(currentUser));
        mDcimUsagePref.setSize(dcimSize);
        mMusicUsagePref.setSize(musicSize);
        mDownloadsUsagePref.setSize(downloadsSize);
        mCacheUsagePref.setSize(details.cacheSize);
        mMiscUsagePref.setSize(details.miscSize.get(currentUser));
    }

    private static long totalValues(HashMap<String, Long> map, String... keys) {
        long total = 0;
        if (map != null) {
            for (String key : keys) {
                if (map.containsKey(key)) {
                    total += map.get(key);
                }
            }
        } else {
            Log.w(TAG,
                    "MeasurementDetails mediaSize array does not have key for current user " +
                            ActivityManager.getCurrentUser());
        }
        return total;
    }

    private class MeasurementReceiver implements StorageMeasurement.MeasurementReceiver {

        @Override
        public void onDetailsChanged(StorageMeasurement.MeasurementDetails details) {
            updateDetails(details);
        }
    }

    private class StorageEventListener extends android.os.storage.StorageEventListener {
        @Override
        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
            mVolumeInfo = vol;
            if (isResumed()) {
                if (mVolumeInfo.isMountedReadable()) {
                    refresh();
                } else {
                    navigateBack();
                }
            }
        }
    }

    @Override
    protected int getPageId() {
        return TvSettingsEnums.SYSTEM_STORAGE_INTERNAL_STORAGE;
    }

    @SuppressLint("RestrictedApi")
    private void navigateBack() {
        if (getCallbackFragment() instanceof TwoPanelSettingsFragment) {
            TwoPanelSettingsFragment parentFragment =
                    (TwoPanelSettingsFragment) getCallbackFragment();
            if (parentFragment.isFragmentInTheMainPanel(this)) {
                parentFragment.navigateBack();
            }
        } else {
            getFragmentManager().popBackStack();
        }
    }
}