aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowSettings.java
blob: 00149ac681a2d1c0064e56044f9a85099cf1d977 (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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static android.provider.Settings.Secure.LOCATION_MODE_OFF;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.provider.Settings.SettingNotFoundException;
import android.text.TextUtils;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.Static;

@SuppressWarnings({"UnusedDeclaration"})
@Implements(Settings.class)
public class ShadowSettings {

  @Implements(value = Settings.System.class)
  public static class ShadowSystem {
    private static final ImmutableMap<String, Optional<Object>> DEFAULTS =
        ImmutableMap.<String, Optional<Object>>builder()
            .put(Settings.System.ANIMATOR_DURATION_SCALE, Optional.of(1))
            .build();
    private static final Map<String, Optional<Object>> settings = new ConcurrentHashMap<>(DEFAULTS);

    @Implementation
    protected static boolean putInt(ContentResolver cr, String name, int value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static int getInt(ContentResolver cr, String name, int def) {
      return get(Integer.class, name).orElse(def);
    }

    @Implementation
    protected static int getInt(ContentResolver cr, String name) throws SettingNotFoundException {
      return get(Integer.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    @Implementation
    protected static boolean putString(ContentResolver cr, String name, String value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static String getString(ContentResolver cr, String name) {
      return get(String.class, name).orElse(null);
    }

    @Implementation
    protected static String getStringForUser(ContentResolver cr, String name, int userHandle) {
      return get(String.class, name).orElse(null);
    }

    @Implementation
    protected static boolean putLong(ContentResolver cr, String name, long value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static long getLong(ContentResolver cr, String name, long def) {
      return get(Long.class, name).orElse(def);
    }

    @Implementation
    protected static long getLong(ContentResolver cr, String name) throws SettingNotFoundException {
      return get(Long.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    @Implementation
    protected static boolean putFloat(ContentResolver cr, String name, float value) {
      boolean result = put(cr, name, value);
      if (Settings.System.WINDOW_ANIMATION_SCALE.equals(name)) {
        ShadowValueAnimator.setDurationScale(value);
      }
      return result;
    }

    @Implementation
    protected static float getFloat(ContentResolver cr, String name, float def) {
      return get(Float.class, name).orElse(def);
    }

    @Implementation
    protected static float getFloat(ContentResolver cr, String name)
        throws SettingNotFoundException {
      return get(Float.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    private static boolean put(ContentResolver cr, String name, Object value) {
      if (!Objects.equals(
          settings.put(name, Optional.ofNullable(value)), Optional.ofNullable(value))) {
        if (cr != null) {
          cr.notifyChange(Settings.System.getUriFor(name), null);
        }
      }
      return true;
    }

    private static <T> Optional<T> get(Class<T> type, String name) {
      return settings.getOrDefault(name, Optional.empty()).filter(type::isInstance).map(type::cast);
    }

    @Resetter
    public static void reset() {
      settings.clear();
      settings.putAll(DEFAULTS);
    }
  }

  @Implements(value = Settings.Secure.class)
  public static class ShadowSecure {
    private static final HashMap<String, Optional<Object>> SECURE_DEFAULTS = new HashMap<>();

    // source of truth for initial location state
    static final boolean INITIAL_GPS_PROVIDER_STATE = true;
    static final boolean INITIAL_NETWORK_PROVIDER_STATE = false;

    static {
      if (INITIAL_GPS_PROVIDER_STATE && INITIAL_NETWORK_PROVIDER_STATE) {
        SECURE_DEFAULTS.put(Secure.LOCATION_MODE, Optional.of(Secure.LOCATION_MODE_HIGH_ACCURACY));
        SECURE_DEFAULTS.put(Secure.LOCATION_PROVIDERS_ALLOWED, Optional.of("gps,network"));
      } else if (INITIAL_GPS_PROVIDER_STATE) {
        SECURE_DEFAULTS.put(Secure.LOCATION_MODE, Optional.of(Secure.LOCATION_MODE_SENSORS_ONLY));
        SECURE_DEFAULTS.put(Secure.LOCATION_PROVIDERS_ALLOWED, Optional.of("gps"));
      } else if (INITIAL_NETWORK_PROVIDER_STATE) {
        SECURE_DEFAULTS.put(Secure.LOCATION_MODE, Optional.of(Secure.LOCATION_MODE_BATTERY_SAVING));
        SECURE_DEFAULTS.put(Secure.LOCATION_PROVIDERS_ALLOWED, Optional.of("network"));
      } else {
        SECURE_DEFAULTS.put(Secure.LOCATION_MODE, Optional.of(LOCATION_MODE_OFF));
      }
    }

    private static final Map<String, Optional<Object>> dataMap =
        new ConcurrentHashMap<>(SECURE_DEFAULTS);

    @Implementation(maxSdk = P)
    @SuppressWarnings("robolectric.ShadowReturnTypeMismatch")
    protected static boolean setLocationProviderEnabledForUser(
        ContentResolver cr, String provider, boolean enabled, int uid) {
      return updateEnabledProviders(cr, provider, enabled);
    }

    @Implementation(maxSdk = JELLY_BEAN)
    protected static void setLocationProviderEnabled(
        ContentResolver cr, String provider, boolean enabled) {
      updateEnabledProviders(cr, provider, enabled);
    }

    // only for use locally and by ShadowLocationManager, which requires a tight integration with
    // ShadowSettings due to historical weirdness between LocationManager and Settings.
    static boolean updateEnabledProviders(ContentResolver cr, String provider, boolean enabled) {
      Set<String> providers = new HashSet<>();
      String oldProviders =
          Settings.Secure.getString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
      if (!TextUtils.isEmpty(oldProviders)) {
        providers.addAll(Arrays.asList(oldProviders.split(",")));
      }

      if (enabled == oldProviders.contains(provider)) {
        return true;
      }

      if (enabled) {
        providers.add(provider);
      } else {
        providers.remove(provider);
      }

      String newProviders = TextUtils.join(",", providers.toArray());
      boolean r =
          Settings.Secure.putString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders);

      Intent providersBroadcast = new Intent(LocationManager.PROVIDERS_CHANGED_ACTION);
      if (RuntimeEnvironment.getApiLevel() >= Q) {
        providersBroadcast.putExtra(LocationManager.EXTRA_PROVIDER_NAME, provider);
      }
      if (RuntimeEnvironment.getApiLevel() >= R) {
        providersBroadcast.putExtra(LocationManager.EXTRA_PROVIDER_ENABLED, enabled);
      }
      RuntimeEnvironment.getApplication().sendBroadcast(providersBroadcast);

      return r;
    }

    @Implementation
    protected static boolean putInt(ContentResolver cr, String name, int value) {
      boolean changed = !Objects.equals(dataMap.put(name, Optional.of(value)), Optional.of(value));

      if (Settings.Secure.LOCATION_MODE.equals(name)) {
        if (RuntimeEnvironment.getApiLevel() <= P) {
          // do this after setting location mode but before invoking contentobservers, so that
          // observers for both settings will see the correct values
          boolean gps =
              (value == Settings.Secure.LOCATION_MODE_SENSORS_ONLY
                  || value == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
          boolean network =
              (value == Settings.Secure.LOCATION_MODE_BATTERY_SAVING
                  || value == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
          Settings.Secure.setLocationProviderEnabled(cr, LocationManager.GPS_PROVIDER, gps);
          Settings.Secure.setLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER, network);
        }

        Intent modeBroadcast = new Intent(LocationManager.MODE_CHANGED_ACTION);
        if (RuntimeEnvironment.getApiLevel() >= R) {
          modeBroadcast.putExtra(
              LocationManager.EXTRA_LOCATION_ENABLED, value != LOCATION_MODE_OFF);
        }
        RuntimeEnvironment.getApplication().sendBroadcast(modeBroadcast);
      }

      if (changed && cr != null) {
        cr.notifyChange(Settings.Secure.getUriFor(name), null);
      }

      return true;
    }

    @Implementation(minSdk = LOLLIPOP)
    protected static boolean putIntForUser(
        ContentResolver cr, String name, int value, int userHandle) {
      putInt(cr, name, value);
      return true;
    }

    @Implementation
    protected static int getIntForUser(ContentResolver cr, String name, int def, int userHandle) {
      // ignore userhandle
      return getInt(cr, name, def);
    }

    @Implementation
    protected static int getIntForUser(ContentResolver cr, String name, int userHandle)
        throws SettingNotFoundException {
      // ignore userhandle
      return getInt(cr, name);
    }

    @Implementation
    protected static int getInt(ContentResolver cr, String name) throws SettingNotFoundException {
      if (Settings.Secure.LOCATION_MODE.equals(name)
          && RuntimeEnvironment.getApiLevel() < P) {
        // Map from to underlying location provider storage API to location mode
        return reflector(SettingsSecureReflector.class).getLocationModeForUser(cr, 0);
      }

      return get(Integer.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    @Implementation
    protected static int getInt(ContentResolver cr, String name, int def) {
      if (Settings.Secure.LOCATION_MODE.equals(name)
          && RuntimeEnvironment.getApiLevel() < P) {
        // Map from to underlying location provider storage API to location mode
        return reflector(SettingsSecureReflector.class).getLocationModeForUser(cr, 0);
      }

      return get(Integer.class, name).orElse(def);
    }

    @Implementation
    protected static boolean putString(ContentResolver cr, String name, String value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static String getString(ContentResolver cr, String name) {
      return get(String.class, name).orElse(null);
    }

    @Implementation
    protected static String getStringForUser(ContentResolver cr, String name, int userHandle) {
      return getString(cr, name);
    }

    @Implementation
    protected static boolean putLong(ContentResolver cr, String name, long value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static long getLong(ContentResolver cr, String name, long def) {
      return get(Long.class, name).orElse(def);
    }

    @Implementation
    protected static long getLong(ContentResolver cr, String name) throws SettingNotFoundException {
      return get(Long.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    @Implementation
    protected static boolean putFloat(ContentResolver cr, String name, float value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static float getFloat(ContentResolver cr, String name, float def) {
      return get(Float.class, name).orElse(def);
    }

    @Implementation
    protected static float getFloat(ContentResolver cr, String name)
        throws SettingNotFoundException {
      return get(Float.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    private static boolean put(ContentResolver cr, String name, Object value) {
      if (!Objects.equals(
          dataMap.put(name, Optional.ofNullable(value)), Optional.ofNullable(value))) {
        if (cr != null) {
          cr.notifyChange(Settings.Secure.getUriFor(name), null);
        }
      }
      return true;
    }

    private static <T> Optional<T> get(Class<T> type, String name) {
      return dataMap.getOrDefault(name, Optional.empty()).filter(type::isInstance).map(type::cast);
    }

    @Resetter
    public static void reset() {
      dataMap.clear();
      dataMap.putAll(SECURE_DEFAULTS);
    }
  }

  @Implements(value = Settings.Global.class)
  public static class ShadowGlobal {
    private static final ImmutableMap<String, Optional<Object>> DEFAULTS =
        ImmutableMap.<String, Optional<Object>>builder()
            .put(Settings.Global.ANIMATOR_DURATION_SCALE, Optional.of(1))
            .build();
    private static final Map<String, Optional<Object>> settings = new ConcurrentHashMap<>(DEFAULTS);

    @Implementation
    protected static boolean putInt(ContentResolver cr, String name, int value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static int getInt(ContentResolver cr, String name, int def) {
      return get(Integer.class, name).orElse(def);
    }

    @Implementation
    protected static int getInt(ContentResolver cr, String name) throws SettingNotFoundException {
      return get(Integer.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    @Implementation
    protected static boolean putString(ContentResolver cr, String name, String value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static String getString(ContentResolver cr, String name) {
      return get(String.class, name).orElse(null);
    }

    @Implementation
    protected static String getStringForUser(ContentResolver cr, String name, int userHandle) {
      return getString(cr, name);
    }

    @Implementation
    protected static boolean putLong(ContentResolver cr, String name, long value) {
      return put(cr, name, value);
    }

    @Implementation
    protected static long getLong(ContentResolver cr, String name, long def) {
      return get(Long.class, name).orElse(def);
    }

    @Implementation
    protected static long getLong(ContentResolver cr, String name) throws SettingNotFoundException {
      return get(Long.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    @Implementation
    protected static boolean putFloat(ContentResolver cr, String name, float value) {
      boolean result = put(cr, name, value);
      if (Settings.Global.ANIMATOR_DURATION_SCALE.equals(name)) {
        ShadowValueAnimator.setDurationScale(value);
      }
      return result;
    }

    @Implementation
    protected static float getFloat(ContentResolver cr, String name, float def) {
      return get(Float.class, name).orElse(def);
    }

    @Implementation
    protected static float getFloat(ContentResolver cr, String name)
        throws SettingNotFoundException {
      return get(Float.class, name).orElseThrow(() -> new SettingNotFoundException(name));
    }

    private static boolean put(ContentResolver cr, String name, Object value) {
      if (!Objects.equals(
          settings.put(name, Optional.ofNullable(value)), Optional.ofNullable(value))) {
        if (cr != null) {
          cr.notifyChange(Settings.Global.getUriFor(name), null);
        }
      }
      return true;
    }

    private static <T> Optional<T> get(Class<T> type, String name) {
      return settings.getOrDefault(name, Optional.empty()).filter(type::isInstance).map(type::cast);
    }

    @Resetter
    public static void reset() {
      settings.clear();
      settings.putAll(DEFAULTS);
    }
  }

  /**
   * Sets the value of the {@link Settings.System#AIRPLANE_MODE_ON} setting.
   *
   * @param isAirplaneMode new status for airplane mode
   */
  public static void setAirplaneMode(boolean isAirplaneMode) {
    Settings.Global.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Global.AIRPLANE_MODE_ON,
        isAirplaneMode ? 1 : 0);
    Settings.System.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.System.AIRPLANE_MODE_ON,
        isAirplaneMode ? 1 : 0);
  }

  /**
   * Non-Android accessor that allows the value of the WIFI_ON setting to be set.
   *
   * @param isOn new status for wifi mode
   */
  public static void setWifiOn(boolean isOn) {
    Settings.Global.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Global.WIFI_ON,
        isOn ? 1 : 0);
    Settings.System.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.System.WIFI_ON,
        isOn ? 1 : 0);
  }

  /**
   * Sets the value of the {@link Settings.System#TIME_12_24} setting.
   *
   * @param use24HourTimeFormat new status for the time setting
   */
  public static void set24HourTimeFormat(boolean use24HourTimeFormat) {
    Settings.System.putString(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.System.TIME_12_24,
        use24HourTimeFormat ? "24" : "12");
  }

  private static boolean canDrawOverlays = false;

  /**
   * @return false by default, or the value specified via {@link #setCanDrawOverlays(boolean)}
   */
  @Implementation(minSdk = M)
  protected static boolean canDrawOverlays(Context context) {
    return canDrawOverlays;
  }

  /** Sets the value returned by {@link #canDrawOverlays(Context)}. */
  public static void setCanDrawOverlays(boolean canDrawOverlays) {
    ShadowSettings.canDrawOverlays = canDrawOverlays;
  }

  /**
   * Sets the value of the {@link Settings.Global#ADB_ENABLED} setting or {@link
   * Settings.Secure#ADB_ENABLED} depending on API level.
   *
   * @param adbEnabled new value for whether adb is enabled
   */
  public static void setAdbEnabled(boolean adbEnabled) {
    Settings.Global.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Global.ADB_ENABLED,
        adbEnabled ? 1 : 0);
    // Support all clients by always setting the Secure version of the setting
    Settings.Secure.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Secure.ADB_ENABLED,
        adbEnabled ? 1 : 0);
  }

  /**
   * Sets the value of the {@link Settings.Global#INSTALL_NON_MARKET_APPS} setting or {@link
   * Settings.Secure#INSTALL_NON_MARKET_APPS} depending on API level.
   *
   * @param installNonMarketApps new value for whether non-market apps are allowed to be installed
   */
  public static void setInstallNonMarketApps(boolean installNonMarketApps) {
    // This setting moved from Secure to Global in JELLY_BEAN_MR1 and then moved it back to Global
    // in LOLLIPOP. Support all clients by always setting this field on all versions >=
    // JELLY_BEAN_MR1.
    Settings.Global.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Global.INSTALL_NON_MARKET_APPS,
        installNonMarketApps ? 1 : 0);
    // Always set the Secure version of the setting
    Settings.Secure.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Secure.INSTALL_NON_MARKET_APPS,
        installNonMarketApps ? 1 : 0);
  }

  public static void setLockScreenShowNotifications(boolean lockScreenShowNotifications) {
    Settings.Secure.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
        lockScreenShowNotifications ? 1 : 0);
  }

  public static void setLockScreenAllowPrivateNotifications(
      boolean lockScreenAllowPrivateNotifications) {
    Settings.Secure.putInt(
        RuntimeEnvironment.getApplication().getContentResolver(),
        Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
        lockScreenAllowPrivateNotifications ? 1 : 0);
  }

  /**
   * Shadow for {@link Settings.Config}.
   *
   * <p>This shadow is primarily to support {@link android.provider.DeviceConfig}, which queries
   * {@link Settings.Config}. {@link android.provider.DeviceConfig} is pure Java code so it's not
   * necessary to shadow that directly.
   *
   * <p>The underlying implementation calls into a system content provider. Starting in Android U,
   * the internal logic of Activity is querying DeviceConfig, so to avoid crashes we need to make
   * DeviceConfig a no-op.
   */
  @Implements(value = Settings.Config.class, isInAndroidSdk = false)
  public static class ShadowConfig {
    @Implementation(minSdk = R)
    protected static Map<String, String> getStrings(
        ContentResolver resolver, String namespace, List<String> names) {
      return ImmutableMap.of();
    }
  }

  @Resetter
  public static void reset() {
    canDrawOverlays = false;
  }

  @ForType(Settings.Secure.class)
  interface SettingsSecureReflector {
    @Static
    int getLocationModeForUser(ContentResolver cr, int userId);
  }
}