Bring application to background and then to foreground
Asked Answered
P

2

6

What method should I use to move my app to background and then move it to foreground again? I tried using moveTaskToBack(true) and the activity is moved to background successfully but then I can't move it to foreground. I tried starting the activity again using startActivity() but with no success and there seems to be no method moveTaskToFront() or something similar.

Phoebephoebus answered 18/3, 2013 at 16:3 Comment(0)
S
13

Use moveTaskToBack() to move your app to the background.

To move it to the foreground, use the following code:

Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
startActivity(intent);

If you are trying to do this from a Service or BroadcastReceiver then you will need to do this before calling startActivity():

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Steak answered 18/3, 2013 at 16:22 Comment(3)
After Home button is pressed, it takes 5 seconds to bring the app back to foreground. How to make it fast and real time?Oneida
@Oneida You should probably open a new question as this is only tangentially related to my answer. Also, if you are trying to force your app to the foreground when the user puts it in the background, I would imagine that Android is adding the delay to prevent rogue apps from bothering the user. If I had an app that did that I would throw my phone out the window.Steak
No, sir. I don't want to bother any user at all. I want to make a kiosk exam browser which limits common button functionality.Oneida
C
0

Thanks it worked for me by adding following intent

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Coronation answered 8/6, 2016 at 3:40 Comment(1)
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!Wilford

© 2022 - 2024 — McMap. All rights reserved.