title: android - How to close an activity on button click?
body: <p>I want a button click to close an Activity. I am new to intents and and a little confused.
  This is <code>ActivityOne</code> which keeps a track of life cycle. <br>On a button press, it opens <code>ActivityTwo</code> and puts <code>ActivityOne</code> in background.<br>
  This works fine when I used this intent in my <code>onClickListener</code>:  </p>
  
  <pre><code>Intent myIntent = new Intent(ActivityOne.this, ActivityTwo.class);
  ActivityOne.this.startActivity(myIntent);
  </code></pre>
  
  <p>In <code>ActivityTwo</code> I need to use intents and <code>finish()</code> method to close the activity. I tried to Google it and I thought this might work:</p>
  
  <pre><code>Intent myIntent2 = new Intent(getApplicationContext(), ActivityTwo.class);
  ActivityTwo.this.finish(myIntent2);
  </code></pre>
  
  <hr>
  
  <p>It didn't work the full code is below:</p>
  
  <pre><code>public class ActivityOne extends Activity {
  
      // ...
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_one);
  
          // ...
  
          Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo); 
          launchActivityTwoButton.setOnClickListener(new OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  // TODO:
                  // Launch Activity Two
                  // Hint: use Context's startActivity() method
  
                  // Create an intent stating which Activity you would like to start
                  Intent myIntent = new Intent(ActivityOne.this, ActivityTwo.class);
  
                  // Launch the Activity using the intent
                  ActivityOne.this.startActivity(myIntent);               
              }
          });
  
          // ...
      }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Activity 2:</strong></p>
  
  <pre><code>public class ActivityTwo extends Activity {    
  
      // ...
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_two);
  
          // ...
  
          Button closeButton = (Button) findViewById(R.id.bClose); 
          closeButton.setOnClickListener(new OnClickListener() {
  
              @Override
              public void onClick(View v) {
  
                  // TODO:
                  // This function closes Activity Two
                  // Hint: use Context's finish() method
                  Intent myIntent2 = new Intent(getApplicationContext(), ActivityTwo.class);
                  ActivityTwo.this.finish(myIntent2);
              }
          });
          // ...
      }
  }
  </code></pre>