how to override backpress to not kill activity? - android

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.

Related

How to execute code when Home button is pressed?

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.

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.

Overriding the Home button - how do I get rid of the choice?

When creating one Intent so that MyActivity reacts to a User pressing the Home-button is easy using the XML markup:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
I want to know how to avoid getting the choice of "what activity do you want to use" for the Home screen? HTC has made its "Touch Flo" (Sense) override the default "start" Activity and I never get the question if I want to use "Start" or "TouchFlo" usually. However, when I added my own Activity I always get the question.
Yes, I know that I can check the "Use this as standard"-checkbox, but that's not what I want right now. So, question is: can I make the system override everything else and always use MyActivity as default?
Next, I really only want to override the normal Home Screen when my app is running. If its not running, everything should work as normal, ie MyActivity should NOT be associated with the Home button.
You can't permanently override the Home button without the user confirming it.
One argument for why this is the case is a security one. The Home button is the one way a user can be guaranteed to exit any application. If you could make the Home button launch your application instead of the Home screen without the user confirming this change, it would then be very easy to write a malicious application that hijacked a user's phone.
Alternatively, your application could contain a replicate Home Screen that harvested a user's Google account details; not that hard since the source is available. If your application could silently replace the default Home Screen, it would be hard for the user to tell this had happened.
Also, do you really want to override Home? Home is like an emergency escape button. Pressing Home twice will always take a user back to the center panel of the Home Screen, so whatever application they're running, it's easy for a user to get back to somewhere they know. You shouldn't really be overriding this unless you're producing a full Home replacement.
#Override
public void onAttachedToWindow()
{
Log.i("TESTE", "onAttachedToWindow");
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
With this method, the HOME Button stops working in this activity (only this activity). Then you just reimplement as it was a normal button event (the back button for instance).
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
Log.i("TESTE", "BOTAO HOME");
return true;
}
return super.onKeyDown(keyCode, event);
}
The overridable onUserLeaveHint() lifecycle hook can be used when the user presses the home button.
This hook has been present since API level 3.
#Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
// Your code here
}
More info about the method:
Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice.
For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted.
In cases when it is invoked, this method is called right before the activity's onPause() callback.
Source: https://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()
Well, the user would still have to choose the regular home as their home with use as default checked to stop the prompt from coming back. However, I believe it is possible for you to then modify the system settings in some way to incidentally have your particular activity be considered the default home, such that press of home would then do nothing or appear locked to the user at the main activity, and I understand you wish to launch your user into other activities from there, giving them a fast home press return to this root Launcher. I can see the benefit of this completely, and it may even benefit what I'm developing if I choose to implement multiple widget screens that the user can flip left or right between.
There is at least 1 app out there that I've downloaded which appears to be doing exactly this. When the user exits the app, it restores the user's regular default home preference. The app instructs the users very explicitly to choose Launcher as their default home and never do that with the app itself. It has a few different "exit" methods which give the user the choice of which home to return to if they have multiple, and one that just exits to their regular default.
I am researching this as well and will report back with progress & source.
Use onUserLeaveHint().
onUserLeaveHint() is a protected method as other lifecycle methods of the activity and if you are handling onUserLeaveHint this will take care of the following case
When User hits home key
When User hits back key
When User hits annunciator bar
Here you can catch Homeb button click.

Categories

Resources