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();