Home » Android » android – Not to destroy current activity on back button is pressed

android – Not to destroy current activity on back button is pressed

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have two activities, A and B. I have a button in A,when pressed starts a new intent to B.
However whenever I press the back button while in B, than click the button again is restarts Activity.I do not want to do that,I want it to resume Activity B.
Actually I am doing some networking in Activity B and I want to save unless the user wants to refresh.
How can I do it? Thanks in advance

How to&Answers:

Use

@Override
    public void onBackPressed(){
        moveTaskToBack(true);
    }

Hope, It must help you

Answer:

You need to Overrider the

onBackPressed

method and start there the activity like this:

@Override
    public void onBackPressed() {
    Intent intent = new Intent(this, activityA.class);
    startActivityForResult(intent, PICK_CONTACT_REQ);
}

Answer:

This sounds like you need to rethink your architecture. You say:

Actually I am doing some networking in Activity B and I want to save
unless the user wants to refresh.

If this is the case, you probably don’t want to do your networking in ActivityB. Maybe you should start a Service from ActivityB to do the networking. The service and the activity can communicate with each other so that the activity can keep the user up-to-date about the state of the networking. If the user presses BACK in ActivityB, it can finish (as usual) and return to ActivityA. In this case, the Service is still managing the networking. When the user again starts ActivityB (from ActivityA), the new instance of ActivityB can communicate with the service to see if there is any networking going on, and if so it can get the current status of that networking or start it or stop it or whatever.