Skip to content Skip to sidebar Skip to footer

How To Work With Onbackpressed() In Android?

I have Activity 'A', Activity 'B', Activity 'C', Activity 'D', Activity 'E', Activity 'E' . I want to exit the Activity click on onBackPressed(). When i run the app it goes to Act

Solution 1:

You can try this in onBackPressed:

@OverridepublicvoidonBackPressed() {
    // TODO Auto-generated method stubIntentintent=newIntent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

Which exits the application. And works fine for me. Hope it helps.

Solution 2:

call this.finish() while you open your new activity(i.e going from activty A to some other activity). In your case write this

publicvoidonClick(View v){
                // TODO Auto-generated method stub
                Intent i = newIntent(MainActivity.this, Employee_List.class);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                MainActivity.this.finish();
            }
        });

Solution 3:

You can do something like this -

private exit = false;
publicvoidonBackPressed() {
    if (exit)
        Home.this.finish();
    else {
        Toast.makeText(this, "Press Back again to Exit.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            publicvoidrun() {
                exit = false;
            }
        }, 3 * 1000);

    }

}

Post a Comment for "How To Work With Onbackpressed() In Android?"