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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