android监听home
① 如何在Android的service里进行按键的监听
app中对于HOME键广播事件的接收
首先,自定义一个BroadcastReceiver:
[java] view plain
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处理点
} else if (reason.equals(SYSTEM_RECENT_APPS)) {
// long home key处理点
}
}
}
}
}
其次,生成且注册之
[java] view plain
receiver = new HomeKeyEventBroadCastReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
这样,我们就可以在app中进行HOME键的处理了!
② android 在fragment中怎么监听返回键,home键
android 在fragment中监听返回键和home键的方法:
思路:
1、定义OnBackPressedListener监听接口
2、创建基础监听类,实现OnBackPressedListener接口
3、在BaseActivity中创建方法调用
4、重写onBackPressed方法和onHomePress方法
核心代码如下:
@Override
public void onBackPressed() {
FragmentManager fragmentManager =getSupportFragmentManager();
if (((C_fragment) getSupportFragmentManager().findFragmentByTag("xyz")) != null && ((C_fragment) getSupportFragmentManager().findFragmentByTag("xyz")).isVisible()) {
Fragment fragment = new D_Fragment();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
getSupportActionBar().setTitle("D fragment ");
} else {
super.onBackPressed();
}
}
@Override
public void onHomePressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();