android电源键广播,Android利用广播监听按下HOME和电源键
packagecc.testhome;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;public classHomeKeyObserver {privateContext mCo
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();
}
}
}
}
}
}
更多推荐
所有评论(0)