Skip to content

Commit 49786f6

Browse files
authored
Merge pull request #1040 from ThDev-only/main
Refactor Iap.java: Use WeakReference for Context and Activity to prevent memory leaks
2 parents 413c430 + bff7d6e commit 49786f6

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)