Skip to content

Commit 486f3b0

Browse files
cmcewengrabbou
authored andcommitted
Prevent app from crashing when getCurrentActivity is null
Summary: We're seeing a lot of crashes from `PermissionsModule` not being able to access the current activity, mentioned in #10009 and here: #9310 (comment) As far as I can tell, there is no way to ensure the Activity exists since the `ReactContext` holds a `WeakReference` to the current Activity and it appears that the lifecycle calls are happening in the right order (so not the same as #9310). This will at least allow people to catch the error in JS and update the UI or try again as opposed to crashing the app. I'm working on some bigger changes in #10221 but this is a smaller change and important to get fixed I think. Closes #10351 Differential Revision: D4010242 fbshipit-source-id: 7a76973bb2b3e45817d4283917740c89a10ec0b0
1 parent 2958676 commit 486f3b0

1 file changed

Lines changed: 15 additions & 5 deletions

File tree

ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
@ReactModule(name = "PermissionsAndroid")
3232
public class PermissionsModule extends ReactContextBaseJavaModule implements PermissionListener {
3333

34+
private static final String ERROR_INVALID_ACTIVITY = "E_INVALID_ACTIVITY";
3435
private final SparseArray<Callback> mCallbacks;
3536
private int mRequestCode = 0;
3637

@@ -73,7 +74,11 @@ public void shouldShowRequestPermissionRationale(final String permission, final
7374
promise.resolve(false);
7475
return;
7576
}
76-
promise.resolve(getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission));
77+
try {
78+
promise.resolve(getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission));
79+
} catch (IllegalStateException e) {
80+
promise.reject(ERROR_INVALID_ACTIVITY, e);
81+
}
7782
}
7883

7984
/**
@@ -95,17 +100,22 @@ public void requestPermission(final String permission, final Promise promise) {
95100
return;
96101
}
97102

98-
mCallbacks.put(
103+
try {
104+
PermissionAwareActivity activity = getPermissionAwareActivity();
105+
106+
mCallbacks.put(
99107
mRequestCode, new Callback() {
100108
@Override
101109
public void invoke(Object... args) {
102110
promise.resolve(args[0].equals(PackageManager.PERMISSION_GRANTED));
103111
}
104112
});
105113

106-
PermissionAwareActivity activity = getPermissionAwareActivity();
107-
activity.requestPermissions(new String[]{permission}, mRequestCode, this);
108-
mRequestCode++;
114+
activity.requestPermissions(new String[]{permission}, mRequestCode, this);
115+
mRequestCode++;
116+
} catch (IllegalStateException e) {
117+
promise.reject(ERROR_INVALID_ACTIVITY, e);
118+
}
109119
}
110120

111121
/**

0 commit comments

Comments
 (0)