Android - How to exit an app when user press the home button? - android

I want to know how to exit an app when user press the Home Button.
As far as i know that Home Button moves the running app in background and puts Launcher process in front.
I know i can use finish() but i don't know where i should call it because i have no idea which function is going to get a call when user will press the Home Key.
Thanks.

Depending on what you want to do, overriding onUserLeaveHint might be the best bet:
http://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()
This will let your app know that your app is being exited because the user chose to switch apps (Like by hitting the Home button or selecting a notification). This hint function will not be called if an incoming phone call (or similar) is causing your app to go to the background, as the user didn't initiate that action.

In my case,
I have many activities in application
so if I use 'onUserLeaveHint', 'onStop' or ...
It just catch activity transition.
So I put below code every activities.
And finally catch user's home button action.
first, you have singleton object
public class ActivityContext {
public static Context context = null;
}
and every activities,
#Override
protected void onStop(){ //onStop runs after New one's onResume
super.onStop();
if(ActivityContext.context==context) { //user home button out
AppStartEnd.sendAppEndData(context);
}
}
#Override
protected void onResume(){
super.onResume();
ActivityContext.context = YourActivity.this;
}
I hope this will help you

Related

Distinguish OnResume invoked when starting activity for the first time vs when back button is pressed

I have an activity that opens the browser. On the back press of the browser, the activity is invoked which needs to perform some operation. The problem is that onResume() of the activity is invoked for the first time when it is created and also when the back arrow is pressed from the browser. I want to perform a specific operations on the back press of the browser. This logic should not be executed for the first time the activity is created. Is there any way to distinguish the flows or other ways to handle the back press from the browser?
One way to do it is to make a Flag, say:
boolean isBrowserOpen = false;
public void openBrowser(){
startActivity(launchBrowserIntent);
isBrowserOpen = true;
}
public void onResume(){
if(isBrowserOpen){
isBrowserOpen = false;
// Your code here
}
}
It depends on what you really want to achieve
Edit:
To have more control of the browser's event, I suggest you should try to use in-app browser.
https://developer.android.com/guide/webapps/webview

What is the default implementation of onBackPressed() in Activity

I want to know the default implementation of onBackPressed() in Activity. How to deal with the Activity recover in the default implementation of onBackPressed()?.
The following is the issues I suffer from. I have a test Activity code like this:
public class MainActivity extends Activity {
public static boolean test = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this,"is "+test,Toast.LENGTH_LONG).show();
test = !test;
}
}
When I first enter the app, I get 'is false'. Then I click back button and get to the home screen. After that, when I enter the app, I get the Toast 'is true'. I think the onBackPressed() should kill my app when it gets back to the home screen, but It does not. This is my question.
If I override onBackPressed() like this
#Override
public void onBackPressed() {
// super.onBackPressed();
finish();
try {
android.os.Process.killProcess(android.os.Process.myPid());
} catch (Exception e) {
e.printStackTrace();
}
}
I always get the Toast 'is false' after I enter the app.
Can anyone explain this problem and tell me what the default implementation of onBackPressed()?
I'd like to know the flow process in onBackPressed() in detail. I have read some of the source code on onBackPressed(), but I couldn't understand it well.
Thanks in advance.
The default implementation of Activity's onBackPressed() probably won't tell you a lot about the actual Activity/application lifetime. You should dig much dipper to understand the internal Android (and Linux) "mechanics" on application/process killing.
What an application developer should know is that once an Activity is in background (Home button pressed, incoming call received etc., i.e. onPause() followed by onStop() have been invoked) its process may (similar to what you did with android.os.Process.killProcess(...)) or may NOT be killed. See Multitasking the Android Way by Dianne Hackborn for the reference.
As to finishing an Activity by pressing the back button, it does not mean its instance will be immediately killed and the memory garbage collected (see this answer). It just means a new instance of the Activity will be created next time you navigate back to it.
Regarding your code and the statement that
When I first enter the app, I get 'is false'. Then I click back button and get to the home screen. After that, when I enter the app, I get the Toast 'is true'. I think the onBackPressed() should kill my app when it gets back to the home screen, but It does not.
This is the case when the system didn't kill the process while the Activity were in background (again, it is not guaranteed). If it did, the Toast would have shown false.
In order to check that a new instance of MainActivity is created each time you press the back button and then navigate back to the app, I don't recommend to use a static variable, - it appears to be not that obvious (see, for instance, is it possible for Android VM to garbage collect static variables... or Are static fields open for garbage collection?).
Besides you're simply switching between true and false that might be confusing. Instead of using a static variable you might use a non-static one incrementing it, for example, or toast the hash code of the current Activity instance, like Toast.makeText(this,"is " + this.hashCode(), Toast.LENGTH_LONG).show(). By doing this the Activity lifecycle should act as per the documentation.
If I override onBackPressed() ... I always get the Toast 'is false' after I enter the app.
This is more or less similar to what if the system kills your app's process.
From the AOSP Activity class found here:
/**
* 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.
*/
public void onBackPressed() {
if (mActionBar != null && mActionBar.collapseActionView()) {
return;
}
if (!mFragments.getFragmentManager().popBackStackImmediate()) {
finishAfterTransition();
}
}
So basically when you call finish, the process is not actually destroyed. You can read more about that here. This means that the memory in your app isn't destroyed, so when you restart your app, the boolean value from before is remembered.
In the case of your overridden implementation, you are explicitly destroying the process, which will clear memory of your activity state, so when you restart the app, the boolean initialization will occur again.

