How to handle back button in activity
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);
}
Android - Back button in the title bar
There are two simple steps to create a back button in the title bar:
First, make the application icon clickable using the following code in the activity whose title bar you want to have a back button in:
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
After you have added the above code, you will see a back arrow appear to the left of the application icon.
Second, after you have done the above, you still have to create code that will take advantage of the click event. To do so, be aware that, when you actually click on the application icon, an onOptionsItemSelected
method is called. So to go back to the previous activity, add that method to your activity and put Intent
code in it that will return you to the previous activity. For example, let's say the activity you are trying to go back to is called MyActivity
. To go back to it, write the method as follows:
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MyActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
That's it!
(In the Android developers API, it recommends messing around with the manifest and adding stuff like android:parentActivityName
. But that doesn't seem to work for me. The above is simpler and more reliable.)
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
And in your Activity
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Handling Back button in Parent Activity
i am assuming you are using ActionBar.
Try adding this in your activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to leave? ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.show();
}
Android - How To Override the Back button so it doesn't Finish() my Activity?
Remove your key listener or return true
when you have KEY_BACK
.
You just need the following to catch the back key (Make sure not to call super in onBackPressed()
).
Also, if you plan on having a service run in the background, make sure to look at startForeground()
and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.
@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
Handling back button in Android Navigation Component
Newest Update - April 25th, 2019
New release androidx.activity ver. 1.0.0-alpha07 brings some changes
More explanations in android official guide: Provide custom back navigation
Example:
public class MyFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This callback will only be called when MyFragment is at least Started.
OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
@Override
public void handleOnBackPressed() {
// Handle the back button event
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
// The callback can be enabled or disabled here or in handleOnBackPressed()
}
...
}
Old Updates
UPD: April 3rd, 2019
Now its simplified. More info here
Example:
requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), this);
@Override
public boolean handleOnBackPressed() {
//Do your job here
//use next line if you just need navigate up
//NavHostFragment.findNavController(this).navigateUp();
//Log.e(getClass().getSimpleName(), "handleOnBackPressed");
return true;
}
Deprecated (since Version 1.0.0-alpha06
April 3rd, 2019) :
Since this, it can be implemented just using JetPack implementation OnBackPressedCallback
in your fragment
and add it to activity:getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
Your fragment should looks like this:
public MyFragment extends Fragment implements OnBackPressedCallback {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
}
@Override
public boolean handleOnBackPressed() {
//Do your job here
//use next line if you just need navigate up
//NavHostFragment.findNavController(this).navigateUp();
//Log.e(getClass().getSimpleName(), "handleOnBackPressed");
return true;
}
@Override
public void onDestroyView() {
super.onDestroyView();
getActivity().removeOnBackPressedCallback(this);
}
}
UPD:
Your activity should extends AppCompatActivity
or FragmentActivity
and in Gradle file:
implementation 'androidx.appcompat:appcompat:{lastVersion}'
App closed when pressing back button from activity results intent
After a lot of struggle I found that if we press back button with out selecting any file the activity results will returns null.
So we should check if activity results not equal to null and then do some operations.
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
if(uri!=null){
// Handle the returned Uri
}
}
});
Related Topics
How to Configure a Static Ip Address, Netmask, Gateway Programmatically on Android 3.X or 4.X
Image in Canvas with Touch Events
Sync Data Between Android App and Webserver
How to Play Videos in Android from Assets Folder or Raw Folder
How to Dynamically Set the Position of View in Android
Changing Screen Brightness Programmatically (As with the Power Widget)
Nullpointerexception:Println Needs a Message in Android
How to Deploy and Execute an Application on a Device Connected to a Remote System
How to Center Text Horizontally and Vertically in a Textview
Capturing Mobile Phone Traffic on Wireshark
Change Project Name on Android Studio
Overlay Two Images in Android to Set an Imageview
How to Send Data from One Fragment to Another Fragment
Android: Taking Complete Control of Phone(Kiosk Mode), Is It Possible? How
How to Startforeground() Without Showing Notification
Decimal Separator Comma (',') with Numberdecimal Inputtype in Edittext