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 android.support.v4.os;
18
19import android.os.Build;
20import android.os.Environment;
21import android.util.Log;
22
23import java.io.File;
24import java.io.IOException;
25
26/**
27 * Helper for accessing features in {@link Environment} in a backwards compatible fashion.
28 */
29public final class EnvironmentCompat {
30    private static final String TAG = "EnvironmentCompat";
31
32    /**
33     * Unknown storage state, such as when a path isn't backed by known storage
34     * media.
35     *
36     * @see #getStorageState(File)
37     */
38    public static final String MEDIA_UNKNOWN = "unknown";
39
40    /**
41     * Returns the current state of the storage device that provides the given
42     * path.
43     *
44     * @return one of {@link #MEDIA_UNKNOWN}, {@link Environment#MEDIA_REMOVED},
45     *         {@link Environment#MEDIA_UNMOUNTED},
46     *         {@link Environment#MEDIA_CHECKING},
47     *         {@link Environment#MEDIA_NOFS},
48     *         {@link Environment#MEDIA_MOUNTED},
49     *         {@link Environment#MEDIA_MOUNTED_READ_ONLY},
50     *         {@link Environment#MEDIA_SHARED},
51     *         {@link Environment#MEDIA_BAD_REMOVAL}, or
52     *         {@link Environment#MEDIA_UNMOUNTABLE}.
53     */
54    public static String getStorageState(File path) {
55        if (Build.VERSION.SDK_INT >= 19) {
56            return Environment.getStorageState(path);
57        }
58
59        try {
60            final String canonicalPath = path.getCanonicalPath();
61            final String canonicalExternal = Environment.getExternalStorageDirectory()
62                    .getCanonicalPath();
63
64            if (canonicalPath.startsWith(canonicalExternal)) {
65                return Environment.getExternalStorageState();
66            }
67        } catch (IOException e) {
68            Log.w(TAG, "Failed to resolve canonical path: " + e);
69        }
70
71        return MEDIA_UNKNOWN;
72    }
73
74    private EnvironmentCompat() {}
75}
76