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


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

Android java 移动app android-studio 移动应用开发

纯洁的腐女 10 years, 2 months ago

onbackpressed可以, http://tianmaying.com/snippet/8ab3eda84dd8bc9f014de5eab9bf036c
话说你确定有好多程序用到了双击退出?
哪个好点不好说 我一般用onbackpressed.

亿千万的妹抖 answered 10 years, 2 months ago

没那么麻烦,直接用toast的getView().getParent() 判断是不是空就ok了。API 16 测试通过


 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);
        }
    }
}

神偷魔理沙 answered 10 years, 2 months ago

Your Answer