常见的物理按键:
Android为每个物理按键都提供了如下几个回调方法:
代码示例:
package com.example.demo3;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;
import java.security.Key;
public class MainActivity extends AppCompatActivity {
private long exitTime;
@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);
}
//第二步:创建退出方法exit()
public void exit(){
//两次点击回退键前后间隔小于2秒退出,否则弹出提示
if((System.currentTimeMillis()-exitTime)>2000){
Toast.makeText(MainActivity.this,"再按一次退出应用",
Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
}else{
finish();
System.exit(0);
}
}
}