程序退出處理
public class SplashScreen extends AppCompatActivity {
private static long SPLASH_MILLIS = 1000;
ImageView image1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
LayoutInflater inflater = LayoutInflater.from(this);
LinearLayout layout = (LinearLayout) inflater.inflate(
R.layout.splashscreen, null, false);
addContentView(layout, new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
}, SPLASH_MILLIS);
}
}
//上次按下返回鍵的系統時間
private long lastBackTime = 0;
//當前按下返回鍵的系統時間
private long currentBackTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//捕獲返回鍵按下的事件
if(keyCode == KeyEvent.KEYCODE_BACK){
//獲取當前系統時間的毫秒數
currentBackTime = System.currentTimeMillis();
//比較上次按下返回鍵和當前按下返回鍵的時間差,如果大於2秒,則提示再按一次退出
if(currentBackTime - lastBackTime > 2 * 1000){
Toast.makeText(this, "再按一次返回鍵退出", Toast.LENGTH_SHORT).show();
lastBackTime = currentBackTime;
}else{ //如果兩次按下的時間差小於2秒,則退出程序
//int pid = android.os.Process.myPid(); //獲取當前應用程序的PID
//android.os.Process.killProcess(pid); //殺死當前進程
this.finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
攔截回退操作
@Override
public void onBackPressed() {
Intent MyIntent = new Intent(Intent.ACTION_MAIN);
MyIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(MyIntent);
}