Skip to content

Commit bff7d6e

Browse files
authored
chore: prevent memory leaks in Iap.java by using WeakReference for Context and Activity references
I used the Weak Reference passing the Context and Activity instead of the old Context and Activity directly, this is done to prevent memory leaks and unexpected closure if the context or activity become null
1 parent 6d6aeea commit bff7d6e

File tree

1 file changed

+7
-6
lines changed
  • src/plugins/iap/src/com/foxdebug/iap

1 file changed

+7
-6
lines changed

src/plugins/iap/src/com/foxdebug/iap/Iap.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.util.ArrayList;
2424
import java.util.Arrays;
2525
import java.util.List;
26+
import java.lang.ref.WeakReference;
2627
import org.apache.cordova.CallbackContext;
2728
import org.apache.cordova.CordovaInterface;
2829
import org.apache.cordova.CordovaPlugin;
@@ -35,14 +36,14 @@
3536
public class Iap extends CordovaPlugin {
3637

3738
private BillingClient billingClient;
38-
private Context context;
39-
private Activity activity;
39+
private WeakReference<Context> contextRef;
40+
private WeakReference<Activity> activityRef;
4041
private CallbackContext purchaseUpdated;
4142

4243
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
4344
super.initialize(cordova, webView);
44-
context = cordova.getContext();
45-
activity = cordova.getActivity();
45+
contextRef = new WeakReference<>(cordova.getContext());
46+
activityRef = new WeakReference<>(cordova.getActivity());
4647
billingClient = getBillingClient();
4748
}
4849

@@ -103,7 +104,7 @@ public void run() {
103104

104105
private BillingClient getBillingClient() {
105106
return BillingClient
106-
.newBuilder(this.context)
107+
.newBuilder(this.contextRef.get())
107108
.enablePendingPurchases()
108109
.setListener(
109110
new PurchasesUpdatedListener() {
@@ -248,7 +249,7 @@ private void purchase(String json, CallbackContext callbackContext) {
248249
try {
249250
SkuDetails skuDetails = new SkuDetails(json);
250251
BillingResult result = billingClient.launchBillingFlow(
251-
activity,
252+
activityRef.get(),
252253
BillingFlowParams.newBuilder().setSkuDetails(skuDetails).build()
253254
);
254255
int responseCode = result.getResponseCode();

0 commit comments

Comments
 (0)