How to execute code when Home button is pressed? - android

I want to run code only when the home button (when the app is sent to background) is pressed. I tried using the lifecycle-method but the problem is that they also get executed when and other dialog/activity is started. I only want to check if the application is sent to background. How can I achieve that?

In onOptionsItemSelected(MenuItem item);, check to see if the item clicked is the home button:
EDIT:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}

Activity.onUserLeaveHint() fires on your activity when the Activity is going to be backgrounded as a result of user action, such as pressing the home button or switching apps.

Well since you are writing the code you can set some boolean flags when you start explicitly another acitivty, and check that when your activity goes through onPause()...
if they are false, it means someone else is pausing your activity.
Maybe not the most elegant solution but it will work if that is the only problem you have.

You could have a tracking system (basically a counter) to know when one of your activities is resumed and paused, thus allowing you to know if any of your activities is open.
This way you could know if your app is "open". but this would not apply only to the home button, but to the back button (last back to close your app) or even opening another app from the notification bar.

Android OS will kill your application to free resources, it wont stay in the background all the time. Use service if you want your app keep running in the background

If you want to do when the home button is pressed and the activity is going background, you can override this on the activity:
#Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
switch(keyCode)
{
case KeyEvent.KEYCODE_HOME:
//somthing you want to do
default:
return super.onKeyUp(keyCode, event);
}
}
I am using the KeyUp event because that's when the app goes backgroud, the user can do a longPress and I don't think you want to do the method when the app still open.

this is sort of a cheat answer, but i find it to be much more reliable.
one method that's always called when you press the home button is the surfacedestroyed method for any surfaceviews contained in any of the program's activities.
Putting the code you want to execute there, having the method point to another method you want to execute, or having the method trigger a flag that points to the method you want to execute will do the job.

Related

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

Android app exist when home button is pressed. Clicking app icon starts app over. I want it to just unpause

In my game, if a user hits the back button I pop up a dialog asking if they really want to quit. However, I can't do the same with the home button because there's no way to override it.
If the user knows the task manager trick they can hold down home and switch back to the app and not lose their place.
If they don't know the trick they'll just select the icon again which will start the application over from the main menu.
Is there any way to override this behavior so that instead of starting at the main menu it would go back to where it was if the app is currently running?
I know that I could save the state of everything when the app pauses and then programmatically reload everything and send them to where they were. I'd like to avoid having to do all that work if possible.
However, I can't do the same with the home button because there's no way to override it.
You can,actually,override the home button.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
//do your stuff
return true;
}
return super.onKeyDown(keyCode, event);
}
Is there any way to override this behavior so that instead of starting at the main menu it would go back to where it was if the app is currently running?
About this, your best bet is to override the onPause() method in every Activity. But there is no guarantee about it, because, the OS might choose to kill your application when the user navigates away from it(for resource requirements,maybe). So in such a case, your application will start off from the main menu, and you can't help it.

Starting an Activity from a service and do not want any key input

I'm starting an activity from a service, which displays some text.
Now if a user presses a key - say a back key, I would like that back button to be processed by any other app which may be running (not started by my service).
Is this possible? I have tried FLAG_NOT_FOCUSABLE, however, the back key is still not processed by any other app/ignored. Android, after some time keep giving a option for "Force Close" or 'Wait".
Any pointers will be helpful.
Just FYI, "whitepages" app does something like this - it shows a dialog window, however, doesn't process the back key.
Thanks.
I'm not sure if this is correct or not, but I've seen the same behavior in a few apps myself. I think they are using Toast messages to display the text. I'm not sure if a service can display Toast or not - you'll have to try... if not then you could also try having the Activity display the toast and immediately exit.
Only the currently running activity receives in the button pressed signal. All you can do is intercept the back button press by implementing:
onBackPressed()
On older devices this won't quite work and you'll need to do something like:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Do something here
return true;
}
return super.onKeyDown(keyCode, event);
}
As far as passing the button press to another activity, I'm not sure you can do that. What you could do is pass the activity an intent that could specify the back button was pressed. However, this assumes that the other activity is setup to deal with such an intent.

how to override backpress to not kill activity?

I would like to display some images when the application is opened for the first time. Or if its being reopened. I don't want the application to be killed when the user presses the back button, to go to the home screen. But instead keep it alive but still return to the home screen.
As Andro_Selva said, the back button finishes your activity; it doesn't kill the app.
If you want to accomplish something similar to pressing the home button (so your app is hidden, but the activity is still alive), you can do something like this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
It's a little different than pressing the home key, because it will only take you to last app you were in when you launched this app. So it won't necessarily take you back to the launcher. But this behavior will be closer to what the user expects when pressing back.
You may also want to put this in the Manifest under your root Activity :
android:alwaysRetainTaskState="true"
This will prevent Android's default behavior of finishing all your Activities if they have been idle for about half an hour.
add this to your activity
public void onBackPressed() {
//finish(); this is what would normally happen
}
This way you have the full control on the back key. As for the home key, you better not do anything to it. otherwise it could be a big problem if something goes wrong with your app, and the user wont be able to get out of it. Also if you look at how android works, when a home key is pressed, the app isn't killed, just paused, unless the system decides there is not enough memory to keep your app, in which case it will shut down.
how to override backpress to not kill activity?
I believe that you have not understood certain things here. When you press your back button it doesn't mean that you are killing your app. It means that you are finishing your activity and which also means that your app is running in the background. If you want to kill your activity you have to do one of these,
by calling System.exit(0);
Or by
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Or by manually getting into settings->manage applications->select your app->click on force stop
When you press your home key it means that your activity is paused or something like freezed and when you get to your app again, you can see your app resumed from where you left your app.

Home button listener

Using the setOnKeyListener I can able to listen for all physical buttons except Home and End button, is there any possibility to catch the action of Home button.
You may try this on Android 4.0+:
1. Register a BroadcastReceiver for Intent.ACTION_CLOSE_SYSTEM_DIALOGS.
2. Call Intent.getStringExtra("reason") to get the reason. Reasons are below:
"homekey" for home key pressed;
"assist" for home key long pressed;
You do not need to catch Home button. If user press Home and some other Activity comes to foreground, your app goes to background and onPause() is called in your current Activity. You may override that function to clean search string or anything you need.
UPDATE:
More clean solution is to use flag FLAG_ACTIVITY_NO_HISTORY when starting that critical activity. So, when your activity goes to background system will close it properly for you.
You want to use public boolean dispatchKeyEvent(KeyEvent event), as covered here: http://developer.android.com/reference/android/app/Activity.html#dispatchKeyEvent%28android.view.KeyEvent%29.
Use it like so:
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
// do whatever you want to do here, then return true if you handled the key code
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
mBackDown = true;
return true;
case KeyEvent.KEYCODE_HOME:
mHomeDown = true;
return true;
}
}
return super.dispatchKeyEvent(event); // let the default handling take care of it
}
Let me know if that works for you.
EDIT: not sure why this doesn't work for you, but without looking through the rest of your code it would be hard to tell what exactly is going on. However, for your task, what I would recommend is that you use the finishOnTaskLaunch manifest attribute, as described at http://developer.android.com/guide/topics/manifest/activity-element.html#finish: properly used (set it to true) this will make sure that if your Activity is relaunched it will shutdown any existing instance.
This is only possible if you modify the main android source code. Although this is not recommended for app purposes. But more geared towards hidden menus.
public static final int KEYCODE_HOME
Since: API Level 1
Key code constant: Home key. This key is handled by the framework and is never delivered to applications.
Constant Value: 3 (0x00000003)

Categories

Resources