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