press back again to exit

    private static Boolean already_pressed_back = false;

    @Override
    public void onBackPressed() {
    	if (already_pressed_back) {
    		super.onBackPressed();
    		return;
    	}
    	already_pressed_back = true;
    	Toast.makeText(this, R.string.press_back_again_to_exit, Toast.LENGTH_SHORT).show();
    	new Handler().postDelayed(new Runnable() {
    		@Override
    		public void run() {
    			already_pressed_back = false;
    		}
    	}, 2000);
    }

– or –

    private static Boolean isExit = false;
    private static Boolean hasTask = false;
    Timer tExit = new Timer();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
    		if (isExit == false) {
    			isExit = true;
    			Toast.makeText(this, R.string.press_back_again_to_exit, Toast.LENGTH_SHORT).show();
    			if (!hasTask) {
    				tExit.schedule(new TimerTask() {
    			    	@Override
    			    	public void run() {
    			    		isExit = false;
    			    		hasTask = true;
    			    	}
    			    }, 2000);
    			}
    		} else {
    			finish();
    			System.exit(0);
    		}
    	}
    	return false;
    }
Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

w

Connecting to %s