public class MainActivity extends BridgeActivity {
private static final String TAG = "MainActivity";
private NfcAdapter nfcAdapter;
public float initialSystemFontScale;
code
@Override
protected void onCreate(Bundle savedInstanceState) {
registerPlugin(MtbPlugin.class);
registerPlugin(ZoomPlugin.class);
super.onCreate(savedInstanceState);
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
if (nfcAdapter != null) {
disableNFC();
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
if (Build.VERSION.SDK_INT >= 34 && getApplicationInfo().targetSdkVersion >= 34) {
this.registerReceiver(NFCReceiver, filter, Context.RECEIVER_EXPORTED);
} else {
this.registerReceiver(NFCReceiver, filter);
}
}
// Emit text zoom by plugin, ignore native scaling
WebSettings settings = bridge.getWebView().getSettings();
initialSystemFontScale = settings.getTextZoom() / 100.0f;
settings.setTextZoom(100);
settings.setSupportZoom(false);
View decorView = getWindow().getDecorView();
decorView.getViewTreeObserver().addOnWindowFocusChangeListener(hasFocus -> {
Log.d(TAG, "DecorView focus changed: hasFocus=" + hasFocus);
emitAppFocusEvent(hasFocus);
});
handleAppLink(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleAppLink(intent);
}
private void handleAppLink(Intent intent) {
String action = intent.getAction();
Uri data = intent.getData();
if (Intent.ACTION_VIEW.equals(action) && data != null) {
String url = data.toString();
if (url.contains("al_applink_data")) {
url = extractTargetUrlFromFacebookAppLink(url);
}
if (bridge != null) {
JSObject urlObject = new JSObject();
urlObject.put("url", url);
bridge.triggerWindowJSEvent("appUrlOpen", urlObject.toString());
Log.d(TAG, "Deep link processed: " + url);
}
}
}
private String extractTargetUrlFromFacebookAppLink(String appLinkUrl) {
try {
Uri uri = Uri.parse(appLinkUrl);
String alData = uri.getQueryParameter("al_applink_data");
if (alData != null) {
JSONObject json = new JSONObject(alData);
return json.optString("target_url", appLinkUrl);
}
} catch (Exception e) {
Log.e(TAG, "Error parsing Facebook App Link", e);
}
return appLinkUrl;
}
private void emitAppFocusEvent(boolean hasFocus) {
JSObject eventData = new JSObject();
eventData.put("hasFocus", hasFocus);
bridge.triggerWindowJSEvent("appFocusChanged", eventData.toString());
Log.d(TAG, "Emitted appFocusChanged event with hasFocus=" + hasFocus);
}
private final BroadcastReceiver NFCReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
final int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
NfcAdapter.STATE_OFF);
switch (state) {
case NfcAdapter.STATE_OFF:
case NfcAdapter.STATE_TURNING_OFF:
break;
case NfcAdapter.STATE_ON:
case NfcAdapter.STATE_TURNING_ON:
disableNFC();
break;
}
}
}
};
@Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(NFCReceiver);
}
private void disableNFC() {
nfcAdapter.enableReaderMode(this, null, NfcAdapter.STATE_OFF, null);
}
}
Assistant
Of course. After reviewing your MainActivity.java code, I can see a couple of issues, one of which is almost certainly the cause of your problem, and another which is a potential race condition that you should fix for reliability.
The app opens because your AndroidManifest.xml (which you haven't shared, but must be configured correctly for this to happen) is successfully catching the URL and launching MainActivity. The problem lies in how you are passing the URL data from the native Java code to your web view (JavaScript).
1. The Core Problem: Incorrectly Passing Data to JavaScript
The main issue is in this line within your handleAppLink method:
The bridge.triggerWindowJSEvent method expects a JSObject as its second parameter, not a String representation of that object.
When you call urlObject.toString(), you are converting the JSObject into a JSON string like "{"url":"https://your-link.com"}". Your JavaScript listener for the appUrlOpen event then receives this literal string, not a JavaScript object. When you try to access event.url in your JavaScript, it will be undefined because you're trying to access a property on a string.
The Fix
You should pass the JSObject directly.
java
private void handleAppLink(Intent intent) {
String action = intent.getAction();
Uri data = intent.getData();
if (Intent.ACTION_VIEW.equals(action) && data != null) {
String url = data.toString();
if (url.contains("al_applink_data")) {
url = extractTargetUrlFromFacebookAppLink(url);
}
if (bridge != null) {
JSObject urlObject = new JSObject();
urlObject.put("url", url);
// CORRECT: Pass the JSObject directly, not its string representation
bridge.triggerWindowJSEvent("appUrlOpen", urlObject);
Log.d(TAG, "Deep link processed: " + url);
}
}
}
With this change, your JavaScript listener will receive a proper object, and event.url (or however you access the payload) will contain the correct URL string.
javascript
// Example JavaScript listener
window.addEventListener('appUrlOpen', (event) => {
// Now, event.detail will be an object: { url: "https://your-link.com" }
const url = event.detail.url;
console.log('App opened with URL:', url);
// Now you can navigate to the correct page in your app
// e.g., router.push(new URL(url).pathname);
});
There is a classic race condition in your onCreate method.
java
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
super.onCreate(savedInstanceState);
// ...
handleAppLink(getIntent()); // <--- This can run too early
}
You call handleAppLink(getIntent()) immediately in onCreate. At this point, your web view might not have finished loading, and your JavaScript code (including the window.addEventListener for appUrlOpen) may not have executed yet.
If the deep link event is fired from native code before the JavaScript listener is ready, the event is lost. This is a very common problem.
The onNewIntent method is usually fine because it's called when the app is already running, so the JavaScript listeners are already in place. The problem is for a "cold start" (when the app is launched from a closed state by the deep link).
The Robust Solution using Capacitor's App Plugin
Capacitor provides a standard, robust way to handle this that avoids the race condition. The idea is to let the JavaScript "pull" the launch URL when it's ready, instead of having the native code "push" it immediately.
Step 1: Modify MainActivity.java
Remove the call to handleAppLink from onCreate. The Capacitor App plugin handles this for you. Your onNewIntent is still necessary for when the app is already open.
java
// In MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
registerPlugin(MtbPlugin.class);
registerPlugin(ZoomPlugin.class);
super.onCreate(savedInstanceState);
// ... (rest of your onCreate code like NFC, WebSettings, etc.) ...
// REMOVE THIS LINE
// handleAppLink(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// KEEP THIS! This is now the primary responsibility of this method.
// Capacitor's App plugin will automatically capture this and fire the 'appUrlOpen' event.
setIntent(intent);
}
Important: The default Capacitor BridgeActivity's onNewIntent already handles firing the appUrlOpen event. By calling super.onNewIntent(intent) and then setIntent(intent), you ensure the framework can correctly process it. You can actually remove your custom handleAppLink and onNewIntent override if all it does is fire this event, as Capacitor handles it by default.
If you stick with your custom handler, ensure setIntent(intent) is called inside onNewIntent so that subsequent calls to getIntent() within the activity's lifecycle get the new intent.
Step 2: Modify your JavaScript/TypeScript Code
In your main app component (e.g., App.vue, app.component.ts, etc.), use the official Capacitor App plugin.
Add a listener for appUrlOpen. This handles links that open while the app is already running.
Call App.getLaunchUrl() to get the URL that launched the app on a cold start.
typescript
// Example in a TypeScript project (e.g., Angular, React, Vue)
import { App } from '@capacitor/app';
import { Capacitor } from '@capacitor/core';
// This function should be called when your app initializes
const initializeDeepLinkHandler = () => {
// This listener will fire when the app is already open and a new deep link is used
App.addListener('appUrlOpen', (data) => {
console.log('App opened from deep link while running:', data.url);
// Navigate to the url, e.g., router.push(new URL(data.url).pathname)
handleRouting(data.url);
});
// This will check if the app was opened by a deep link on a "cold start"
if (Capacitor.isNativePlatform()) {
App.getLaunchUrl().then((data) => {
if (data && data.url) {
console.log('App launched with URL:', data.url);
handleRouting(data.url);
}
});
}
};
const handleRouting = (url: string) => {
// Your logic to parse the URL and navigate to the correct view/page
// For example:
// const path = new URL(url).pathname;
// router.push(path);
};
// Call the initialization function
initializeDeepLinkHandler();
Summary of Recommendations
Fix the Immediate Bug: Change bridge.triggerWindowJSEvent("appUrlOpen", urlObject.toString()); to bridge.triggerWindowJSEvent("appUrlOpen", urlObject);.
Implement the Robust Solution (Highly Recommended):
Remove the handleAppLink(getIntent()); call from onCreate.
Let the default Capacitor onNewIntent logic handle warm starts, or ensure your override calls super.onNewIntent(intent).
In your JavaScript, use App.addListener('appUrlOpen', ...) and App.getLaunchUrl() to reliably handle deep links on both warm and cold starts. This is the official, race-condition-free method.