/
Bridge.java
1544 lines (1315 loc) · 54.6 KB
/
Bridge.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
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.getcapacitor;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.pm.PackageInfoCompat;
import androidx.fragment.app.Fragment;
import com.getcapacitor.android.R;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.cordova.MockCordovaInterfaceImpl;
import com.getcapacitor.cordova.MockCordovaWebViewImpl;
import com.getcapacitor.util.HostMask;
import com.getcapacitor.util.InternalUtils;
import com.getcapacitor.util.PermissionHelper;
import com.getcapacitor.util.WebColor;
import java.io.File;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginManager;
import org.json.JSONException;
/**
* The Bridge class is the main engine of Capacitor. It manages
* loading and communicating with all Plugins,
* proxying Native events to Plugins, executing Plugin methods,
* communicating with the WebView, and a whole lot more.
*
* Generally, you'll not use Bridge directly, instead, extend from BridgeActivity
* to get a WebView instance and proxy native events automatically.
*
* If you want to use this Bridge in an existing Android app, please
* see the source for BridgeActivity for the methods you'll need to
* pass through to Bridge:
* <a href="https://github.com/ionic-team/capacitor/blob/HEAD/android/capacitor/src/main/java/com/getcapacitor/BridgeActivity.java">
* BridgeActivity.java</a>
*/
public class Bridge {
private static final String PREFS_NAME = "CapacitorSettings";
private static final String PERMISSION_PREFS_NAME = "PluginPermStates";
private static final String BUNDLE_LAST_PLUGIN_ID_KEY = "capacitorLastActivityPluginId";
private static final String BUNDLE_LAST_PLUGIN_CALL_METHOD_NAME_KEY = "capacitorLastActivityPluginMethod";
private static final String BUNDLE_PLUGIN_CALL_OPTIONS_SAVED_KEY = "capacitorLastPluginCallOptions";
private static final String BUNDLE_PLUGIN_CALL_BUNDLE_KEY = "capacitorLastPluginCallBundle";
private static final String LAST_BINARY_VERSION_CODE = "lastBinaryVersionCode";
private static final String LAST_BINARY_VERSION_NAME = "lastBinaryVersionName";
private static final String MINIMUM_ANDROID_WEBVIEW_ERROR = "System WebView is not supported";
// The name of the directory we use to look for index.html and the rest of our web assets
public static final String DEFAULT_WEB_ASSET_DIR = "public";
public static final String CAPACITOR_HTTP_SCHEME = "http";
public static final String CAPACITOR_HTTPS_SCHEME = "https";
public static final String CAPACITOR_FILE_START = "/_capacitor_file_";
public static final String CAPACITOR_CONTENT_START = "/_capacitor_content_";
public static final int DEFAULT_ANDROID_WEBVIEW_VERSION = 60;
public static final int MINIMUM_ANDROID_WEBVIEW_VERSION = 55;
public static final int DEFAULT_HUAWEI_WEBVIEW_VERSION = 10;
public static final int MINIMUM_HUAWEI_WEBVIEW_VERSION = 10;
// Loaded Capacitor config
private CapConfig config;
// A reference to the main activity for the app
private final AppCompatActivity context;
// A reference to the containing Fragment if used
private final Fragment fragment;
private WebViewLocalServer localServer;
private String localUrl;
private String appUrl;
private String appUrlConfig;
private HostMask appAllowNavigationMask;
private Set<String> allowedOriginRules = new HashSet<String>();
// A reference to the main WebView for the app
private final WebView webView;
public final MockCordovaInterfaceImpl cordovaInterface;
private CordovaWebView cordovaWebView;
private CordovaPreferences preferences;
private BridgeWebViewClient webViewClient;
private App app;
// Our MessageHandler for sending and receiving data to the WebView
private final MessageHandler msgHandler;
// The ThreadHandler for executing plugin calls
private final HandlerThread handlerThread = new HandlerThread("CapacitorPlugins");
// Our Handler for posting plugin calls. Created from the ThreadHandler
private Handler taskHandler = null;
private final List<Class<? extends Plugin>> initialPlugins;
private final List<Plugin> pluginInstances;
// A map of Plugin Id's to PluginHandle's
private Map<String, PluginHandle> plugins = new HashMap<>();
// Stored plugin calls that we're keeping around to call again someday
private Map<String, PluginCall> savedCalls = new HashMap<>();
// The call IDs of saved plugin calls with associated plugin id for handling permissions
private Map<String, LinkedList<String>> savedPermissionCallIds = new HashMap<>();
// Store a plugin that started a new activity, in case we need to resume
// the app and return that data back
private PluginCall pluginCallForLastActivity;
// Any URI that was passed to the app on start
private Uri intentUri;
// A list of listeners that trigger when webView events occur
private List<WebViewListener> webViewListeners = new ArrayList<>();
// An interface to manipulate route resolving
private RouteProcessor routeProcessor;
// A pre-determined path to load the bridge
private ServerPath serverPath;
/**
* Create the Bridge with a reference to the main {@link Activity} for the
* app, and a reference to the {@link WebView} our app will use.
* @param context
* @param webView
* @deprecated Use {@link Bridge.Builder} to create Bridge instances
*/
@Deprecated
public Bridge(
AppCompatActivity context,
WebView webView,
List<Class<? extends Plugin>> initialPlugins,
MockCordovaInterfaceImpl cordovaInterface,
PluginManager pluginManager,
CordovaPreferences preferences,
CapConfig config
) {
this(context, null, null, webView, initialPlugins, new ArrayList<>(), cordovaInterface, pluginManager, preferences, config);
}
private Bridge(
AppCompatActivity context,
ServerPath serverPath,
Fragment fragment,
WebView webView,
List<Class<? extends Plugin>> initialPlugins,
List<Plugin> pluginInstances,
MockCordovaInterfaceImpl cordovaInterface,
PluginManager pluginManager,
CordovaPreferences preferences,
CapConfig config
) {
this.app = new App();
this.serverPath = serverPath;
this.context = context;
this.fragment = fragment;
this.webView = webView;
this.webViewClient = new BridgeWebViewClient(this);
this.initialPlugins = initialPlugins;
this.pluginInstances = pluginInstances;
this.cordovaInterface = cordovaInterface;
this.preferences = preferences;
// Start our plugin execution threads and handlers
handlerThread.start();
taskHandler = new Handler(handlerThread.getLooper());
this.config = config != null ? config : CapConfig.loadDefault(getActivity());
Logger.init(this.config);
// Initialize web view and message handler for it
this.initWebView();
this.setAllowedOriginRules();
this.msgHandler = new MessageHandler(this, webView, pluginManager);
// Grab any intent info that our app was launched with
Intent intent = context.getIntent();
this.intentUri = intent.getData();
// Register our core plugins
this.registerAllPlugins();
this.loadWebView();
}
private void setAllowedOriginRules() {
String[] appAllowNavigationConfig = this.config.getAllowNavigation();
String authority = this.getHost();
String scheme = this.getScheme();
allowedOriginRules.add(scheme + "://" + authority);
if (this.getServerUrl() != null) {
allowedOriginRules.add(this.getServerUrl());
}
if (appAllowNavigationConfig != null) {
for (String allowNavigation : appAllowNavigationConfig) {
if (!allowNavigation.startsWith("http")) {
allowedOriginRules.add("https://" + allowNavigation);
} else {
allowedOriginRules.add(allowNavigation);
}
}
}
}
public App getApp() {
return app;
}
private void loadWebView() {
appUrlConfig = this.getServerUrl();
String[] appAllowNavigationConfig = this.config.getAllowNavigation();
ArrayList<String> authorities = new ArrayList<>();
if (appAllowNavigationConfig != null) {
authorities.addAll(Arrays.asList(appAllowNavigationConfig));
}
this.appAllowNavigationMask = HostMask.Parser.parse(appAllowNavigationConfig);
String authority = this.getHost();
authorities.add(authority);
String scheme = this.getScheme();
localUrl = scheme + "://" + authority;
if (appUrlConfig != null) {
try {
URL appUrlObject = new URL(appUrlConfig);
authorities.add(appUrlObject.getAuthority());
} catch (Exception ex) {
Logger.error("Provided server url is invalid: " + ex.getMessage());
return;
}
localUrl = appUrlConfig;
appUrl = appUrlConfig;
} else {
appUrl = localUrl;
// custom URL schemes requires path ending with /
if (!scheme.equals(Bridge.CAPACITOR_HTTP_SCHEME) && !scheme.equals(CAPACITOR_HTTPS_SCHEME)) {
appUrl += "/";
}
}
String appUrlPath = this.config.getStartPath();
if (appUrlPath != null && !appUrlPath.trim().isEmpty()) {
appUrl += appUrlPath;
}
final boolean html5mode = this.config.isHTML5Mode();
// Start the local web server
localServer = new WebViewLocalServer(context, this, getJSInjector(), authorities, html5mode);
localServer.hostAssets(DEFAULT_WEB_ASSET_DIR);
Logger.debug("Loading app at " + appUrl);
webView.setWebChromeClient(new BridgeWebChromeClient(this));
webView.setWebViewClient(this.webViewClient);
if (!isDeployDisabled() && !isNewBinary()) {
SharedPreferences prefs = getContext()
.getSharedPreferences(com.getcapacitor.plugin.WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
String path = prefs.getString(com.getcapacitor.plugin.WebView.CAP_SERVER_PATH, null);
if (path != null && !path.isEmpty() && new File(path).exists()) {
setServerBasePath(path);
}
}
if (!this.isMinimumWebViewInstalled()) {
String errorUrl = this.getErrorUrl();
if (errorUrl != null) {
webView.loadUrl(errorUrl);
return;
} else {
Logger.error(MINIMUM_ANDROID_WEBVIEW_ERROR);
}
}
// If serverPath configured, start server based on provided path
if (serverPath != null) {
if (serverPath.getType() == ServerPath.PathType.ASSET_PATH) {
setServerAssetPath(serverPath.getPath());
} else {
setServerBasePath(serverPath.getPath());
}
} else {
// Get to work
webView.loadUrl(appUrl);
}
}
@SuppressLint("WebViewApiAvailability")
public boolean isMinimumWebViewInstalled() {
PackageManager pm = getContext().getPackageManager();
// Check getCurrentWebViewPackage() directly if above Android 8
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PackageInfo info = WebView.getCurrentWebViewPackage();
if (info.packageName.equals("com.huawei.webview")) {
String majorVersionStr = info.versionName.split("\\.")[0];
int majorVersion = Integer.parseInt(majorVersionStr);
return majorVersion >= config.getMinHuaweiWebViewVersion();
}
String majorVersionStr = info.versionName.split("\\.")[0];
int majorVersion = Integer.parseInt(majorVersionStr);
return majorVersion >= config.getMinWebViewVersion();
}
// Otherwise manually check WebView versions
try {
String webViewPackage = "com.google.android.webview";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
webViewPackage = "com.android.chrome";
}
PackageInfo info = InternalUtils.getPackageInfo(pm, webViewPackage);
String majorVersionStr = info.versionName.split("\\.")[0];
int majorVersion = Integer.parseInt(majorVersionStr);
return majorVersion >= config.getMinWebViewVersion();
} catch (Exception ex) {
Logger.warn("Unable to get package info for 'com.google.android.webview'" + ex.toString());
}
try {
PackageInfo info = InternalUtils.getPackageInfo(pm, "com.android.webview");
String majorVersionStr = info.versionName.split("\\.")[0];
int majorVersion = Integer.parseInt(majorVersionStr);
return majorVersion >= config.getMinWebViewVersion();
} catch (Exception ex) {
Logger.warn("Unable to get package info for 'com.android.webview'" + ex.toString());
}
// Could not detect any webview, return false
return false;
}
public boolean launchIntent(Uri url) {
/*
* Give plugins the chance to handle the url
*/
for (Map.Entry<String, PluginHandle> entry : plugins.entrySet()) {
Plugin plugin = entry.getValue().getInstance();
if (plugin != null) {
Boolean shouldOverrideLoad = plugin.shouldOverrideLoad(url);
if (shouldOverrideLoad != null) {
return shouldOverrideLoad;
}
}
}
if (url.getScheme().equals("data")) {
return false;
}
if (!url.toString().startsWith(appUrl) && !appAllowNavigationMask.matches(url.getHost())) {
try {
Intent openIntent = new Intent(Intent.ACTION_VIEW, url);
getContext().startActivity(openIntent);
} catch (ActivityNotFoundException e) {
// TODO - trigger an event
}
return true;
}
return false;
}
private boolean isNewBinary() {
String versionCode = "";
String versionName = "";
SharedPreferences prefs = getContext()
.getSharedPreferences(com.getcapacitor.plugin.WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
String lastVersionCode = prefs.getString(LAST_BINARY_VERSION_CODE, null);
String lastVersionName = prefs.getString(LAST_BINARY_VERSION_NAME, null);
try {
PackageManager pm = getContext().getPackageManager();
PackageInfo pInfo = InternalUtils.getPackageInfo(pm, getContext().getPackageName());
versionCode = Integer.toString((int) PackageInfoCompat.getLongVersionCode(pInfo));
versionName = pInfo.versionName;
} catch (Exception ex) {
Logger.error("Unable to get package info", ex);
}
if (!versionCode.equals(lastVersionCode) || !versionName.equals(lastVersionName)) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(LAST_BINARY_VERSION_CODE, versionCode);
editor.putString(LAST_BINARY_VERSION_NAME, versionName);
editor.putString(com.getcapacitor.plugin.WebView.CAP_SERVER_PATH, "");
editor.apply();
return true;
}
return false;
}
public boolean isDeployDisabled() {
return preferences.getBoolean("DisableDeploy", false);
}
public boolean shouldKeepRunning() {
return preferences.getBoolean("KeepRunning", true);
}
public void handleAppUrlLoadError(Exception ex) {
if (ex instanceof SocketTimeoutException) {
Logger.error(
"Unable to load app. Ensure the server is running at " +
appUrl +
", or modify the " +
"appUrl setting in capacitor.config.json (make sure to npx cap copy after to commit changes).",
ex
);
}
}
public boolean isDevMode() {
return (getActivity().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
}
protected void setCordovaWebView(CordovaWebView cordovaWebView) {
this.cordovaWebView = cordovaWebView;
}
/**
* Get the Context for the App
* @return
*/
public Context getContext() {
return this.context;
}
/**
* Get the activity for the app
* @return
*/
public AppCompatActivity getActivity() {
return this.context;
}
/**
* Get the fragment for the app, if applicable. This will likely be null unless Capacitor
* is being used embedded in a Native Android app.
*
* @return The fragment containing the Capacitor WebView.
*/
public Fragment getFragment() {
return this.fragment;
}
/**
* Get the core WebView under Capacitor's control
* @return
*/
public WebView getWebView() {
return this.webView;
}
/**
* Get the URI that was used to launch the app (if any)
* @return
*/
public Uri getIntentUri() {
return intentUri;
}
/**
* Get scheme that is used to serve content
* @return
*/
public String getScheme() {
return this.config.getAndroidScheme();
}
/**
* Get host name that is used to serve content
* @return
*/
public String getHost() {
return this.config.getHostname();
}
/**
* Get the server url that is used to serve content
* @return
*/
public String getServerUrl() {
return this.config.getServerUrl();
}
public String getErrorUrl() {
String errorPath = this.config.getErrorPath();
if (errorPath != null && !errorPath.trim().isEmpty()) {
String authority = this.getHost();
String scheme = this.getScheme();
String localUrl = scheme + "://" + authority;
return localUrl + "/" + errorPath;
}
return null;
}
public String getAppUrl() {
return appUrl;
}
public CapConfig getConfig() {
return this.config;
}
public void reset() {
savedCalls = new HashMap<>();
}
/**
* Initialize the WebView, setting required flags
*/
@SuppressLint("SetJavaScriptEnabled")
private void initWebView() {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setGeolocationEnabled(true);
settings.setDatabaseEnabled(true);
settings.setMediaPlaybackRequiresUserGesture(false);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
if (this.config.isMixedContentAllowed()) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
String appendUserAgent = this.config.getAppendedUserAgentString();
if (appendUserAgent != null) {
String defaultUserAgent = settings.getUserAgentString();
settings.setUserAgentString(defaultUserAgent + " " + appendUserAgent);
}
String overrideUserAgent = this.config.getOverriddenUserAgentString();
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
String backgroundColor = this.config.getBackgroundColor();
try {
if (backgroundColor != null) {
webView.setBackgroundColor(WebColor.parseColor(backgroundColor));
}
} catch (IllegalArgumentException ex) {
Logger.debug("WebView background color not applied");
}
if (config.isInitialFocus()) {
webView.requestFocusFromTouch();
}
WebView.setWebContentsDebuggingEnabled(this.config.isWebContentsDebuggingEnabled());
}
/**
* Register our core Plugin APIs
*/
private void registerAllPlugins() {
this.registerPlugin(com.getcapacitor.plugin.CapacitorCookies.class);
this.registerPlugin(com.getcapacitor.plugin.WebView.class);
this.registerPlugin(com.getcapacitor.plugin.CapacitorHttp.class);
for (Class<? extends Plugin> pluginClass : this.initialPlugins) {
this.registerPlugin(pluginClass);
}
for (Plugin plugin : pluginInstances) {
registerPluginInstance(plugin);
}
}
/**
* Register additional plugins
* @param pluginClasses the plugins to register
*/
public void registerPlugins(Class<? extends Plugin>[] pluginClasses) {
for (Class<? extends Plugin> plugin : pluginClasses) {
this.registerPlugin(plugin);
}
}
public void registerPluginInstances(Plugin[] pluginInstances) {
for (Plugin plugin : pluginInstances) {
this.registerPluginInstance(plugin);
}
}
@SuppressWarnings("deprecation")
private String getLegacyPluginName(Class<? extends Plugin> pluginClass) {
NativePlugin legacyPluginAnnotation = pluginClass.getAnnotation(NativePlugin.class);
if (legacyPluginAnnotation == null) {
Logger.error("Plugin doesn't have the @CapacitorPlugin annotation. Please add it");
return null;
}
return legacyPluginAnnotation.name();
}
/**
* Register a plugin class
* @param pluginClass a class inheriting from Plugin
*/
public void registerPlugin(Class<? extends Plugin> pluginClass) {
String pluginId = pluginId(pluginClass);
if (pluginId == null) return;
try {
this.plugins.put(pluginId, new PluginHandle(this, pluginClass));
} catch (InvalidPluginException ex) {
logInvalidPluginException(pluginClass);
} catch (PluginLoadException ex) {
logPluginLoadException(pluginClass, ex);
}
}
public void registerPluginInstance(Plugin plugin) {
Class<? extends Plugin> clazz = plugin.getClass();
String pluginId = pluginId(clazz);
if (pluginId == null) return;
try {
this.plugins.put(pluginId, new PluginHandle(this, plugin));
} catch (InvalidPluginException ex) {
logInvalidPluginException(clazz);
}
}
private String pluginId(Class<? extends Plugin> clazz) {
String pluginName = pluginName(clazz);
String pluginId = clazz.getSimpleName();
if (pluginName == null) return null;
if (!pluginName.equals("")) {
pluginId = pluginName;
}
Logger.debug("Registering plugin instance: " + pluginId);
return pluginId;
}
private String pluginName(Class<? extends Plugin> clazz) {
String pluginName;
CapacitorPlugin pluginAnnotation = clazz.getAnnotation(CapacitorPlugin.class);
if (pluginAnnotation == null) {
pluginName = this.getLegacyPluginName(clazz);
} else {
pluginName = pluginAnnotation.name();
}
return pluginName;
}
private void logInvalidPluginException(Class<? extends Plugin> clazz) {
Logger.error(
"NativePlugin " +
clazz.getName() +
" is invalid. Ensure the @CapacitorPlugin annotation exists on the plugin class and" +
" the class extends Plugin"
);
}
private void logPluginLoadException(Class<? extends Plugin> clazz, Exception ex) {
Logger.error("NativePlugin " + clazz.getName() + " failed to load", ex);
}
public PluginHandle getPlugin(String pluginId) {
return this.plugins.get(pluginId);
}
/**
* Find the plugin handle that responds to the given request code. This will
* fire after certain Android OS intent results/permission checks/etc.
* @param requestCode
* @return
*/
@Deprecated
@SuppressWarnings("deprecation")
public PluginHandle getPluginWithRequestCode(int requestCode) {
for (PluginHandle handle : this.plugins.values()) {
int[] requestCodes;
CapacitorPlugin pluginAnnotation = handle.getPluginAnnotation();
if (pluginAnnotation == null) {
// Check for legacy plugin annotation, @NativePlugin
NativePlugin legacyPluginAnnotation = handle.getLegacyPluginAnnotation();
if (legacyPluginAnnotation == null) {
continue;
}
if (legacyPluginAnnotation.permissionRequestCode() == requestCode) {
return handle;
}
requestCodes = legacyPluginAnnotation.requestCodes();
for (int rc : requestCodes) {
if (rc == requestCode) {
return handle;
}
}
} else {
requestCodes = pluginAnnotation.requestCodes();
for (int rc : requestCodes) {
if (rc == requestCode) {
return handle;
}
}
}
}
return null;
}
/**
* Call a method on a plugin.
* @param pluginId the plugin id to use to lookup the plugin handle
* @param methodName the name of the method to call
* @param call the call object to pass to the method
*/
public void callPluginMethod(String pluginId, final String methodName, final PluginCall call) {
try {
final PluginHandle plugin = this.getPlugin(pluginId);
if (plugin == null) {
Logger.error("unable to find plugin : " + pluginId);
call.errorCallback("unable to find plugin : " + pluginId);
return;
}
if (Logger.shouldLog()) {
Logger.verbose(
"callback: " +
call.getCallbackId() +
", pluginId: " +
plugin.getId() +
", methodName: " +
methodName +
", methodData: " +
call.getData().toString()
);
}
Runnable currentThreadTask = () -> {
try {
plugin.invoke(methodName, call);
if (call.isKeptAlive()) {
saveCall(call);
}
} catch (PluginLoadException | InvalidPluginMethodException ex) {
Logger.error("Unable to execute plugin method", ex);
} catch (Exception ex) {
Logger.error("Serious error executing plugin", ex);
throw new RuntimeException(ex);
}
};
taskHandler.post(currentThreadTask);
} catch (Exception ex) {
Logger.error(Logger.tags("callPluginMethod"), "error : " + ex, null);
call.errorCallback(ex.toString());
}
}
/**
* Evaluate JavaScript in the web view. This method
* executes on the main thread automatically.
* @param js the JS to execute
* @param callback an optional ValueCallback that will synchronously receive a value
* after calling the JS
*/
public void eval(final String js, final ValueCallback<String> callback) {
Handler mainHandler = new Handler(context.getMainLooper());
mainHandler.post(() -> webView.evaluateJavascript(js, callback));
}
public void logToJs(final String message, final String level) {
eval("window.Capacitor.logJs(\"" + message + "\", \"" + level + "\")", null);
}
public void logToJs(final String message) {
logToJs(message, "log");
}
public void triggerJSEvent(final String eventName, final String target) {
eval("window.Capacitor.triggerEvent(\"" + eventName + "\", \"" + target + "\")", s -> {});
}
public void triggerJSEvent(final String eventName, final String target, final String data) {
eval("window.Capacitor.triggerEvent(\"" + eventName + "\", \"" + target + "\", " + data + ")", s -> {});
}
public void triggerWindowJSEvent(final String eventName) {
this.triggerJSEvent(eventName, "window");
}
public void triggerWindowJSEvent(final String eventName, final String data) {
this.triggerJSEvent(eventName, "window", data);
}
public void triggerDocumentJSEvent(final String eventName) {
this.triggerJSEvent(eventName, "document");
}
public void triggerDocumentJSEvent(final String eventName, final String data) {
this.triggerJSEvent(eventName, "document", data);
}
public void execute(Runnable runnable) {
taskHandler.post(runnable);
}
public void executeOnMainThread(Runnable runnable) {
Handler mainHandler = new Handler(context.getMainLooper());
mainHandler.post(runnable);
}
/**
* Retain a call between plugin invocations
* @param call
*/
public void saveCall(PluginCall call) {
this.savedCalls.put(call.getCallbackId(), call);
}
/**
* Get a retained plugin call
* @param callbackId the callbackId to use to lookup the call with
* @return the stored call
*/
public PluginCall getSavedCall(String callbackId) {
if (callbackId == null) {
return null;
}
return this.savedCalls.get(callbackId);
}
PluginCall getPluginCallForLastActivity() {
PluginCall pluginCallForLastActivity = this.pluginCallForLastActivity;
this.pluginCallForLastActivity = null;
return pluginCallForLastActivity;
}
void setPluginCallForLastActivity(PluginCall pluginCallForLastActivity) {
this.pluginCallForLastActivity = pluginCallForLastActivity;
}
/**
* Release a retained call
* @param call a call to release
*/
public void releaseCall(PluginCall call) {
releaseCall(call.getCallbackId());
}
/**
* Release a retained call by its ID
* @param callbackId an ID of a callback to release
*/
public void releaseCall(String callbackId) {
this.savedCalls.remove(callbackId);
}
/**
* Removes the earliest saved call prior to a permissions request for a given plugin and
* returns it.
*
* @return The saved plugin call
*/
protected PluginCall getPermissionCall(String pluginId) {
LinkedList<String> permissionCallIds = this.savedPermissionCallIds.get(pluginId);
String savedCallId = null;
if (permissionCallIds != null) {
savedCallId = permissionCallIds.poll();
}
return getSavedCall(savedCallId);
}
/**
* Save a call to be retrieved after requesting permissions. Calls are saved in order.
*
* @param call The plugin call to save.
*/
protected void savePermissionCall(PluginCall call) {
if (call != null) {
if (!savedPermissionCallIds.containsKey(call.getPluginId())) {
savedPermissionCallIds.put(call.getPluginId(), new LinkedList<>());
}
savedPermissionCallIds.get(call.getPluginId()).add(call.getCallbackId());
saveCall(call);
}
}
/**
* Register an Activity Result Launcher to the containing Fragment or Activity.
*
* @param contract A contract specifying that an activity can be called with an input of
* type I and produce an output of type O.
* @param callback The callback run on Activity Result.
* @return A registered Activity Result Launcher.
*/
public <I, O> ActivityResultLauncher<I> registerForActivityResult(
@NonNull final ActivityResultContract<I, O> contract,
@NonNull final ActivityResultCallback<O> callback
) {
if (fragment != null) {
return fragment.registerForActivityResult(contract, callback);
} else {
return context.registerForActivityResult(contract, callback);
}
}
/**
* Build the JSInjector that will be used to inject JS into files served to the app,
* to ensure that Capacitor's JS and the JS for all the plugins is loaded each time.
*/
private JSInjector getJSInjector() {
try {
String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode());
String bridgeJS = JSExport.getBridgeJS(context);
String pluginJS = JSExport.getPluginJS(plugins.values());
String cordovaJS = JSExport.getCordovaJS(context);
String cordovaPluginsJS = JSExport.getCordovaPluginJS(context);
String cordovaPluginsFileJS = JSExport.getCordovaPluginsFileJS(context);
String localUrlJS = "window.WEBVIEW_SERVER_URL = '" + localUrl + "';";
return new JSInjector(globalJS, bridgeJS, pluginJS, cordovaJS, cordovaPluginsJS, cordovaPluginsFileJS, localUrlJS);
} catch (Exception ex) {
Logger.error("Unable to export Capacitor JS. App will not function!", ex);
}
return null;
}
/**
* Restore any saved bundle state data
* @param savedInstanceState
*/
public void restoreInstanceState(Bundle savedInstanceState) {
String lastPluginId = savedInstanceState.getString(BUNDLE_LAST_PLUGIN_ID_KEY);
String lastPluginCallMethod = savedInstanceState.getString(BUNDLE_LAST_PLUGIN_CALL_METHOD_NAME_KEY);
String lastOptionsJson = savedInstanceState.getString(BUNDLE_PLUGIN_CALL_OPTIONS_SAVED_KEY);
if (lastPluginId != null) {
// If we have JSON blob saved, create a new plugin call with the original options
if (lastOptionsJson != null) {
try {
JSObject options = new JSObject(lastOptionsJson);
pluginCallForLastActivity =
new PluginCall(msgHandler, lastPluginId, PluginCall.CALLBACK_ID_DANGLING, lastPluginCallMethod, options);
} catch (JSONException ex) {
Logger.error("Unable to restore plugin call, unable to parse persisted JSON object", ex);
}
}
// Let the plugin restore any state it needs
Bundle bundleData = savedInstanceState.getBundle(BUNDLE_PLUGIN_CALL_BUNDLE_KEY);
PluginHandle lastPlugin = getPlugin(lastPluginId);
if (bundleData != null && lastPlugin != null) {
lastPlugin.getInstance().restoreState(bundleData);
} else {
Logger.error("Unable to restore last plugin call");
}
}
}