Android java back button

How to handle back button in activity

How to handle a back button in an activity? I have some buttons. If I click one of the buttons, it’s redirecting to the buttons which I required. It’s working fine but when I press back button it gets finished. How to solve this problem? I have only one activity for all those buttons.

@Override public boolean onKeyDown(int keyCode, KeyEvent event) < if ((keyCode == KeyEvent.KEYCODE_BACK)) < return false; //I have tried here true also >return super.onKeyDown(keyCode, event); > 

I have used above code to handle back button but it’s not working. When I press back button its struck there itself.

9 Answers 9

You can handle it like this:

for API level 5 and greater

@Override public void onBackPressed() < // your code. >

older than API 5

@Override public boolean onKeyDown(int keyCode, KeyEvent event) < if (keyCode == KeyEvent.KEYCODE_BACK) < // your code return true; >return super.onKeyDown(keyCode, event); > 

In addition to the above I personally recommend

Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*

This remains true for all development platforms.

Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.

public boolean onKeyDown(int keyCode, KeyEvent event) < if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) < event.startTracking(); return true; >return super.onKeyDown(keyCode, event); > public boolean onKeyUp(int keyCode, KeyEvent event) < if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() && !event.isCanceled()) < // *** Your Code *** return true; >return super.onKeyUp(keyCode, event); > 

Источник

Add back button to action bar

enter image description here

I have been trying to add a back button to the action bar. I want my view to look like this: I want to add the back button in the left of the action bar. I added this code

ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); 

The screenshot is of an iPhone. Android does not run on such devices. Android has its own back button, always available for the user; you do not need to put one in the action bar.

Many apps today (2014) put a back/up button in the actionbar (eg. Instagram) so I even if this is an antipattern.. It is clearly a need in users (maybe users going from iPhone see more benefit on this)

11 Answers 11

After setting actionBar.setHomeButtonEnabled(true);

@Override public boolean onOptionsItemSelected(MenuItem item) < switch (item.getItemId()) < case android.R.id.home: // app icon in action bar clicked; goto parent activity. this.finish(); return true; default: return super.onOptionsItemSelected(item); >> 

That’s a bit cavalier, you have to test that menuItem == android.R.id.home before taking that action (usually in a switch statement along with other options for that activity or fragment). For API >= 16, you can also simply define the parent activity in the manifest

actionBar.setHomeButtonEnabled(true); 

and then add the following

@Override public boolean onOptionsItemSelected(MenuItem menuItem) < switch (menuItem.getItemId()) < case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(menuItem); >> 

As suggested by naXa I’ve added a check on the itemId , to have it work correctly in case there are multiple buttons on the action bar.

Читайте также:  What is jsonarray in java

I mean, if there are other options in menu (for example, Help) they will be handled by onOptionsItemSelected() too, so we need to check menuItem.getItemId() == android.R.id.home

@Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_your_activity); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // . other stuff >@Override public boolean onSupportNavigateUp()

The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.

 actionBar.setHomeButtonEnabled(true); 

You have to configure the parent activity in your AndroidManifest.xml

I suspect this will not work if your child activity has more than one parent activity. i.e. more than one activity has the ability to navigate to the child activity.

There are two ways to approach this.

Option 1: Update the Android Manifest If the settings Activity is always called from the same activity, you can make the relationship in the Android Manifest. Android will automagically show the ‘back’ button in the ActionBar

Option 2: Change a setting for the ActionBar If you don’t know which Activity will call the Settings Activity, you can create it like this. First in your activity that extends ActionBarActivity (Make sure your @imports match the level of compatibility you are looking for).

@Override protected void onCreate(Bundle savedInstanceState)

Then, detect the ‘back button’ press and tell Android to close the currently open Activity.

@Override public boolean onOptionsItemSelected(MenuItem item) < switch (item.getItemId()) < case android.R.id.home: // app icon in action bar clicked; goto parent activity. this.finish(); return true; default: return super.onOptionsItemSelected(item); >> 

Источник

How to press back button in android programmatically?

In my app I have a logout functionality. If user clicks logout it goes to home screen. Now I am exiting my app by pressing back button. But what I want is I need to exit automatically(i.e Programmatically) as same like as back button functionality. I know by calling finish() will do the functionality. But the thing is it goes to the previous activity.

