Repository navigation
Expand file tree
/
Copy pathMainActivity.java
More file actions
637 lines (585 loc) · 30 KB
/
Copy pathMainActivity.java
File metadata and controls
637 lines (585 loc) · 30 KB
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/**
* @author Shakib
* @since 20/07/26
*/
package io.devconsole.sample.viewsjava;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.WindowInsets;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import io.devconsole.DevConsole;
import io.devconsole.api.BindingMode;
import io.devconsole.api.BrowserBinding;
import io.devconsole.api.BrowserConfig;
import io.devconsole.api.DevConsoleConfig;
import io.devconsole.api.DevConsoleState;
import io.devconsole.api.EditingCapabilities;
import io.devconsole.api.OpenTriggers;
import io.devconsole.api.ScreenshotResult;
import io.devconsole.api.ShakeIntensity;
import io.devconsole.api.StartRequest;
import io.devconsole.api.StartResult;
import io.devconsole.api.StopReason;
import io.devconsole.mocks.MockAction;
import io.devconsole.mocks.MockRule;
import io.devconsole.mocks.MockScope;
import io.devconsole.network.okhttp.DevConsoleOkHttp;
import io.devconsole.push.PushEvent;
import io.devconsole.push.PushInput;
import io.devconsole.push.PushLifecycle;
import io.devconsole.push.firebase.FirebaseRemoteMessageAdapter;
import io.devconsole.socket.okhttp.DevConsoleOkHttpWebSocketListener;
import io.devconsole.socket.okhttp.DevConsoleRecordingWebSocket;
import io.devconsole.state.FeatureFlag;
import io.devconsole.state.StateProvider;
import io.devconsole.state.StateSnapshot;
import io.devconsole.state.StateValue;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlinx.coroutines.CoroutineScope;
import kotlinx.coroutines.CoroutineScopeKt;
import kotlinx.coroutines.Dispatchers;
import kotlinx.coroutines.Job;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
/**
* Java + XML launcher sample exercising every SDK capability: network + socket capture, mocks
* (with enable/disable), push recording (manual and Firebase-shaped), a feature flag, and a state
* provider. The SDK itself never auto-registers this activity.
*
* <p>Capability-flag posture (see compose-app's {@code MainActivity} for the full three-sample
* matrix): this sample sits between compose-app's fully-unlocked and foundation-app's fully-locked
* {@link EditingCapabilities} -- {@code mocks} and {@code captureRules} are editable, but
* preferences/database/files stay read-only, matching a host that trusts in-session traffic
* shaping but not remote edits to on-device storage.
*
* <p>Screenshot capture stays at its SDK-wide default here too -- no {@code withScreenshotPolicy}
* override, so {@code btnCaptureScreenshot} always resolves {@link ScreenshotResult.Disabled}. A
* screenshot is a different, orthogonal axis from the mocks/captureRules edits this sample already
* unlocks: trusting the dashboard to reshape in-session traffic is not the same trust decision as
* handing it the most sensitive, unredactable artifact the SDK can emit. compose-app is the one
* sample that opts in; this one demonstrates the Java-friendly
* {@link io.devconsole.DevConsole#captureScreenshotAsync} callback API reaching the same refusal
* foundation-app reaches through the Kotlin suspend function.
*
* <p>{@code btnTriggerCrash} and {@code btnTriggerAnr} sit in a HAZARD ZONE card set apart from the
* ordinary demo buttons, since a tap kills the process (crash) or freezes the UI for several
* seconds (ANR). {@link io.devconsole.api.CrashPolicy} is left at its default 5s
* {@code anrThresholdMs} here -- compose-app is the sample that demonstrates shortening it for a
* faster demo -- so the ANR button just needs to block comfortably past 5s.
*/
public final class MainActivity extends Activity {
private static final String SHOW_DIAGNOSTICS_FLAG = "views_java_sample.show_diagnostics";
private static final String MOCK_RULE_ID = "java-sample-orders";
private static final int REQUEST_LAN_PERMISSION = 1001;
private static final AtomicInteger REQUEST_COUNT = new AtomicInteger();
// Default CrashPolicy.anrThresholdMs is 5s; comfortably clear it rather than shortening the
// policy here -- compose-app is the sample that demonstrates a shortened threshold.
private static final long ANR_BLOCK_MS = 6_000L;
private boolean mockRuleEnabled = true;
private CoroutineScope panelScope;
private OkHttpClient client;
private SampleLocationPings sampleLocationPings;
private OkHttpClient socketClient;
private TextView lastResponse;
private DevConsolePanelController panel;
private Job panelJob;
private final ExecutorService ioExecutor = Executors.newSingleThreadExecutor();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final Runnable restoreRunningSession = new Runnable() {
@Override public void run() {
DevConsoleState state = DevConsole.state().getValue();
if (state == DevConsoleState.Running.INSTANCE) {
// Mock rules are SESSION-scoped and dropped on every server restart, so the rule is
// (re)installed here -- the Running-state observer -- rather than once in onCreate,
// which would silently stop mocking after a restart.
installMockRule();
panel.setEndpoint(DevConsole.endpoint());
if (DevConsole.accessInfo() != null) {
showConnectUrl(DevConsole.accessInfo().getConnectUrl());
}
// Poll while running so either access mode updates the displayed URL after a
// restart; SESSION_CODE also re-issues the code after a browser consumes it.
mainHandler.postDelayed(this, CONNECT_URL_POLL_MS);
} else if (state == DevConsoleState.Starting.INSTANCE) {
mainHandler.postDelayed(this, 50L);
}
}
};
private static final long CONNECT_URL_POLL_MS = 3_000L;
private String connectUrl;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DevConsole.initialize(getApplication(), buildConfig());
setContentView(R.layout.activity_main);
applySystemBarInsets(findViewById(R.id.root));
// DevConsoleOkHttp.install() is the Java-friendly one-call installer: it wires the event
// listener factory and interceptor together so the Network inspector's timing bar
// (DNS/connect/TLS/send/wait/receive) is populated -- see its kdoc for why the equivalent
// manual three-step form is easy to get wrong from Java. Mock rules come with it, from the
// engine DevConsole published at initialize, so no DevConsoleMockInterceptor line is needed.
client = DevConsoleOkHttp.install(new OkHttpClient.Builder(), DevConsole.networkRecorder())
.build();
sampleLocationPings = new SampleLocationPings(client);
socketClient = new OkHttpClient();
// Mock rules are SESSION-scoped and dropped on every server restart -- restoreRunningSession
// (re)installs it on each Running transition instead, so a one-shot call here isn't needed.
seedSampleData(getApplicationContext());
lastResponse = findViewById(R.id.tvLastResponse);
lastResponse.setOnClickListener(view -> copyConnectUrlIfAvailable());
panelScope = CoroutineScopeKt.CoroutineScope(Dispatchers.getMain());
FrameLayout panelContainer = findViewById(R.id.dev_console_panel_container);
panel = DevConsolePanelControllerFactory.create(panelContainer);
panelJob = panel.bind(
DevConsole.state(),
panelScope,
() -> { startServer(); return Unit.INSTANCE; },
() -> { stopServer(); return Unit.INSTANCE; }
);
mainHandler.post(restoreRunningSession);
findViewById(R.id.btnSendNetworkRequest).setOnClickListener(view ->
sendRequest("https://jsonplaceholder.typicode.com/todos/1", "Network response"));
findViewById(R.id.btnSendMockedRequest).setOnClickListener(view ->
sendRequest("https://example.test/orders", "Mocked response"));
findViewById(R.id.btnOpenSocket).setOnClickListener(view -> openSampleWebSocket());
findViewById(R.id.btnSimulatePush).setOnClickListener(view -> simulatePush());
findViewById(R.id.btnSimulateFirebasePush).setOnClickListener(view -> simulateFirebasePush());
findViewById(R.id.btnReadFeatureFlag).setOnClickListener(view -> readFeatureFlag());
findViewById(R.id.btnToggleMockRule).setOnClickListener(view -> toggleMockRule());
findViewById(R.id.btnSendLocationPing).setOnClickListener(view ->
ioExecutor.execute(() -> postResult(sampleLocationPings.sendNextPing())));
findViewById(R.id.btnCaptureScreenshot).setOnClickListener(view -> captureScreenshot());
findViewById(R.id.btnTriggerCrash).setOnClickListener(view -> triggerCrash());
findViewById(R.id.btnTriggerAnr).setOnClickListener(view -> triggerAnr());
}
private static void applySystemBarInsets(View view) {
view.setOnApplyWindowInsetsListener((target, insets) -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
android.graphics.Insets bars = insets.getInsets(WindowInsets.Type.systemBars());
target.setPadding(bars.left, bars.top, bars.right, bars.bottom);
} else {
target.setPadding(
insets.getSystemWindowInsetLeft(),
insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(),
insets.getSystemWindowInsetBottom()
);
}
return insets;
});
view.requestApplyInsets();
}
private DevConsoleConfig buildConfig() {
StateProvider stateProvider = new StateProvider() {
@Override public String getId() {
return "views-java-sample";
}
@Override public StateSnapshot snapshot() {
Map<String, StateValue> values = new HashMap<>();
values.put("requestsSent", new StateValue.NumberValue(REQUEST_COUNT.get()));
return new StateSnapshot(values);
}
};
FeatureFlag featureFlag = FeatureFlag.ofBoolean(
SHOW_DIAGNOSTICS_FLAG,
false,
"Shows extra diagnostics in the sample UI"
);
// mocks + captureRules editable, preferences/database/files read-only -- see the class-level
// comment for how this sits between compose-app's and foundation-app's postures.
// Open triggers take the same middle ground below: shake-to-open only (LIGHT), no floating button.
EditingCapabilities editingCapabilities = EditingCapabilities.builder()
.mocks(true)
.captureRules(true)
// The in-app Composer screen runs through this flag, not composerEnabled below --
// without it the panel reports Disabled("requestExecution") even though the
// browser dashboard would happily serve /api/v1/composer/*.
.requestExecution(true)
.build();
// Builder rather than positional construction: Kotlin default arguments do not reach Java,
// so every added field would otherwise break this call site.
return DevConsoleConfig.builder()
.addStateProvider(stateProvider)
.addFeatureFlag(featureFlag)
.editingCapabilities(editingCapabilities)
.locationPingTracking(SampleLocationPings.tracking())
// Composer is off by default: it makes the device issue arbitrary outbound
// requests, i.e. turns it into a proxy onto its network. Every /api/v1/composer
// route (GETs included) answers 404 {"code":"COMPOSER_DISABLED"} until this is on.
// The allowlist is NOT optional in practice -- empty denies every destination, so
// execute would just fail next with COMPOSER_HOST_REJECTED. Exact hostnames, no
// wildcards; matching what this sample's own buttons talk to.
.composerEnabled(true)
.composerHostsEditable(true)
.composerAllowedHosts(new HashSet<>(Arrays.asList(
"jsonplaceholder.typicode.com", "example.test")))
// The floating button is not a Compose feature: OpenTriggerController attaches a
// plain ImageView to the Activity's decorView, so an XML/Views host gets the same
// draggable, translucent button a Compose host does. Enabled here to show that.
.openTriggers(OpenTriggers.builder()
.shakeToOpen(true)
.shakeIntensity(ShakeIntensity.LIGHT)
.floatingButton(true)
.build())
// Matches the BindingMode.LAN passed to startBrowserAsync below: the in-app
// inspector's More screen issues no StartRequest of its own, so without this it
// would bind loopback while this activity's own Start button binds LAN.
.browserConfig(new BrowserConfig(BrowserBinding.LAN, new kotlin.ranges.IntRange(8080, 8099),
BrowserConfig.DEFAULT_SESSION_CODE_TTL_MS))
.build();
}
@Override public void onDestroy() {
mainHandler.removeCallbacks(restoreRunningSession);
if (panelJob != null) panelJob.cancel(null);
ioExecutor.shutdownNow();
if (client != null) {
client.dispatcher().executorService().shutdown();
client.connectionPool().evictAll();
}
if (socketClient != null) {
socketClient.dispatcher().executorService().shutdown();
socketClient.connectionPool().evictAll();
}
if (isFinishing() && !isChangingConfigurations()) {
DevConsole.stopAsync(StopReason.ApplicationTerminated.INSTANCE);
}
super.onDestroy();
}
private void stopServer() {
DevConsole.stopAsync(StopReason.UserRequested.INSTANCE, ignored ->
runOnUiThread(() -> {
panel.setEndpoint(null);
showResult("Server stopped");
})
);
}
private void startServer() {
// LAN so the connect URL carries the device's own address and a browser on the same network
// can reach it without `adb forward`. That exposure is real: the dashboard speaks plaintext
// HTTP, so anyone who can see these packets reads every captured header, token and body.
// Swap to LOOPBACK below on any network you do not control. See docs/THREAT_MODEL.md.
StartRequest startRequest = new StartRequest(BindingMode.LAN, new kotlin.ranges.IntRange(8080, 8099));
// StartRequest startRequest = new StartRequest(BindingMode.LOOPBACK, new kotlin.ranges.IntRange(8080, 8099));
DevConsole.startBrowserAsync(startRequest, result -> runOnUiThread(() -> {
if (result instanceof StartResult.Started) {
StartResult.Started started = (StartResult.Started) result;
// Covers the interactive Stop -> Start flow; restoreRunningSession covers the
// activity-recreated-while-already-running case at onCreate.
installMockRule();
panel.setEndpoint(started.getEndpoint());
showConnectUrl(started.getAccess().getConnectUrl());
} else if (result instanceof StartResult.PermissionRequired) {
String permission = ((StartResult.PermissionRequired) result).getPermission();
showResult("Requesting local network permission...");
requestPermissions(new String[] {permission}, REQUEST_LAN_PERMISSION);
} else {
showResult("Could not start DevConsole: " + result.getClass().getSimpleName());
}
}));
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_LAN_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startServer();
} else {
showResult("Local network permission was denied");
}
}
}
private void copyConnectUrlIfAvailable() {
if (connectUrl == null) return;
ClipboardManager clipboard = getSystemService(ClipboardManager.class);
clipboard.setPrimaryClip(ClipData.newPlainText("DevConsole dashboard URL", connectUrl));
Toast.makeText(this, connectUrl.contains("#code=") ? "Session code copied -- keep it private" : "Dashboard URL copied", Toast.LENGTH_SHORT).show();
}
private void sendRequest(String url, String successLabel) {
REQUEST_COUNT.incrementAndGet();
ioExecutor.execute(() -> {
String result;
try (Response response = client.newCall(new Request.Builder().url(url).build()).execute()) {
result = successLabel + ": " + response.code();
} catch (Exception error) {
result = "Request failed: " + error.getMessage();
}
postResult(result);
});
}
private void openSampleWebSocket() {
Request request = new Request.Builder().url("wss://ws.postman-echo.com/raw").build();
Function1<WebSocket, String> connectionIdProvider =
socket -> socket.request().url() + "-" + System.identityHashCode(socket);
WebSocketListener listener = new DevConsoleOkHttpWebSocketListener(
DevConsole.socketRecorder(), connectionIdProvider);
WebSocket socket = socketClient.newWebSocket(request, listener);
// Wrap the returned socket so an outbound frame is captured too -- the raw socket from
// newWebSocket() only records inbound events via the listener. Reuses the same
// connectionIdProvider so the "created" (wrap) and "open" (listener) events line up.
DevConsoleRecordingWebSocket.Companion.wrap(socket, DevConsole.socketRecorder(), connectionIdProvider)
.send("Hello from the views-java sample");
showResult("WebSocket connecting...");
}
private void simulatePush() {
Map<String, String> data = new HashMap<>();
data.put("campaign", "java-sample");
PushEvent event = DevConsole.recordPush(new PushInput(
"local",
data,
"java-sample-message-1",
"local-simulation",
null,
System.currentTimeMillis(),
null,
Collections.emptyMap(),
PushLifecycle.RECEIVED,
true
));
showResult("Push recorded: " + event.getMessageId());
}
private void simulateFirebasePush() {
FakeRemoteMessage remoteMessage = new FakeRemoteMessage();
PushInput input = new FirebaseRemoteMessageAdapter().toPushInput(remoteMessage);
PushEvent event = DevConsole.recordPush(input);
showResult("Firebase push recorded: " + event.getMessageId());
}
private void readFeatureFlag() {
showResult("Diagnostics flag: " + DevConsole.featureFlagValue(SHOW_DIAGNOSTICS_FLAG));
}
private void installMockRule() {
DevConsole.mockEngine().upsert(new MockRule(
MOCK_RULE_ID,
0,
null,
null,
null,
"/orders",
Collections.emptyMap(),
Collections.emptyMap(),
null,
MockScope.SESSION,
new MockAction.StaticResponse(200, "{\"mocked\":true,\"orders\":[]}", Collections.emptyMap()),
null
));
}
private void toggleMockRule() {
mockRuleEnabled = !mockRuleEnabled;
DevConsole.mockEngine().setEnabled(MOCK_RULE_ID, mockRuleEnabled);
showResult("Mock rule " + (mockRuleEnabled ? "enabled" : "disabled"));
}
/**
* Exercises the Java-friendly {@link DevConsole#captureScreenshotAsync} callback API -- the
* counterpart to the {@code suspend fun} the Kotlin samples call directly. Since this sample's
* config never calls {@code withScreenshotPolicy}, {@link ScreenshotResult.Disabled} is the
* branch actually reached here; the callback runs on a background thread, so the result is
* routed back through {@link #runOnUiThread}.
*/
private void captureScreenshot() {
DevConsole.captureScreenshotAsync(result -> runOnUiThread(() -> showResult(formatScreenshotResult(result))));
}
private static String formatScreenshotResult(ScreenshotResult result) {
if (result instanceof ScreenshotResult.Captured) {
ScreenshotResult.Captured captured = (ScreenshotResult.Captured) result;
return "Screenshot captured: " + captured.getWidthPx() + "x" + captured.getHeightPx()
+ ", " + captured.getByteCount() + " bytes";
} else if (result instanceof ScreenshotResult.Disabled) {
return "Screenshot capture is off -- set screenshotPolicy.enabled = true on DevConsoleConfig "
+ "(left at the default here; see the class Javadoc for why mocks being editable "
+ "doesn't imply screenshots are)";
} else if (result instanceof ScreenshotResult.DisabledForBuild) {
return "Screenshot capture isn't available in this release build";
} else if (result instanceof ScreenshotResult.NoForegroundActivity) {
return "No foreground activity to capture -- bring the app to the front and try again";
} else if (result instanceof ScreenshotResult.SecureWindow) {
return "This screen is FLAG_SECURE and cannot be captured";
} else if (result instanceof ScreenshotResult.Failed) {
return "Screenshot failed: " + ((ScreenshotResult.Failed) result).getReason();
}
return "Unknown screenshot result: " + result;
}
/**
* HAZARD: throws directly on the UI thread (button clicks already run there), producing a real
* uncaught crash that kills the process.
*/
private void triggerCrash() {
throw new IllegalStateException("views-java-app sample: deliberate uncaught crash");
}
/**
* HAZARD: blocks the UI thread past the default {@link io.devconsole.api.CrashPolicy}'s 5s
* {@code anrThresholdMs} so the ANR watchdog's all-thread dump fires. The process survives,
* unlike {@link #triggerCrash}.
*/
private void triggerAnr() {
try {
Thread.sleep(ANR_BLOCK_MS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
}
private void postResult(String text) {
new Handler(Looper.getMainLooper()).post(() -> showResult(text));
}
private void showResult(String text) {
connectUrl = null;
lastResponse.setText(text);
lastResponse.setClickable(false);
lastResponse.setContentDescription(text);
}
private void showConnectUrl(String url) {
connectUrl = url;
boolean usesSessionCode = url.contains("#code=");
String message = (usesSessionCode
? "Tap to copy the session-code URL: " + url + "\n\n"
+ "This is a full, single-use session credential -- the same code also renders as a QR on "
+ "the dashboard's More screen once you're connected. Treat it like a password.\n\n"
: "Tap to copy the dashboard URL: " + url + "\n\n"
+ "No session code is required in the default open mode. Use SESSION_CODE before sharing "
+ "a LAN-bound dashboard on an untrusted network.\n\n")
+ "This debugging session uses local-network HTTP. Other participants on an untrusted network "
+ "may observe or modify traffic. Use ADB localhost mode or a trusted isolated network for sensitive testing.";
lastResponse.setText(message);
lastResponse.setClickable(true);
lastResponse.setContentDescription(message + " Double tap to copy the dashboard URL.");
}
/**
* Seeds the Data inspectors (preferences/database/files) so the browser dashboard and the
* SDK's in-app inspector have real, browsable content the moment this sample launches.
* Preferences/database/files stay read-only per this file's {@link EditingCapabilities}
* posture (see the class-level comment); only mocks and capture rules are editable here.
*/
private static void seedSampleData(Context context) {
seedPreferences(context);
seedDatabase(context);
seedFiles(context);
}
private static void seedPreferences(Context context) {
SharedPreferences preferences = context.getSharedPreferences("views_java_sample_prefs", MODE_PRIVATE);
preferences.edit()
.putString("displayName", "Margaret Hamilton")
.putInt("cartItemCount", 2)
.putBoolean("darkModeEnabled", true)
.putFloat("checkoutProgress", 0.4f)
// Sensitive-named key (not a real secret): demonstrates the Preferences inspector's
// key-based redaction without ever writing a live credential to disk.
.putString("apiSecret", "sample-not-a-real-secret-77cd")
.apply();
}
private static void seedDatabase(Context context) {
try (SampleOrdersDatabase helper = new SampleOrdersDatabase(context);
SQLiteDatabase db = helper.getWritableDatabase()) {
if (DatabaseUtils.queryNumEntries(db, "orders") > 0) return;
insertOrder(db, "Views + Java sample mug", 12.0);
insertOrder(db, "DevConsole keychain", 3.5);
}
}
private static void insertOrder(SQLiteDatabase db, String item, double price) {
ContentValues values = new ContentValues();
values.put("item", item);
values.put("price", price);
db.insert("orders", null, values);
}
private static void seedFiles(Context context) {
writeTextFile(new File(context.getFilesDir(), "sample-notes.txt"),
"DevConsole views-java sample\nSeeded so the Files inspector has something to preview and download.\n");
writeBinaryFile(new File(context.getFilesDir(), "sample-binary.dat"));
}
private static void writeTextFile(File file, String content) {
try (FileOutputStream out = new FileOutputStream(file)) {
out.write(content.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) {
// Best-effort seed data; a failed write just leaves the Files inspector with less to show.
}
}
private static void writeBinaryFile(File file) {
byte[] bytes = new byte[64];
for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) i;
try (FileOutputStream out = new FileOutputStream(file)) {
out.write(bytes);
} catch (IOException ignored) {
// Best-effort seed data; a failed write just leaves the Files inspector with less to show.
}
}
/** Minimal SQLite schema so the Database inspector has a real table + rows to browse and query. */
private static final class SampleOrdersDatabase extends SQLiteOpenHelper {
SampleOrdersDatabase(Context context) {
super(context, "views_java_sample.db", null, 1);
}
@Override public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT NOT NULL, price REAL NOT NULL)");
}
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// No schema migrations in a sample database.
}
}
/**
* Reflection-shaped stand-in for {@code com.google.firebase.messaging.RemoteMessage}, letting
* {@link FirebaseRemoteMessageAdapter} be exercised without a real Firebase dependency.
*/
private static final class FakeRemoteMessage {
public Map<String, String> getData() {
Map<String, String> data = new HashMap<>();
data.put("campaign", "java-sample-firebase");
return data;
}
public FakeNotification getNotification() {
return new FakeNotification();
}
public String getMessageId() {
return "java-sample-firebase-message-1";
}
public long getSentTime() {
return System.currentTimeMillis();
}
public String getFrom() {
return "123456789";
}
public String getCollapseKey() {
return "java-sample-collapse-key";
}
}
private static final class FakeNotification {
public String getTitle() {
return "Sample notification";
}
public String getBody() {
return "Simulated via FirebaseRemoteMessageAdapter";
}
public String getChannelId() {
return "sample-channel";
}
public String getImageUrl() {
return null;
}
}
}