-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathEmbeddedBrowserActivity.java
433 lines (359 loc) · 13.7 KB
/
EmbeddedBrowserActivity.java
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
package org.medicmobile.webapp.mobile;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static org.medicmobile.webapp.mobile.BuildConfig.DEBUG;
import static org.medicmobile.webapp.mobile.MedicLog.error;
import static org.medicmobile.webapp.mobile.MedicLog.log;
import static org.medicmobile.webapp.mobile.MedicLog.trace;
import static org.medicmobile.webapp.mobile.MedicLog.warn;
import static org.medicmobile.webapp.mobile.SimpleJsonClient2.redactUrl;
import static org.medicmobile.webapp.mobile.Utils.createUseragentFrom;
import static org.medicmobile.webapp.mobile.Utils.isValidNavigationUrl;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import java.util.Arrays;
import java.util.Optional;
@SuppressWarnings({ "PMD.GodClass", "PMD.TooManyMethods" })
public class EmbeddedBrowserActivity extends Activity {
private WebView container;
private SettingsStore settings;
private String appUrl;
private MrdtSupport mrdt;
private FilePickerHandler filePickerHandler;
private SmsSender smsSender;
private ChtExternalAppHandler chtExternalAppHandler;
private boolean isMigrationRunning = false;
private static final ValueCallback<String> IGNORE_RESULT = new ValueCallback<String>() {
public void onReceiveValue(String result) { /* ignore */ }
};
private final ValueCallback<String> backButtonHandler = new ValueCallback<String>() {
public void onReceiveValue(String result) {
if(!"true".equals(result)) {
EmbeddedBrowserActivity.this.moveTaskToBack(false);
}
}
};
//> ACTIVITY LIFECYCLE METHODS
@SuppressLint("ClickableViewAccessibility")
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
trace(this, "Starting webview...");
this.filePickerHandler = new FilePickerHandler(this);
this.mrdt = new MrdtSupport(this);
this.chtExternalAppHandler = new ChtExternalAppHandler(this);
try {
this.smsSender = SmsSender.createInstance(this);
} catch(Exception ex) {
error(ex, "Failed to create SmsSender.");
}
this.settings = SettingsStore.in(this);
this.appUrl = settings.getAppUrl();
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// Add an alarming red border if using configurable (i.e. dev)
// app with a medic production server.
if (settings.allowsConfiguration() && appUrl != null && appUrl.contains("app.medicmobile.org")) {
View webviewContainer = findViewById(R.id.lytWebView);
webviewContainer.setPadding(10, 10, 10, 10);
webviewContainer.setBackgroundResource(R.drawable.warning_background);
}
// Add a noticeable border to easily identify a training app
if (BuildConfig.IS_TRAINING_APP) {
View webviewContainer = findViewById(R.id.lytWebView);
webviewContainer.setPadding(10, 10, 10, 10);
webviewContainer.setBackgroundResource(R.drawable.training_background);
}
container = findViewById(R.id.wbvMain);
getFragmentManager()
.beginTransaction()
.add(new OpenSettingsDialogFragment(), OpenSettingsDialogFragment.class.getName())
.commit();
configureUserAgent();
setUpUiClient(container);
enableRemoteChromeDebugging();
enableJavascript(container);
enableStorage(container);
enableUrlHandlers(container);
Intent appLinkIntent = getIntent();
Uri appLinkData = appLinkIntent.getData();
browseTo(appLinkData);
if (settings.allowsConfiguration()) {
toast(redactUrl(appUrl));
}
registerRetryConnectionBroadcastReceiver();
String recentNavigation = settings.getLastUrl();
if (isValidNavigationUrl(appUrl, recentNavigation)) {
container.loadUrl(recentNavigation);
}
}
@SuppressWarnings("PMD.CallSuperFirst")
@Override
protected void onStart() {
trace(this, "onStart() :: Checking Crosswalk migration ...");
XWalkMigration xWalkMigration = new XWalkMigration(this.getApplicationContext());
if (xWalkMigration.hasToMigrate()) {
log(this, "onStart() :: Running Crosswalk migration ...");
isMigrationRunning = true;
Intent intent = new Intent(this, UpgradingActivity.class)
.putExtra("isClosable", false)
.putExtra("backPressedMessage", getString(R.string.waitMigration));
startActivity(intent);
xWalkMigration.run();
} else {
trace(this, "onStart() :: Crosswalk installation not found - skipping migration");
}
trace(this, "onStart() :: Checking Crosswalk migration done.");
if (BuildConfig.IS_TRAINING_APP) {
toast(getString(R.string.usingTrainingApp));
}
super.onStart();
}
@Override
protected void onStop() {
String recentNavigation = container.getUrl();
if (isValidNavigationUrl(appUrl, recentNavigation)) {
try {
settings.setLastUrl(recentNavigation);
} catch (SettingsException e) {
error(e, "Error recording last URL loaded");
}
}
super.onStop();
}
@Override public void onBackPressed() {
trace(this, "onBackPressed()");
container.evaluateJavascript(
"angular.element(document.body).injector().get('AndroidApi').v1.back()",
backButtonHandler);
}
@Override
protected void onActivityResult(int requestCd, int resultCode, Intent intent) {
Optional<RequestCode> requestCodeOpt = RequestCode.valueOf(requestCd);
if (!requestCodeOpt.isPresent()) {
trace(this, "onActivityResult() :: no handling for requestCode=%s", requestCd);
return;
}
RequestCode requestCode = requestCodeOpt.get();
try {
trace(this, "onActivityResult() :: requestCode=%s, resultCode=%s", requestCode.name(), resultCode);
switch (requestCode) {
case FILE_PICKER_ACTIVITY:
this.filePickerHandler.processResult(resultCode, intent);
return;
case GRAB_MRDT_PHOTO_ACTIVITY:
processMrdtResult(requestCode, intent);
return;
case CHT_EXTERNAL_APP_ACTIVITY:
processChtExternalAppResult(resultCode, intent);
return;
case ACCESS_STORAGE_PERMISSION:
processStoragePermissionResult(resultCode, intent);
return;
case ACCESS_LOCATION_PERMISSION:
locationRequestResolved();
return;
case ACCESS_SEND_SMS_PERMISSION:
this.smsSender.resumeProcess(resultCode);
return;
default:
trace(this, "onActivityResult() :: no handling for requestCode=%s", requestCode.name());
}
} catch (Exception ex) {
String action = intent == null ? null : intent.getAction();
warn(ex, "Problem handling intent %s (%s) with requestCode=%s & resultCode=%s",
intent, action, requestCode.name(), resultCode);
}
}
//> ACCESSORS
MrdtSupport getMrdtSupport() {
return this.mrdt;
}
SmsSender getSmsSender() {
return this.smsSender;
}
ChtExternalAppHandler getChtExternalAppHandler() {
return this.chtExternalAppHandler;
}
//> PUBLIC API
public void evaluateJavascript(final String js) {
evaluateJavascript(js, true);
}
public void evaluateJavascript(final String js, final boolean useLoadUrl) {
int maxUrlSize = 2097100; // Maximum character limit supported for loading as url.
if (useLoadUrl && js.length() <= maxUrlSize) {
// `WebView.loadUrl()` seems to be significantly faster than `WebView.evaluateJavascript()` on Tecno Y4.
container.post(() -> container.loadUrl("javascript:" + js, null));
} else {
container.post(() -> container.evaluateJavascript(js, IGNORE_RESULT));
}
}
public void errorToJsConsole(String message, Object... extras) {
String formatted = String.format(message, extras);
String escaped = formatted.replace("'", "\\'");
evaluateJavascript("console.error('" + escaped + "');");
}
public boolean isMigrationRunning() {
return isMigrationRunning;
}
public void setMigrationRunning(boolean migrationRunning) {
isMigrationRunning = migrationRunning;
}
public boolean getLocationPermissions() {
boolean hasFineLocation = ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED;
boolean hasCoarseLocation = ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED;
if (hasFineLocation && hasCoarseLocation) {
trace(this, "getLocationPermissions() :: Fine and Coarse location already granted");
return true;
}
trace(this, "getLocationPermissions() :: Fine or Coarse location not granted before, requesting access...");
startActivityForResult(
new Intent(this, RequestLocationPermissionActivity.class),
RequestCode.ACCESS_LOCATION_PERMISSION.getCode()
);
return false;
}
//> PRIVATE HELPERS
private void locationRequestResolved() {
evaluateJavascript("window.CHTCore.AndroidApi.v1.locationPermissionRequestResolved();");
}
private void processChtExternalAppResult(int resultCode, Intent intentData) {
String script = this.chtExternalAppHandler.processResult(resultCode, intentData);
trace(this, "ChtExternalAppHandler :: Executing JavaScript: %s", script);
evaluateJavascript(script);
}
private void processMrdtResult(RequestCode requestCode, Intent intent) {
String js = mrdt.process(requestCode, intent);
trace(this, "Executing JavaScript: %s", js);
evaluateJavascript(js);
}
private void processStoragePermissionResult(int resultCode, Intent intent) {
String triggerClass = intent == null ? null : intent.getStringExtra(RequestStoragePermissionActivity.TRIGGER_CLASS);
if (FilePickerHandler.class.getName().equals(triggerClass)) {
trace(this, "EmbeddedBrowserActivity :: Resuming FilePickerHandler process. Trigger:%s", triggerClass);
this.filePickerHandler.resumeProcess(resultCode);
return;
}
if (ChtExternalAppHandler.class.getName().equals(triggerClass)) {
trace(this, "EmbeddedBrowserActivity :: Resuming ChtExternalAppHandler activity. Trigger:%s", triggerClass);
this.chtExternalAppHandler.resumeActivity(resultCode);
return;
}
trace(
this,
"EmbeddedBrowserActivity :: No handling for trigger: %s, requestCode: %s",
triggerClass,
RequestCode.ACCESS_STORAGE_PERMISSION.name()
);
}
private void configureUserAgent() {
String current = WebSettings.getDefaultUserAgent(this);
container.getSettings().setUserAgentString(createUseragentFrom(current));
}
private void browseTo(Uri url) {
String urlToLoad = this.settings.getUrlToLoad(url);
trace(this, "Pointing browser to: %s", redactUrl(urlToLoad));
container.loadUrl(urlToLoad, null);
}
private void enableRemoteChromeDebugging() {
WebView.setWebContentsDebuggingEnabled(true);
}
private void setUpUiClient(WebView container) {
container.setWebChromeClient(new WebChromeClient() {
@Override public boolean onConsoleMessage(ConsoleMessage cm) {
if (!DEBUG) {
return super.onConsoleMessage(cm);
}
trace(this, "onConsoleMessage() :: %s:%s | %s", cm.sourceId(), cm.lineNumber(), cm.message());
return true;
}
@Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
filePickerHandler.openPicker(fileChooserParams, filePathCallback);
return true;
}
@Override public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, true);
}
});
}
@SuppressLint("SetJavaScriptEnabled")
private void enableJavascript(WebView container) {
container.getSettings().setJavaScriptEnabled(true);
MedicAndroidJavascript maj = new MedicAndroidJavascript(this);
maj.setAlert(new Alert(this));
maj.setActivityManager((ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE));
maj.setConnectivityManager((ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE));
container.addJavascriptInterface(maj, "medicmobile_android");
}
private void enableStorage(WebView container) {
WebSettings settings = container.getSettings();
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
}
private void enableUrlHandlers(WebView container) {
container.setWebViewClient(new UrlHandler(this, settings));
}
private void toast(String message) {
if (message != null) {
Toast.makeText(container.getContext(), message, Toast.LENGTH_LONG).show();
}
}
private void registerRetryConnectionBroadcastReceiver() {
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("retryConnection")) {
// user fixed the connection and asked the app
// to retry the load from the connection error activity
evaluateJavascript("window.location.reload()", false);
}
}
};
ContextCompat.registerReceiver(
getApplicationContext(),
broadcastReceiver,
new IntentFilter("retryConnection"),
ContextCompat.RECEIVER_NOT_EXPORTED
);
}
//> ENUMS
public enum RequestCode {
ACCESS_LOCATION_PERMISSION(100),
ACCESS_STORAGE_PERMISSION(101),
ACCESS_SEND_SMS_PERMISSION(102),
CHT_EXTERNAL_APP_ACTIVITY(103),
GRAB_MRDT_PHOTO_ACTIVITY(104),
FILE_PICKER_ACTIVITY(105);
private final int requestCode;
RequestCode(int requestCode) {
this.requestCode = requestCode;
}
public static Optional<RequestCode> valueOf(int code) {
return Arrays
.stream(RequestCode.values())
.filter(e -> e.getCode() == code)
.findFirst();
}
public int getCode() {
return requestCode;
}
}
}