android开发:退出程序(对话框、两次返回键退出)

贴代码:

public void exitclick(View view)
    {
        AlertDialog.Builder aa=new AlertDialog.Builder(this); 
        aa.setTitle("消息提示");
        aa.setMessage("确认退出?"); 
        aa.setIcon(R.drawable.icon);
        aa.setPositiveButton("确定",new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                MainActivity.this.finish();
            }
        });
        aa.setNegativeButton("取消", null);
        aa.create(); 
        aa.show(); 

        //this.finish();
    }

感觉比C#的复杂呀。。。

还有就是按返回键提示退出,继续贴代码:

private void exitDialog()
    {
        AlertDialog.Builder aa=new AlertDialog.Builder(this); 
        aa.setTitle("消息提示");
        aa.setMessage("确认退出?"); 
        aa.setIcon(R.drawable.icon);
        aa.setPositiveButton("确定",new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                MainActivity.this.finish();
            }
        });
        aa.setNegativeButton("取消", null);
        aa.create(); 
        aa.show(); 
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
        exitDialog();
        }
        return true;
        
    }

现在还流行连续按两次返回退出,代码:

    private static boolean isExit=false;
    private static boolean hasTask=false;
    Timer tExit=new Timer();
    TimerTask task=new TimerTask() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            isExit=false;
            hasTask=true;
        }
    };


@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            //exitDialog();
            if(isExit==false)
            {
                isExit=true;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); 
                if(!hasTask) {
                    tExit.schedule(task, 2000);
                }
            }
            else
            {
                finish();
                System.exit(0);
            }
            
        }
        //return true;
        return false;
        
    }

 


你可能感兴趣的:(android开发:退出程序(对话框、两次返回键退出))