How-to Keep an Android Activity Running when hitting the back key - android

I have an activity that essentially launches a CountDownTimer. I need this to continue running while using other Android apps, such as Gmail, and media players etc.
When I hit the back button, my Activity seems to quit. What do I need to do to keep it running when the user clicks the back/home keys etc.

You have to use a Service, you can read the documentation here.

Activities are not supposed to be doing anything when they are not visible. They are basically UI components.
You should be looking into services. These can run as a background process nd contain no UI.

It's been referred to as a serious "hack" by a few developers, but I've successfully checked for the back button being pressed so as to successfully clean my project up. I've recently moved most of this code to onPause() event because it's called right before the app goes down after back button is pressed. However, if it's really what you desire, it's your program and here's the code I used:
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
killAndReturnParams(0);
}
Again, this method has been talked down before, but I'm pretty sure it's because you're not supposed to override the back button for any reason. The user is supposed to be able to use the back button to return at any point, in any app.

#Override
public void onBackPressed() {
mActivity.moveTaskToBack(true);
}

Related

Disable Back Button (onBackPressed)

I want to disable back button from closing the app.
How can i disable back button?
You can override the onBackPressed() method and determine what happens in that method. Like this:
#Override
public void onBackPressed() {
// do nothing because you don't want them to leave when it's pressed
}
Just add that method to your activity class and you're good to go.
However, this is bad app design. What you would most likely want to do is make a dialog pop up that asks them if they are sure they want to leave. You would add the dialog code inside that method so that when the back button is pressed, the dialog pops up.
Generally, that's not a good idea. Users hate to feel "trapped" in your app.
Many users are able to start apps "on top of" other apps. When they hit "back" they may expect your app to stop, and the app they were in previously to appear. This is different from "home" where they expect all apps to go to the background.
Users familiar and comfortable with this functionality will not like it if you change "back" - although you may give them options like "press back again to exit" as some apps do. It depends on your particular situation.
So if you are in need of it, here is a good reference:
Android - How To Override the "Back" button so it doesn't Finish() my Activity?

Method before home button [duplicate]

This question already has answers here:
Run code when Android app is closed/sent to background
(8 answers)
Closed 3 years ago.
My android application is a client, and when someone click the home button, I want to send a message to the server, and when the user changes back to the application, I also want to send a message to the server. If I could overwrite the HOME button keyEvent, or any method which will be called only when the application will be put into background, I could send message and set a static variable in a singleton which will be checked every onStart(), so basically I just need to somehow "override" the HOME button.
I tried the followings:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
//...
return true;
}
return super.onKeyDown(keyCode, event);
}
It does simply not work. I put a breakpoint in it, but HOME button doesn't trigger this method at all. (Samsung Galaxy Ace, android 2.2.1).
I also tried to overrite the onUserLeaveHint() like this:
#Override
protected void onUserLeaveHint() {
//...
super.onUserLeaveHint();
}
But the problem is, this method will be called not only when I press HOME button or the application is interrupted, but when I just navigate to an other activity (and finish the current one).
Are there any solution to this problem?
Might want to take a look at this Android Docs
You are looking for onPause / onResume, based on the line
or any method which will be called only when the application will be
put into background
That doc should explain how the stack works, which will allow you to accomplish this problem.
There is not an day solution to this problem, because android does not let you override the home button. The easiest way around this is to pur your code in onPause, but of course this can be called without the home button being pressed.
The second (not accepted) answer here has an interesting solution, but I have not tried it so I am not sure if it works

In my own custom android home screen, how do I catch the home button?

I know that android does not allow us to catch the home button press; however, I have my own built home screen replacement app and want to just know when the button was pressed to allow animations.
So, my app has just one activity as I do most of my "activities" as canvas drawing so I can have complete control over the visual aesthetics of my app. The problem is if the user navigates to a different page within the app and presses home, nothing happens, since the app is technically already in the same activity.
I want to know when the button is pressed so I can then animate/navigate my app back to the main screen. Also, I know I could accomplish this by having separate real activities however that won't work for what I'm trying to do.
You need to add <category android:name="android.intent.category.HOME"/> to your activity's intent filter in your app's Android.xml
You can take a look at "Home" app in Android SDK samples. They can be downloaded using these instructions.
//overriding method
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
//The Code Want to Perform.
}
});
You can detect when the home button is pressed because onPause() is always called. You are not allowed to override the home button, but the following should work
#Override
protected void onPause()
{
super.onPause();
//code here
}
Of course the problem with using this is that it will be called even if the user is not quitting the app(ie. If they are sent to another application through an intent)
That is the closest that you are going to get to a onHomeButtonPressedListener there are really no ways to do this
Home key press Event Listener

What event does the Kindle's"Home" button kick off?

