APIcloud 按两次返回键退出程序,android按两次返回键退出程序

ApIcloud按两次返回键退出程序,代码如下:

function ExitApp() {
var ci = 0;
var time1, time2;
api.addEventListener({
name : 'keyback'
}, function(ret, err) {
if (ci == 0) {
time1 = new Date().getTime();
ci = 1;

 api.toast({msg:'再按一次返回键退出'});

} else if (ci == 1) {
time2 = new Date().getTime();
if (time2 - time1 < 3000) {
api.closeWidget({
id : api.appId,
retData : {
name : 'closeWidget'
},
silent : true
});
} else {
ci = 0;
 api.toast({msg:'再按一次返回键退出'});
}
}
});
}


android中按两次返回键退出程序代码如下:

int ci=0;
Date  time1 ,time2;
@Override//true 不退出  false 退出
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub

 
if(keyCode==KeyEvent.KEYCODE_BACK&&ci==0){
Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
time1=new Date();
ci=1;
return true;
}else if(keyCode==KeyEvent.KEYCODE_BACK&&ci==1){
time2=new Date();
if(time2.getTime()-time1.getTime()<3000){
finish();
return false;
}else{
Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
ci=0;
return true;
}
}

return super.onKeyDown(keyCode, event);
}

还有一种做法是:

    package com.example.clickexittest;  

    import android.app.Activity;  
    import android.os.Bundle;  
    import android.util.Log;  
    import android.view.KeyEvent;  
    import android.widget.Toast;  

    public class MainActivity extends Activity {  

        private static final String TAG = MainActivity.class.getSimpleName();  

        private long clickTime = 0; //记录第一次点击的时间  

        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  

        }  

        @Override  
        public boolean onKeyDown(int keyCode, KeyEvent event) {  
            if (keyCode == KeyEvent.KEYCODE_BACK) {  
                exit();  
                return true;  
            }  
            return super.onKeyDown(keyCode, event);  
        }  

        private void exit() {  
            if ((System.currentTimeMillis() - clickTime) > 2000) {  
                Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",  
                        Toast.LENGTH_SHORT).show();  
                clickTime = System.currentTimeMillis();  
            } else {  
                Log.e(TAG, "exit application");  
                this.finish();  
    //          System.exit(0);  
            }  
        }  
    }

判断用户两次按键的时间差是否在一个预期值之内,是的话直接直接退出,不是的话提示用户再按一次后退键退出。


你可能感兴趣的:(APICloud,android,按两次返回键退出程序)