summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineManager.java
blob: 7b41184a5a0469d714d7f65d4bddbaf91585713c (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
package com.mapbox.mapboxsdk.offline;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;

import com.mapbox.mapboxsdk.MapboxAccountManager;
import com.mapbox.mapboxsdk.constants.MapboxConstants;

import java.io.File;

/**
 * The offline manager is the main entry point for offline-related functionality.
 * It'll help you list and create offline regions.
 */
public class OfflineManager {

    private final static String LOG_TAG = "OfflineManager";

    //
    // Static methods
    //

    static {
        System.loadLibrary("mapbox-gl");
    }

    // Default database name
    private final static String DATABASE_NAME = "mbgl-offline.db";

    /*
     * The maximumCacheSize parameter is a limit applied to non-offline resources only,
     * i.e. resources added to the database for the "ambient use" caching functionality.
     * There is no size limit for offline resources.
     */
    private final static long DEFAULT_MAX_CACHE_SIZE = 50 * 1024 * 1024;

    // Holds the pointer to JNI DefaultFileSource
    private long mDefaultFileSourcePtr = 0;

    // Makes sure callbacks come back to the main thread
    private Handler handler;

    // This object is implemented as a singleton
    private static OfflineManager instance;

    /**
     * This callback receives an asynchronous response containing a list of all
     * {@link OfflineRegion} in the database, or an error message otherwise.
     */
    public interface ListOfflineRegionsCallback {
        /**
         * Receives the list of offline regions
         *
         * @param offlineRegions
         */
        void onList(OfflineRegion[] offlineRegions);

        /**
         * Receives the error message
         *
         * @param error
         */
        void onError(String error);
    }

    /**
     * This callback receives an asynchronous response containing the newly created
     * {@link OfflineRegion} in the database, or an error message otherwise.
     */
    public interface CreateOfflineRegionCallback {
        /**
         * Receives the newly created offline region
         *
         * @param offlineRegion
         */
        void onCreate(OfflineRegion offlineRegion);

        /**
         * Receives the error message
         *
         * @param error
         */
        void onError(String error);
    }

    /*
     * Constructors
     */

    private OfflineManager(Context context) {
        // Get a pointer to the DefaultFileSource instance
        String assetRoot = getDatabasePath(context);
        String cachePath = assetRoot + File.separator + DATABASE_NAME;
        mDefaultFileSourcePtr = createDefaultFileSource(cachePath, assetRoot, DEFAULT_MAX_CACHE_SIZE);

        if (MapboxAccountManager.getInstance() != null) {
            setAccessToken(mDefaultFileSourcePtr, MapboxAccountManager.getInstance().getAccessToken());
        }

        // Delete any existing previous ambient cache database
        deleteAmbientDatabase(context);
    }

    public static String getDatabasePath(Context context) {
        // Default value
        boolean setStorageExternal = MapboxConstants.DEFAULT_SET_STORAGE_EXTERNAL;

        try {
            // Try getting a custom value from the app Manifest
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            setStorageExternal = appInfo.metaData.getBoolean(
                    MapboxConstants.KEY_META_DATA_SET_STORAGE_EXTERNAL,
                    MapboxConstants.DEFAULT_SET_STORAGE_EXTERNAL);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(LOG_TAG, "Failed to read the package metadata: " + e.getMessage());
        } catch (Exception e) {
            Log.e(LOG_TAG, "Failed to read the storage key: " + e.getMessage());
        }

        String databasePath = null;
        if (setStorageExternal && isExternalStorageReadable()) {
            try {
                // Try getting the external storage path
                databasePath = context.getExternalFilesDir(null).getAbsolutePath();
            } catch (NullPointerException e) {
                Log.e(LOG_TAG, "Failed to obtain the external storage path: " + e.getMessage());
            }
        }

        if (databasePath == null) {
            // Default to internal storage
            databasePath = context.getFilesDir().getAbsolutePath();
        }

        return databasePath;
    }

    /**
     * Checks if external storage is available to at least read. In order for this to work, make
     * sure you include <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     * (or WRITE_EXTERNAL_STORAGE) for API level < 18 in your app Manifest.
     * <p>
     * Code from https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
     * </p>
     */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }

        Log.w(LOG_TAG, "External storage was requested but it isn't readable. For API level < 18"
                + " make sure you've requested READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE"
                + " permissions in your app Manifest (defaulting to internal storage).");

        return false;
    }

    private void deleteAmbientDatabase(final Context context) {
        // Delete the file in a separate thread to avoid affecting the UI
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String path = context.getCacheDir().getAbsolutePath() + File.separator + "mbgl-cache.db";
                    File file = new File(path);
                    if (file.exists()) {
                        file.delete();
                        Log.d(LOG_TAG, "Old ambient cache database deleted to save space: " + path);
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Failed to delete old ambient cache database: " + e.getMessage());
                }
            }
        }).start();
    }

    public static synchronized OfflineManager getInstance(Context context) {
        if (instance == null) {
            instance = new OfflineManager(context);
        }

        return instance;
    }

    /**
     * Access token getter/setter
     *
     * @param accessToken
     * @deprecated As of release 4.1.0, replaced by {@link MapboxAccountManager#start(Context, String)} ()}
     */
    @Deprecated
    public void setAccessToken(String accessToken) {
        setAccessToken(mDefaultFileSourcePtr, accessToken);
    }

    /**
     * Get Access Token
     *
     * @return Access Token
     * @deprecated As of release 4.1.0, replaced by {@link MapboxAccountManager#getAccessToken()}
     */
    @Deprecated
    public String getAccessToken() {
        return getAccessToken(mDefaultFileSourcePtr);
    }

    private Handler getHandler() {
        if (handler == null) {
            handler = new Handler(Looper.getMainLooper());
        }

        return handler;
    }

    /**
     * Retrieve all regions in the offline database.
     * <p>
     * The query will be executed asynchronously and the results passed to the given
     * callback on the main thread.
     * </p>
     */
    public void listOfflineRegions(@NonNull final ListOfflineRegionsCallback callback) {
        listOfflineRegions(mDefaultFileSourcePtr, new ListOfflineRegionsCallback() {
            @Override
            public void onList(final OfflineRegion[] offlineRegions) {
                getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onList(offlineRegions);
                    }
                });
            }

            @Override
            public void onError(final String error) {
                getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(error);
                    }
                });
            }
        });
    }

    /**
     * Create an offline region in the database.
     * <p>
     * When the initial database queries have completed, the provided callback will be
     * executed on the main thread.
     * </p>
     * <p>
     * Note that the resulting region will be in an inactive download state; to begin
     * downloading resources, call `OfflineRegion.setDownloadState(DownloadState.STATE_ACTIVE)`,
     * optionally registering an `OfflineRegionObserver` beforehand.
     * </p>
     */
    public void createOfflineRegion(
            @NonNull OfflineRegionDefinition definition,
            @NonNull byte[] metadata,
            @NonNull final CreateOfflineRegionCallback callback) {

        createOfflineRegion(mDefaultFileSourcePtr, definition, metadata, new CreateOfflineRegionCallback() {
            @Override
            public void onCreate(final OfflineRegion offlineRegion) {
                getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCreate(offlineRegion);
                    }
                });
            }

            @Override
            public void onError(final String error) {
                getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(error);
                    }
                });
            }
        });
    }

    /*
    * Changing or bypassing this limit without permission from Mapbox is prohibited
    * by the Mapbox Terms of Service.
    */
    public void setOfflineMapboxTileCountLimit(long limit) {
        setOfflineMapboxTileCountLimit(mDefaultFileSourcePtr, limit);
    }


    /*
     * Native methods
     */

    private native long createDefaultFileSource(
            String cachePath, String assetRoot, long maximumCacheSize);

    private native void setAccessToken(long defaultFileSourcePtr, String accessToken);

    private native String getAccessToken(long defaultFileSourcePtr);

    private native void listOfflineRegions(
            long defaultFileSourcePtr, ListOfflineRegionsCallback callback);

    private native void createOfflineRegion(
            long defaultFileSourcePtr, OfflineRegionDefinition definition,
            byte[] metadata, CreateOfflineRegionCallback callback);

    private native void setOfflineMapboxTileCountLimit(
            long defaultFileSourcePtr, long limit);

}