0
# Runtime Environment Control
1
2
Runtime environment management providing access to the Application context, device configuration control, threading management, and system property manipulation in the simulated Android environment.
3
4
## Capabilities
5
6
### Application Management
7
8
Access and control the Application instance under test with support for lazy loading and custom Application classes.
9
10
```java { .api }
11
public class RuntimeEnvironment {
12
/**
13
* Get reference to the Application under test.
14
* May be created at setup time or lazily at call time based on LazyApplication setting.
15
* Must be called on main/test thread if lazy loading is enabled.
16
*
17
* Alternative: androidx.test.core.app.ApplicationProvider.getApplicationContext()
18
* for cross-platform tests that work on JVM and real devices.
19
*/
20
public static Application getApplication();
21
22
/** Internal use only - sets Application supplier for lazy loading */
23
public static void setApplicationSupplier(Supplier<Application> applicationSupplier);
24
25
/** Returns the configured Application class */
26
public static Class<? extends Application> getConfiguredApplicationClass();
27
28
/** Sets the Application class to be used */
29
public static void setConfiguredApplicationClass(Class<? extends Application> clazz);
30
}
31
```
32
33
**Static Fields (Deprecated):**
34
35
```java { .api }
36
public class RuntimeEnvironment {
37
/**
38
* @deprecated Use getApplication() instead
39
* Incompatible with LazyApplication and may be removed
40
*/
41
@Deprecated
42
public static Context systemContext;
43
44
/**
45
* @deprecated Use getApplication() instead
46
* Accessing directly is incompatible with LazyApplication
47
*/
48
@Deprecated
49
public static volatile Application application;
50
}
51
```
52
53
**Usage Example:**
54
55
```java
56
// Get application instance
57
Application app = RuntimeEnvironment.getApplication();
58
assertThat(app).isNotNull();
59
60
// Check application type
61
if (RuntimeEnvironment.getConfiguredApplicationClass() == MyCustomApplication.class) {
62
MyCustomApplication customApp = (MyCustomApplication) app;
63
customApp.doCustomSetup();
64
}
65
```
66
67
### Device Configuration Management
68
69
Control device configuration including screen properties, locale settings, and resource qualifiers.
70
71
```java { .api }
72
public class RuntimeEnvironment {
73
/**
74
* Returns qualifier string describing current Configuration of system resources.
75
* Format follows Android resource qualifier rules:
76
* https://developer.android.com/guide/topics/resources/providing-resources.html#QualifierRules
77
*/
78
public static String getQualifiers();
79
80
/**
81
* Returns qualifier string for given configuration and display metrics.
82
*/
83
public static String getQualifiers(Configuration configuration, DisplayMetrics displayMetrics);
84
85
/**
86
* Overrides current device configuration.
87
* If qualifiers start with '+', overlays on prior configuration additively.
88
* Otherwise uses default values for unspecified properties.
89
*
90
* See: http://robolectric.org/device-configuration/
91
*/
92
public static void setQualifiers(String newQualifiers);
93
94
/** Sets font scale for the device */
95
public static void setFontScale(float fontScale);
96
97
/** Returns current font scale */
98
public static float getFontScale();
99
}
100
```
101
102
**Usage Examples:**
103
104
```java
105
// Check current configuration
106
String qualifiers = RuntimeEnvironment.getQualifiers();
107
assertThat(qualifiers).contains("mdpi");
108
109
// Change to tablet landscape configuration
110
RuntimeEnvironment.setQualifiers("xlarge-land-mdpi");
111
112
// Overlay additional qualifiers (additive)
113
RuntimeEnvironment.setQualifiers("+fr-rFR"); // Add French locale
114
115
// Test font scaling
116
RuntimeEnvironment.setFontScale(1.5f);
117
assertThat(RuntimeEnvironment.getFontScale()).isEqualTo(1.5f);
118
119
// Verify resources update
120
Resources resources = RuntimeEnvironment.getApplication().getResources();
121
Configuration config = resources.getConfiguration();
122
assertThat(config.fontScale).isEqualTo(1.5f);
123
```
124
125
### Threading Management (Legacy Mode Only)
126
127
Thread management APIs for LEGACY looper mode. Not supported in PAUSED or INSTRUMENTATION_TEST modes.
128
129
```java { .api }
130
public class RuntimeEnvironment {
131
/**
132
* @deprecated Not supported in realistic looper mode
133
* Tests if given thread is currently set as main thread.
134
*/
135
@Deprecated
136
public static boolean isMainThread(Thread thread);
137
138
/**
139
* @deprecated Not supported in realistic looper mode
140
* Tests if current thread is main thread.
141
*/
142
@Deprecated
143
public static boolean isMainThread();
144
145
/**
146
* @deprecated Not supported in realistic looper mode
147
* Retrieves main thread. Defaults to thread that initializes RuntimeEnvironment.
148
*/
149
@Deprecated
150
public static Thread getMainThread();
151
152
/**
153
* @deprecated Not supported in realistic looper mode
154
* Sets the main thread.
155
*/
156
@Deprecated
157
public static void setMainThread(Thread newMainThread);
158
}
159
```
160
161
### Activity Thread Management
162
163
Access to the ActivityThread for advanced runtime manipulation.
164
165
```java { .api }
166
public class RuntimeEnvironment {
167
/** Returns the activity thread object */
168
public static Object getActivityThread();
169
170
/** Sets the activity thread object */
171
public static void setActivityThread(Object newActivityThread);
172
}
173
```
174
175
**Usage Example:**
176
177
```java
178
// Access activity thread for advanced operations
179
Object activityThread = RuntimeEnvironment.getActivityThread();
180
// Cast and use as needed for specific test scenarios
181
```
182
183
### API Level Information
184
185
Access to the current Android API level being simulated.
186
187
```java { .api }
188
public class RuntimeEnvironment {
189
/** Returns the Android API level being simulated */
190
public static int getApiLevel();
191
}
192
```
193
194
**Usage Example:**
195
196
```java
197
// Check API level for conditional test logic
198
int apiLevel = RuntimeEnvironment.getApiLevel();
199
if (apiLevel >= Build.VERSION_CODES.Q) {
200
// Test API 29+ specific functionality
201
}
202
203
// Assert expected API level
204
assertThat(RuntimeEnvironment.getApiLevel()).isEqualTo(28);
205
```
206
207
### Scheduler Management (Legacy Mode Only)
208
209
Master scheduler management for LEGACY looper mode. Deprecated in favor of PAUSED looper mode.
210
211
```java { .api }
212
public class RuntimeEnvironment {
213
/**
214
* @deprecated Use PAUSED Looper mode instead
215
* Retrieves current master scheduler used by main Looper and optionally all Loopers.
216
*/
217
@Deprecated
218
public static Scheduler getMasterScheduler();
219
220
/**
221
* @deprecated Use PAUSED Looper mode instead
222
* Sets current master scheduler. Primarily for Robolectric core setup.
223
* Changing during test will have unpredictable results.
224
*/
225
@Deprecated
226
public static void setMasterScheduler(Scheduler masterScheduler);
227
}
228
```
229
230
### File System Management
231
232
Temporary directory management for test file operations.
233
234
```java { .api }
235
public class RuntimeEnvironment {
236
/** Sets the temporary directory for test operations */
237
public static void setTempDirectory(TempDirectory tempDirectory);
238
239
/** Returns the current temporary directory */
240
public static TempDirectory getTempDirectory();
241
}
242
```
243
244
**Usage Example:**
245
246
```java
247
// Get temp directory for test files
248
TempDirectory tempDir = RuntimeEnvironment.getTempDirectory();
249
File testFile = tempDir.create("test-data.txt");
250
251
// Write test data
252
Files.write(testFile.toPath(), "test data".getBytes());
253
```
254
255
### Android Framework JAR Management
256
257
Management of the Android framework JAR path for advanced scenarios.
258
259
```java { .api }
260
public class RuntimeEnvironment {
261
/** Sets the path to Android framework JAR */
262
public static void setAndroidFrameworkJarPath(Path localArtifactPath);
263
264
/** Returns the path to Android framework JAR */
265
public static Path getAndroidFrameworkJarPath();
266
}
267
```
268
269
### System Resources Management
270
271
Internal system resource management for compile-time resources.
272
273
```java { .api }
274
public class RuntimeEnvironment {
275
/** Internal use only - sets compile-time system resources supplier */
276
public static void setCompileTimeSystemResources(Supplier<Path> compileTimeSystemResourcesSupplier);
277
278
/** @deprecated Obsolete, do not use */
279
@Deprecated
280
public static Path getCompileTimeSystemResourcesPath();
281
}
282
```
283
284
## Device Configuration Examples
285
286
### Screen Size and Density
287
288
```java
289
// Phone configurations
290
RuntimeEnvironment.setQualifiers("normal-mdpi"); // Standard phone
291
RuntimeEnvironment.setQualifiers("normal-hdpi"); // High-DPI phone
292
RuntimeEnvironment.setQualifiers("normal-xhdpi"); // Extra high-DPI phone
293
RuntimeEnvironment.setQualifiers("normal-xxhdpi"); // XX high-DPI phone
294
295
// Tablet configurations
296
RuntimeEnvironment.setQualifiers("large-mdpi"); // 7" tablet
297
RuntimeEnvironment.setQualifiers("xlarge-mdpi"); // 10" tablet
298
```
299
300
### Orientation
301
302
```java
303
// Portrait (default)
304
RuntimeEnvironment.setQualifiers("normal-port-mdpi");
305
306
// Landscape
307
RuntimeEnvironment.setQualifiers("normal-land-mdpi");
308
```
309
310
### Locale and Language
311
312
```java
313
// English (default)
314
RuntimeEnvironment.setQualifiers("en-rUS");
315
316
// Other languages
317
RuntimeEnvironment.setQualifiers("fr-rFR"); // French
318
RuntimeEnvironment.setQualifiers("es-rES"); // Spanish
319
RuntimeEnvironment.setQualifiers("ja-rJP"); // Japanese
320
321
// Add language to existing configuration
322
RuntimeEnvironment.setQualifiers("+es-rES");
323
```
324
325
### Night Mode
326
327
```java
328
// Light mode (default)
329
RuntimeEnvironment.setQualifiers("notnight");
330
331
// Dark mode
332
RuntimeEnvironment.setQualifiers("night");
333
334
// Add to existing configuration
335
RuntimeEnvironment.setQualifiers("+night");
336
```
337
338
### Complex Configurations
339
340
```java
341
// Large tablet in landscape with high DPI and French locale
342
RuntimeEnvironment.setQualifiers("fr-rFR-xlarge-land-xhdpi");
343
344
// Phone in dark mode with extra large font
345
RuntimeEnvironment.setQualifiers("normal-port-night-mdpi");
346
RuntimeEnvironment.setFontScale(1.3f);
347
```
348
349
## Migration Notes
350
351
For modern Robolectric usage:
352
353
1. **Use PAUSED Looper Mode**: Avoid deprecated threading and scheduler APIs
354
2. **Use ApplicationProvider**: Prefer `androidx.test.core.app.ApplicationProvider.getApplicationContext()` for cross-platform compatibility
355
3. **Avoid Direct Field Access**: Use `getApplication()` instead of accessing `application` field directly
356
4. **Configuration via Annotations**: Use `@Config` annotations instead of programmatic configuration where possible