aboutsummaryrefslogtreecommitdiff
path: root/library/src/main/java/top/trumeet/redirectstorage/RedirectStorage.java
blob: 8c59ed7249d84cee0d8b9d4b0516e3333bd3dcb6 (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
package top.trumeet.redirectstorage;

import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.lang.reflect.Field;

import top.trumeet.redirectstorage.wrapper.AbstractWrapper;

/**
 * Created by Trumeet on 2017/9/8.
 * 重定向 {@link Environment#getExternalStorageDirectory()}
 * 结果的工具类,以防第三方SDK(尤其阿里系)乱改SD卡和读取用户数据。
 *
 * 需要时使用 {@link RedirectStorage#enable(String)} 启用
 * 不需要时使用 {@link RedirectStorage#disable()} 禁用
 * 如果需要获取没有重定向的真实目录,请使用 {@link RedirectStorage#getRealPath()}
 *
 * 特别感谢 little_cup 提供核心代码,我仅仅做了个简单封装和修改
 * @author Trumeet
 */

@SuppressWarnings("unused")
public class RedirectStorage {
    private static final String TAG = RedirectStorage.class.getSimpleName();

    /**
     * 安装并启用。
     * @param callback 当修改路径时的 Callback
     */
    public static void enable (PathCallback callback) {
        try {
            invokeEnvironmentSdcardMethod(callback);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 禁用,不会卸载,只是禁用它
     */
    public static void disable () {
        try {
            AbstractWrapper wrapper =
                    getInstalledWrapper();
            if (wrapper != null)
                wrapper.setEnable(false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取真实目录,比如需要保存图片等
     * @return 真实存储卡目录
     */
    public static File getRealPath () {
        try {
            AbstractWrapper wrapper = getInstalledWrapper();
            if (wrapper != null)
                return wrapper.getRealExternalStorageDirectory();
            return Environment.getExternalStorageDirectory();
        } catch (Exception e) {
            e.printStackTrace();
            return Environment.getExternalStorageDirectory();
        }
    }

    public static boolean isEnable () {
        try {
            AbstractWrapper wrapper = getInstalledWrapper();
            return wrapper != null && wrapper.isEnable();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取需要反射的 Field
     * @return Field
     */
    private static Field getCurrentUserField ()
            throws NoSuchMethodException, ClassNotFoundException,
            NoSuchFieldException, IllegalAccessException{
        Class envClazz = Class.forName(android.os.Environment.class.getName());
        android.os.Environment.getExternalStorageDirectory();
        Field sCurrentUserField = envClazz.getDeclaredField("sCurrentUser");
        sCurrentUserField.setAccessible(true);
        return sCurrentUserField;
    }

    /**
     * 获取已安装的 Wrapper
     * @return 已安装的 Wrapper
     */
    private static AbstractWrapper getInstalledWrapper ()
    throws NoSuchMethodException, ClassNotFoundException,
            NoSuchFieldException, IllegalAccessException{
        return getInstalledWrapper(getCurrentUserField());
    }

    /**
     * 获取已安装的 Wrapper
     * @param field CurrentUserField
     * @return 已安装的 Wrapper
     */
    private static AbstractWrapper getInstalledWrapper (Field field)
            throws IllegalAccessException {
        Environment.UserEnvironment o = (Environment.UserEnvironment) field.get(null);
        return o == null || !(o instanceof AbstractWrapper)
                ? null : (AbstractWrapper) o;
    }

    /**
     * 判断是否已安装
     * @return 是否安装
     */
    public static boolean isInstall () {
        try {
            return getInstalledWrapper() != null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void invokeEnvironmentSdcardMethod(PathCallback callback)
            throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        Field sCurrentUserField = getCurrentUserField();
        AbstractWrapper wrapper = getInstalledWrapper(sCurrentUserField);
        if (wrapper != null) {
            // Update current wrapper
            wrapper.setCallback(callback);
            wrapper.setEnable(true);
        } else {
            // Install new wrapper
            Environment.UserEnvironment o = (Environment.UserEnvironment) sCurrentUserField
                    .get(null);
            int user = 0;
            try {
                Field mUserIdField = o.getClass().getDeclaredField("mUserId");
                mUserIdField.setAccessible(true);
                user = mUserIdField.getInt(o);
            } catch (Exception e) {
                e.printStackTrace();
            }
            AbstractWrapper abstractWrapper = AbstractWrapper.getWrapper(o,
                    callback, user);
            if (abstractWrapper == null) {
                Log.e(TAG, "Can not create wrapper, it looks like not support your ROM: " +
                        Build.VERSION.SDK_INT);
                return;
            }
            sCurrentUserField.set(null, abstractWrapper);
        }
    }
}