title: When does passing an activity to another class cause memory leaks?
body: <p>In my Android Studio project I have an acitivty (<code>MainActivity</code>) and an object (<code>PurchasesHandler</code>). Inside the <code>onCreate</code> method of the activity, the PurchasesHandler gets instantiated like this:</p>
  
  <p><code>PurchasesHandler purchasesHandler = new PurchasesHandler(MainActivity.this, ...)</code></p>
  
  <p>From reading a lot of articles about memory leaks I know that one should be very cautious when passing an activity, since this can lead to memory leaks. But I guess that passing the activity does not necessarily lead to memory leaks, right?</p>
  
  <p>So let's go further and look into the <code>PurchasesHandler</code>. This handler contains a simple <code>AlertDialog</code> builder which looks like this:</p>
  
  <pre><code>private void showBillingResponseDialog(String title, String message) {
          AlertDialog.Builder builder = new AlertDialog.Builder(activity);
          builder
                  .setTitle(title)
                  .setMessage(message)
                  .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                          dialog.cancel();
                      }
                  })
                  .show();
      }
  </code></pre>
  
  <p>As you can see, I am referencing the activity in this method, but I guess that this also cannot lead to memory leaks, right? If so, can someone explain why? I find it intuitive that it is like that, but I cannot explain, why it is like that.</p>
  
  <p>So let's look at one more code snippet from the <code>PurchasesHandler</code>:</p>
  
  <pre><code>public void sampleMethod() {
          BillingClient billingClient = BillingClient.newBuilder(context)
                  .enablePendingPurchases()
                  .setListener(this) // Passes the onPurchasesUpdated listener of this class
                  .build();
  </code></pre>
  
  <p>In this code snippet I am setting a listener which references the <code>PurchasesHandler</code> itself (because of .setListener(<strong>this</strong>)). My guess would be now, that there exists a memory leak, since the listener holds a reference to the <code>PurchasesHandler</code> and the <code>PurchasesHandler</code> holds a reference to the activity. This would mean, that the activity cannot be deallocated/removed from the heap, right?</p>
  
  <p>If my assumptions are true, is there any nice way to get rid of the memory leak? I know that I should unregister listeners, but for the <code>BillingClient</code> there exists no unregister option. Only a <code>endConnection()</code> method, but this method sometimes doesn't work properly.</p>