search

Home  >  Q&A  >  body text

java - Android关于双击退出应用的问题

好多程序返回到第一个activity的时候,再按back会弹出吐司提示双击退出程序
在网上查了一下发现都是用keycode来实现的,用onBackPressed能实现同样的效果吗?
两种哪种方式好一点?用java计时器和handle延时发送两种之间哪个好一点?

ringa_leeringa_lee2767 days ago390

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 14:20:18

    It’s not that troublesome, just use toast’s getView().getParent() to determine whether it is empty. API 16 test passed

    public class MainActivity extends Activity {
    
    
        private Toast toast;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            toast = Toast.makeText(getApplicationContext(), "确定退出?", 0);
    
        }
        public void onBackPressed() {
            quitToast();
        }
        /*
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            System.out.println(keyCode + "...." + event.getKeyCode());
            if(keyCode == KeyEvent.KEYCODE_BACK){
                quitToast();
            }
            return super.onKeyDown(keyCode, event);
        }
        */
        private void quitToast() {
            if(null == toast.getView().getParent()){
                toast.show();
            }else{
                System.exit(0);
            }
        }
    }
    

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:20:18

    onbackpressed is OK, http://tianmaying.com/snippet/8ab3eda84dd8bc9f014de5eab9bf036c
    By the way, are you sure there are many programs that use double-click to exit?
    I can’t say which one is better. I usually use onbackpressed.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:20:18

    /* 上一次按返回按键的时间 */
    long preBackPressTime;
    /* 按返回按键的次数 */
    long pressTimes;
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        long cBackPressTime = SystemClock.uptimeMillis();
        if (cBackPressTime - preBackPressTime < 2000) {
            pressTimes++;
            if (pressTimes >= 2) {
                finish();
            }
        } else {
            pressTimes = 1;
        }
        if (pressTimes == 1) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
        }
        preBackPressTime = cBackPressTime;
    }

    reply
    0
  • Cancelreply