4点几之后onKeyDown方法已经不能监听home键了,系统统一用Intent.ACTION_CLOSE_SYSTEM_DIALOGS广播,点击Home键系统会发出这个广播。
代码如下,分为两部分,一部分是监听广播,一部分在Activity调用
监听广播如下
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
/**
* Home按键监听类
* 使用说明:
* 1、初始化HomeListen
* HomeListen homeListen = new HomeListen( this );
* homeListen.setOnHomeBtnPressListener( new setOnHomeBtnPressListener(){
* @Override
* public void onHomeBtnPress( ){
* // 按下Home按键回调
* }
*
* @Override
* public void onHomeBtnLongPress( ){
* // 长按Home按键回调
* }
* });
*
* 2、在onResume方法中启动HomeListen广播:
* homeListen.start();
*
* 3、在onPause方法中停止HomeListen广播:
* homeListen.stop( );
* */
public class HomeListen {
public HomeListen(Context context) {
mContext = context;
mHomeBtnReceiver = new HomeBtnReceiver( );
mHomeBtnIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomeBtnPressListener( OnHomeBtnPressLitener onHomeBtnPressListener ){
mOnHomeBtnPressListener = onHomeBtnPressListener;
}
public void start( ){
mContext.registerReceiver( mHomeBtnReceiver, mHomeBtnIntentFilter );
}
public void stop( ){
mContext.unregisterReceiver( mHomeBtnReceiver );
}
class HomeBtnReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
receive( context, intent );
}
}
private void receive(Context context, Intent intent){
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra( "reason" );
if (reason != null) {
if( null != mOnHomeBtnPressListener ){
if( reason.equals( "homekey" ) ){
// 按Home按键
mOnHomeBtnPressListener.onHomeBtnPress( );
}else if( reason.equals( "recentapps" ) ){
// 长按Home按键
mOnHomeBtnPressListener.onHomeBtnLongPress( );
}
}
}
}
}
public interface OnHomeBtnPressLitener{
public void onHomeBtnPress( );
public void onHomeBtnLongPress( );
}
private Context mContext = null;
private IntentFilter mHomeBtnIntentFilter = null;
private OnHomeBtnPressLitener mOnHomeBtnPressListener = null;
private HomeBtnReceiver mHomeBtnReceiver = null;
}
在Activity中做例如以下调用就可以:
public class HomeListenActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_listen_layout);
initHomeListen( );
}
@Override
protected void onResume( ) {
super.onResume();
mHomeListen.start( );
}
@Override
protected void onPause() {
super.onPause();
mHomeListen.stop( );
}
private void initHomeListen( ){
mHomeListen = new HomeListen( this );
mHomeListen.setOnHomeBtnPressListener( new OnHomeBtnPressLitener( ) {
@Override
public void onHomeBtnPress() {
showToast( "按下Home按键!" );
}
@Override
public void onHomeBtnLongPress() {
showToast( "长按Home按键!" );
}
});
}
private void showToast( String toastInfoStr ){
Toast.makeText( this, toastInfoStr, Toast.LENGTH_LONG ).show( );
}
private HomeListen mHomeListen = null;
}