Android 监听返回键、HOME键

拦截返回键,HOME键,继承BaseActivity即可

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * 所有Activity继承该类,
 * 该类监测到home键的点击时的事件进行自己的处理
 * 拦截返回键
 * @author RongGuang
 * 
 */
public class BaseActivity extends Activity {
    // 监听HOME键
    HomeKeyEventBroadCastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 监听home键广播
        receiver = new HomeKeyEventBroadCastReceiver();
        registerReceiver(receiver, new IntentFilter(
                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }
    //拦截其他键
    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        switch(keyCode){
            case KeyEvent.KEYCODE_HOME:return true;
            case KeyEvent.KEYCODE_BACK:return true;
            case KeyEvent.KEYCODE_CALL:return true;
            case KeyEvent.KEYCODE_SYM: return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN: return true;
            case KeyEvent.KEYCODE_VOLUME_UP: return true;
            case KeyEvent.KEYCODE_STAR: return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
        static final String SYSTEM_REASON = "reason";
        static final String SYSTEM_HOME_KEY = "homekey";// home key
        static final String SYSTEM_RECENT_APPS = "recentapps";// long home key

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (reason != null) {
                    if (reason.equals(SYSTEM_HOME_KEY)) {
                        // home key处理点
                        Log.e("homekey", "home键被点击");
                        Toast.makeText(BaseActivity.this, "Home键被点击", Toast.LENGTH_SHORT).show();
                    } else if (reason.equals(SYSTEM_RECENT_APPS)) {
                        // long homekey处理点
                         Log.e("homekey", "长按home键");
                         Toast.makeText(BaseActivity.this, "Home键长按", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
}

 

你可能感兴趣的:(Android 监听返回键、HOME键)