3

I know this has been asked earlier here & here too.They are not answered properly (or not answered at all).But,i don't know why moveTaskToBack(true); always returns false for me .Can anyone tell me why and how could i solve the issue? Thanks in advance.

public void onBackPressed() {       
    boolean r=  moveTaskToBack(true);
    //r is false !! using API LEVEL 8
}

Note:The activity from which i am calling it is a child Activity included in a tabActivity and neither of this is a MAIN or LAUNCHER activity.I don't know if that makes a difference.

EDIT: and as a result the application does'nt go to background.I want it to go to background just as if the hardware HOME is pressed

Community
  • 1
  • 1
Nezam
  • 4,122
  • 3
  • 32
  • 49

3 Answers3

9

I don't know why moveTaskToBack(true) is returning false for you. Perhaps there's something weird in your manifest? At any rate, you can do this instead to bring up the home screen:

Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);

However, be aware of this message:

"You cannot simulate a press on the Home key." — Roman Guy, Android framework engineer

I'm not sure how that squares with my suggested code (which I found on the same thread as Roman's statement and seems to work).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • This is a very good generic way. Put this in my baseActivity. Thanks! – Grisgram Feb 27 '18 at 09:29
  • Interestingly, when I am in the situation where `moveTaskToBack(true)` returns false, this code does nothing. – androidguy Feb 25 '20 at 23:04
  • @androidguy - That is interesting. Do you know why `moveTaskToBack(true)` is returning false in the first place? Also, is there anything in the logs to indicate why my suggested code won't bring up the home screen? I would have thought that this would always work. – Ted Hopp Feb 26 '20 at 00:50
  • @TedHopp It is only on certain API levels such as M and maybe lower (not sure about L didn't check) when I return to task root activity with REORDER_TO_FRONT flag. It was "fixed" to work in this more unusual scenario in N seemingly. Just wanted to point this out in case someone tries to use it in the same scenario as me... – androidguy Feb 26 '20 at 02:23
1

Just write:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
    //  super.onBackPressed();
}
mkl
  • 90,588
  • 15
  • 125
  • 265
TanuPriya
  • 13
  • 1
  • 3
0

I came into the similar problem(a child Activity included in a tabActivity), when you call moveTaskToBack(true) in the child activity, it doesn't work, whereas it works in the parent activity. You can call moveTaskToBack(true) in child activity like this: ChildActivity.this.getParent().moveTaskToBack(true)

John
  • 99
  • 1
  • 4