packagecc.testhome;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;public classHomeKeyObserver {privateContext mContext;privateIntentFilter mIntentFilter;privateOnHomeKeyListener mOnHomeKeyListener;privateHomeKeyBroadcastReceiver mHomeKeyBroadcastReceiver;publicHomeKeyObserver(Context context) {this.mContext =context;

}//注册广播接收者

public voidstartListen(){

mIntentFilter=newIntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

mHomeKeyBroadcastReceiver=newHomeKeyBroadcastReceiver();

mContext.registerReceiver(mHomeKeyBroadcastReceiver, mIntentFilter);

System.out.println("----> 开始监听");

}//取消广播接收者

public voidstopListen(){if (mHomeKeyBroadcastReceiver!=null) {

mContext.unregisterReceiver(mHomeKeyBroadcastReceiver);

System.out.println("----> 停止监听");

}

}//对外暴露接口

public voidsetHomeKeyListener(OnHomeKeyListener homeKeyListener) {

mOnHomeKeyListener=homeKeyListener;

}//回调接口

public interfaceOnHomeKeyListener {public voidonHomeKeyPressed();public voidonHomeKeyLongPressed();

}//广播接收者

class HomeKeyBroadcastReceiver extendsBroadcastReceiver{final String SYSTEM_DIALOG_REASON_KEY = "reason";//按下Home键

final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";//长按Home键

final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";

@Overridepublic voidonReceive(Context context, Intent intent) {

String action=intent.getAction();if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {

String reason=intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);if (reason != null && mOnHomeKeyListener != null) {if(reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {

mOnHomeKeyListener.onHomeKeyPressed();

}else if(reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {

mOnHomeKeyListener.onHomeKeyLongPressed();

}

}

}

}

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