按二次back键退出程序应用的实现
package com.loaderman.twoexitdemo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { isExit = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { exit(); return event.equals(KeyEvent.KEYCODE_BACK ); } private static boolean isExit = false; private void exit() { if (!isExit) { isExit = true; Toast.makeText(this, "再次点击退出程序", Toast.LENGTH_SHORT).show(); handler.sendEmptyMessageDelayed(0, 2000); } else { finish(); System.exit(0); } } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!