package com.example.test; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public boolean onKeyDown(int keyCode,KeyEvent event){ if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){ //確定按下退出鍵and防止重複按下退出鍵 dialog(); } return false; } private void dialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //創建訊息方塊 builder.setTitle("確認視窗"); builder.setMessage("確定要結束應用程式嗎?"); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); //dismiss為關閉dialog,Activity還會保留dialog的狀態 MainActivity.this.finish();//關閉activity } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
以上範例是在按下back鍵後,會跳出一個確認的訊息框,確認是否真的要離開此程式。當然也可以用KEYCODE_HOME去偵測HOME鍵被按下的動作,但是會比較麻煩,可能需要加上
public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }此流程與FULL_SCREEN屬性是互斥的,為了避免設計不良或是惡意程式鎖住畫面無法強制退出與結束應用程式
沒有留言:
張貼留言