@Tarun I am using this code to clear all the history ExitActivity.this.finish(); Intent intent1 = new Intent(ExitActivity.this,PinActivity.class); intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1);

8 Answers 8

onBackPressed() is supported since: API Level 5

@Override public boolean onKeyDown(int keyCode, KeyEvent event) < if ((keyCode == KeyEvent.KEYCODE_BACK)) < onBackPressed(); >> @Override public void onBackPressed() < //this is only needed if you have specific things //that you want to do when the user presses the back button. /* your specific things. */ super.onBackPressed(); >

What is the point of this? you are writing what android does by default. It calls onBackPressed() when back button is pressed. am I right?

@KKD if you have to support API below 5 then you have to use like above.. android-developers.blogspot.co.uk/2009/12/…

Thanks for your comment i am not using back button.. I am using a logout button.. when user clicks it populate dialog asking yes or no.. if yes it goes to the home screen where i have to exit automatically but i stuck there. This is need because i am using alarm functionality in my app.. when ever the alarm popup the message the home screen coming background of it.. So i need to remove it thats what i am trying.

You don’t need to override onBackPressed() — it’s already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed() whenever you want to «programatically press» the back button.

Читайте также:  Javascript save xml file

That would only result to finish() being called, though 😉

I think you’re confused with what the back button does. By default, it’s just a call to finish() , so it just exits the current activity. If you have something behind that activity, that screen will show.

What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won’t be there when you exit yours.

Источник

Override back button to act like home button

On pressing the back button, I’d like my application to go into the stopped state, rather than the destroyed state. In the Android docs it states:

. not all activities have the behavior that they are destroyed when BACK is pressed. When the user starts playing music in the Music application and then presses BACK, the application overrides the normal back behavior, preventing the player activity from being destroyed, and continues playing music, even though its activity is no longer visible

@Override public boolean onKeyDown(int keyCode, KeyEvent event) < if ((keyCode == KeyEvent.KEYCODE_BACK)) < Log.d(this.getClass().getName(), "back button pressed"); >return super.onKeyDown(keyCode, event); > 

Edit: I know about services and am using one in the application to which this problem is related. This question is specifically about putting the Activity into the stopped state rather than the destroyed state on pressing the back button.

10 Answers 10

Most of the time you need to create a Service to perform something in the background, and your visible Activity simply controls this Service . (I’m sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that’s the case, then your Activity can finish as usual and the Service will still be running.

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

// 2.0 and above @Override public void onBackPressed() < moveTaskToBack(true); >// Before 2.0 @Override public boolean onKeyDown(int keyCode, KeyEvent event) < if (keyCode == KeyEvent.KEYCODE_BACK) < moveTaskToBack(true); return true; >return super.onKeyDown(keyCode, event); > 

I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack can be used as a quick alternative on occasion.

NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button.

moveTaskToBack() appears to work as desired. What might the downsides be to using this method? Are there cases where this might not work as expected?

After reading its doc more carefully, I actually think it should work fine. (I initially thought it applied to the activity, but in fact it says the «task containing this activity».) But you should test it for yourself of course. 🙂

Thanks Mirko, the method appears to work well. It might be cool if you give more prominence to your edit at the bottom of your answer for those looking at this question later — as that was the bit I was looking for!

Читайте также:  Python среднее арифметическое четных элементов

Please read android-developers.blogspot.com/2009/12/… for the recommended way to handle the back key.

@bdls in theory your background activity could be killed by the system if it runs low on resources, so to be safe it should be able to recreate itself anyway. I had a look at the source code for the Android Music app and don’t see any special back button handling.

public void onBackPressed()

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service . The documentation says the following about Services:

A service doesn’t have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

try to override void onBackPressed() defined in android.app.Activity class.

if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works

@Override public void onBackPressed() < // check if page 2 is open RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout); if(page2layout.getVisibility() == View.VISIBLE)< togglePageLayout(); // my method to toggle the views return; >else < super.onBackPressed(); // allows standard use of backbutton for page 1 >> 

hope it helps someone, cheers

Make sure don’t call super.onBackPressed();

@Override public void onBackPressed()

In this way your Back Button act like Home button . It doesn’t finishes your activity but take it to background

Second way is to call moveTaskToBack(true); in onBackPressed and be sure to remove super.onBackPressed

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A’s onPause() returns, so be sure to enter code here not do anything lengthy here.

This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.

This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.

Источник

Оцените статью