Search code examples
androidandroid-activityactivity-finish

alternative to finish()


I read in the docs that one should avoid using finish() - but I don't really see a better alternative for this...

I just like to know, if there is a better, cleaner way to do this...

Many thanks

This is what I basically need to do:

MainActivity 
   -> Sub1Activity
      -> MySMSActivity
         -> send SMS
         -> handle if SMS was sent or not
            <- finish()
      <- finish()
(skip Sub1Activity)
MainActivity

The code in MainActivity:

this.myBtn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        doSub1Activity("xyz"); 
    }
});

public void doSub1Activity() {
    Intent i;
    i = new Intent(this, SUB1_screen.class);
    startActivity(i);
}

The code in Sub1Activity:

this.myBtn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
       doMySMSActivity("xxx"); 
       finish();         //<- this is the 1. call to "finish" I am concerned about
    }
public void doMySMSActivity() {
    Intent i;
    i = new Intent(this, MySMSActivity.class);
    startActivity(i);
    }

The code in MySMSActivity:

private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

        //---when the SMS has been sent---
        bRSMS_has_been_sent = new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {

                switch (getResultCode())
                {
                case Activity.RESULT_OK:
                    ...
                    break;
                default: 
                    break;
                }
                finish();  // another call to finish so the user continues with
                                       // MainActivity after SMS has been sent...
            }
        }; 

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }

Solution

  • You don't have to call finish() multiple times. If you need to return to the main activity simply start it using an intent with the flags below. That will reuse the activity if it already exists.

    Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP