android的activity再按一次退出程序

package com.example.mylight;


import android.app.Activity;


import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.Toast;


public class BaseActivity extends Activity{
private long exitTime=0;
//protected的属性 让子类使用
//开和关状态的图片
protected ImageView mImageViewFlashlight;
//热区
protected ImageView mImageViewFlashlightController;
protected Camera mCamera;
protected Parameters mParameters;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageViewFlashlight=(ImageView) findViewById(R.id.imageview_flashlight);
   mImageViewFlashlightController=(ImageView) findViewById(R.id.imageview_controller);

}

只要activity复写这个方法,当你按退出键的时候就会响应这个事件,因此这个方法就可以放在几类中。

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
if(event.getAction()==KeyEvent.ACTION_DOWN&&event.getRepeatCount()==0){
this.exitApp();
}
return true;
}
return super.dispatchKeyEvent(event);
}
//退出程序
private void exitApp() {
//判断2次点击事件时间
if((System.currentTimeMillis()-exitTime)>2000){
Toast.makeText(BaseActivity.this, "再按一次退出程序", Toast.LENGTH_LONG).show();
exitTime=System.currentTimeMillis();

}else{
finish();
}
}


}

你可能感兴趣的:(android的activity再按一次退出程序)