amila isura amila isura - 4 months ago 32
Android Question

how to close app when i press back?

I'm installing my app then save data using Main Activity and going to another Fragment activity.Next time I'm starting my App always preview second Fragment then I press back going to Main Activity But I don't want to go Main Activity.I want press back button close My App.I try this

@Override
public void onResume() {
super.onResume();

getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
// handle back button's click listener
Toast.makeText(getActivity(), "Back press", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});

}

Answer

in your Mainactivity, after the line startActivity() for starting second activity add this line this.finish();