To stop an activity from another activity in Java, you can use the finish
method of the Activity
class.
Here's an example of how you can do this:
public class MyActivity extends Activity { public void stopActivityExample() { Intent intent = new Intent(this, ExampleActivity.class); startActivity(intent); finish(); } }
This code will start the ExampleActivity
activity and then immediately stop the current activity using the finish
method.
Alternatively, you can use the setResult
method to set a result code for the activity and then call the finish
method to stop the activity. This approach is useful if you want to pass data back to the calling activity when the activity finishes.
Here's an example of how you can do this:
public class MyActivity extends Activity { public void stopActivityExample() { Intent intent = new Intent(this, ExampleActivity.class); startActivityForResult(intent, REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { // Handle the result data } else { setResult(RESULT_CANCELED); finish(); } } }
This code will start the ExampleActivity
activity and wait for a result to be returned. If the result is RESULT_OK
, the current activity will continue running. If the result is any other value, the current activity will be stopped using the finish
method.
Note that calling the finish
method will cause the activity to be destroyed and removed from the activity stack, so it will not be possible to return to the activity using the "back" button.