Make App Launch Activity not be visible in application manage after back is pressed

Basicly, i have 3 activities in my app. call them A,B and Login, A and B shows the user very sensitive data. a legit flow has the form of launch->Login->A->B->A->B...->A->quit what i really want is that if for some reason the app got to the background ( by pressing back or home or whatever ) while it was still on A, or on B, then no metter what way the app relaunches ( or traced in some way including by the long home press menu ) it would not show A or B content. he can see either the login page content, or nothing at all.
noHistory is almost what i was looking for, but isnt a good solution since i want to allow intuative navigation from A to B and back to A. so how is it done?
Check out the "clearTaskOnLaunch" Activity attribute.
When the value is "true", every time users start the task again, they
are brought to its root activity regardless of what they were last
doing in the task and regardless of whether they used the Back or Home
button to leave it.
try the following pseudo:
public A extends Activity
{
boolean just_launched = true;
void onPause()
{
just_launched = false;
}
void onResume()
{
if (!just_launched)
finish();
}
}

How do I catch the home button click via a broadcast reciever or other technique and stop it?

I'm trying to build a screen-lock app. However, I'm experiencing a gaping hole in the system. The moment the user clicks/touches/presses the home button, the activity goes to the background. How do I prevent that? Is that possible?
I'd like a detailed explanation on how to do it.
No it is not possible to prevent activity goes to the background but you can catch event when you pressed home button so you can release resources or do any other stuff when activity goes to background.
you can override onStop method
#Override
protected void onStop() {
super.onStop();
}

Complete shutting down of Android app when any form of exiting is done i.e. using HOME, SWITCH and BACK button

I'm building an Android app specifically a log in page whereby I'd like the app to completely shut down the app if the user was to exit the log in page in any way i.e. using the SWITCH, HOME or BACK buttons.
The only time the app should not completely shut down should be when user successfully logs in i.e. when the custom created log in button or enter button is pressed.
I've been able to do successfully shut down the app but in shuts down even when the user successfully logs. It isn't meant to do this.
Below is my code for the complete shut down - I took over the onDestroy(), onBackPressed(), finish() and onStop() methods:
// Deal with back button
public void onBackPressed() {
System.runFinalizersOnExit(true);
System.exit(0);
}
// Deal with exiting of app
public void finish() {
System.runFinalizersOnExit(true);
System.exit(0);
}
// Deal with exiting of app
public void onDestroy() {
System.runFinalizersOnExit(true);
System.exit(0);
}
// Deal with exiting of app
public void onStop() {
System.runFinalizersOnExit(true);
System.exit(0);
}
DOES ANYONE HAVE ANY IDEAS REGARDING MY ISSUE
YOUR ASSISTANCE IS GREATLY APPRECIATED
Look here for an explanation of the onStop() method. I suppose you open another Activity when the user has successfully logged in, your Activity above becomes invisible and calls onStop() where you exit your app. So just don't override onStop().
The onStop() method is called each time your activity is made invisible: when your app goes to the background, when the screen is turned off, or when you switch to another activity.
Regardless, what you are trying to do is strongly discouraged.
See this forum thread (Dianne Hackborn being one of the lead developer of the Android Framework).
Force closing your app using System.exit(), Process.killProcess() and the likes has a strong risk of conflict with the Android application lifecycle, and can corrupt its saved state, leading to unexpected and unpleasant behaviors for your users.
A better way is to use the flags FLAG_ACTIVITY_SINGLE_TOP and FLAG_ACTIVITY_CLEAR_TOP when launching your login activity.
This should remove previous activities from application, which would be the same as starting a new application from a user point of view.
Just create a class member boolean mLoggedIn and set it to true when the custom created log in button or enter button is pressed.
Then
#Override
protected void onPause()
{
super.onPause();
if (!mLoggedIn)
{
finish();
}
}

Categories

Resources