The Kindle Fire has a bar at the bottom that includes a "home" button and a "back" button.
When I click the "back" button, my app's "onPause()" event is invoked.
When I click the "home" button, my app crashes. An Android dialog box is displayed. It says my app has stopped unexpectedly. I am presented with a "force close" button.
Sooooo what event do I need to be handling to prevent this. This only happens on my app, not the ones I downloaded, so yeah, it's me, lol.
Edit
As per this web page, I added events and toasts to the app just to gain some insight into how things work. When I click the Back button, I see the toasts produced by the onPause(), onStop(), and onDestroy() methods. When I click the Home button, there are no toasts, just the crash.
RESOLUTION
Akhil suggested I look at the logcat. I don't run the emulator since my machine seems understrength for Android development (or perhaps I expect too much from the emulator); it takes forever to start it up. Anyway, after figuring out how to run the emulator (and look at the logcat for the first time, ha) I saw that I was throwing an exception related to serialization. I'm off to solve it now. Thanks Akhil for the kick in the right direction!
Ah, and the emulator did display the onPause() toast when I clicked Home, so reality is still functioning as expected.
FINAL
The error was related to the serialization I added to make the onSaveInstanceState(Bundle savedInstanceState) method work. Basically, my app (and old game I converted to android) wasn't serializable, therefore this code in onSavedInstanceState() would not compile:
savedInstanceState.putSerializable(GAME, game);
'game' is innocuous, so I added "implements Serializable" to Game's class definition. However, I neglected to add the same to a private class within Game. This is what was causing the exception.
When you click the "back" button, your app's "onPause(), onStop(),onDestroy()" events will be invoked.When you click the "home" button, your app's "onPause(), onStop()," events will be invoked. ( This is a general scenario, assuming)
Put log statements in your onPause(), onStop() and see where you are getting the error.
Home Button cannot be intercepted in android due to security flaws.One option available is to overrride the onStop which is called when you press the home button and the app closes:-
#Override
protected void onStop()
{
super.onStop();
//do whatever you want here
}

Does pressing Back always cause Activity to finish()?

I've heard that pressing the back button will essentially cause the current Activity to finish(). Is this always the case? Seems like it would be with the way it pops the Activity off the stack.
The one situation I'm not so sure about is when the root Activity in a Task has back pressed. I'm currently experiencing a very weird effect, described as follows:
On loading my application, the first Activity is for initialization, and once it finishes, it calls my main Activity (a TabActivity). This first init activity has android:noHistory="true" set in the Manifest so pressing Back from my main Activity won't go back to that. It goes to the Launcher. When I click on my App in the Launcher a second time, the initialization activity loads again, and loads the main Activity when done. Almost immediately after, it loads a second instance of my main Activity. But ONLY after the Application has already been run once, and was exited by pressing BACK from the main Activity. It does it every subsequent time until I force quit the app or load a new version from the IDE.
Based on this, I am suspecting some kind of Activity instance is lying around and being reused, since it only happens on the second+ time I run the application (and exit with BACK -- using HOME just returns to the last state of the app, no big deal). Anyone have any thoughts??
I've heard that pressing the back button will essentially cause the current Activity to finish(). Is this always the case?
No it is not. The most activities have this behaviour but not all. For example you could create a Dialog and set it setCancelable(false) and it won't close if you click BACK button.
Furthermore you could customize activity behaviour on BACK button pressed by overriding onBackPressed
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
About your application behaviour..Did you verify if the activity launcher is finished after it loads your main activity? I mean if the onDestroy() method is called. Maybe after it runs the main activity it remains there and when you click back you just go back to the old Launcher...
hope this helps..
Read through the Activity and Task design guidelines on the Android developer site; they explain how the Home and Back buttons work. Obviously, if you override the default behavior (as mentioned by hara above), the back button will not finish the activity.
On your specific issue, check your logcat. You should be able to see there whether it is bringing an old process back to life or starting up a new one. If that is unclear, insert a couple of log statements into onCreate, onPause, onDestroyed, etc., so that you can see exactly what is happening with your process.
You can control BACK-BUTTON by writing the following code.
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK ) {
//preventing default implementation previous to
//android.os.Build.VERSION_CODES.ECLAIR
return false;
}
return super.onKeyDown(keyCode, event);
}
Are you running your activities with any special flags, such as singleInstance or singleTop? Those could be causing the oddities you're seeing. The easiest way to track down what's causing your problem is to absolutely fill it with debugging messages. For example:
In your initialisation activity, add a log in the beginning of onCreate to get the name of the activity such as this.toString(). More on why you want this line later.
When it launches the main tabbed activity, get the name of the launching activity and a message saying it's launched the tabbed one.
Override the onPause(), onStop() and onDestroy() callbacks and add debugging lines with this.toString() and also a message telling you which callback it is.
What this will do is tell you whether you've got multiple instances of the initialisation activity lying around. To this by comparing the name of the activities calling your main activity with the ones that were just created and the ones that went through to onDestroy.
If you don't know how to debug, use Log.d(LOG_TAG, "Your message here");. And then define a constant LOG_TAG String somewhere. After that, show the LogCat perspective in Eclispe by going to Window, show perspective (or view, don't remember exactly), other, Android, LogCat. The purpose of having a LOG_TAG constant is that you can set up LogCat to filter to that String and only show you those messages. It will make it easier to see them among the mass of system log messages.
The short answer to the original question is 'no'. This is largely because, unfortunately, not every developer follows the guidelines referenced by previous answers.
Yet the guidleines themselves mention exceptions, when the Back key should not call finish(). the most prominent exception is the Web browser, which has its own "back stack" for each window, so it must have its own custom handling of the Back key.
If there are no fragments on the back stack and a developer has not overridden onBackPressed, the activity will finish when the back button is pressed.
Here is the source code for Android 4.4.2 Activity.onBackPressed():
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
just override onbackpressed().. on back press this method will get execute remove super and do what u want to do.

Categories

Resources