Press back and Exit app in androird


If you getting trouble when pressing back don't exit app, then this article will help you. Here first time your will display toast message, please press again for exit app.

here is the full source code:

public class MainActivity extends Activity {
private static long back_pressed;
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

@Override
public void onBackPressed() {

if (back_pressed + 2000 > System.currentTimeMillis()){
// need to cancel the toast here
toast.cancel();
// code for exit
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{
toast = Toast.makeText(getBaseContext(), "Please click BACK again to exit", Toast.LENGTH_SHORT);
toast.show();
}
back_pressed = System.currentTimeMillis();
}

Output looks like:



Happ Coding!!
}
Press back and Exit app in androird Press back and Exit app in androird Reviewed by D Kshetri on 9:48 PM Rating: 5

No comments:

Powered by Blogger.