在Level5以上(包含)中,Activity類中的方法:public void onAttachedToWindow ()就能對Home鍵進行捕獲。具體代碼如下:
MainActivity.java
- package com.lingdududu.test;
- import Android.app.Activity;
- import android.os.Bundle;
- import android.view.KeyEvent;
- import android.view.WindowManager;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- /** Called when the activity is first created. */
- private boolean catchHomeKey = false;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
- @Override
- public void onAttachedToWindow() {
- // TODO Auto-generated method stub
- if (!catchHomeKey) {
- this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
- }
- super.onAttachedToWindow();
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // TODO Auto-generated method stub
- if (keyCode == KeyEvent.KEYCODE_HOME) {
- Toast.makeText(MainActivity.this, "你點擊了HOME鍵", Toast.LENGTH_LONG).show();
- }
- return super.onKeyDown(keyCode, event);
- }
- }
當我們點擊Home鍵的時候,程序並沒有回到主界面,而是停留在當前的頁面,並且能捕獲到Home鍵,調用Toast顯示信息。
效果圖:
650) this.width=650;">