java - 如何检测服务中的导航按钮点击?Android
问题描述
我必须构建一个应用程序,其中的功能需要检测导航按钮点击,例如:返回、主页和最近的应用程序按钮,然后通过服务执行一些功能。
解决方案
在服务类中创建接收器:
class InnerReceiver extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// Home Button click
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
// RecentApp or Overview Button click
}
}
}
}
}
然后在 Service onStartCommand() 方法中注册广播接收器:
mReceiver = new InnerReceiver();
IntentFilter mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mReceiver, mFilter);
并在 onDstroy() 方法中取消注册接收器:
unregisterReceiver(mReceiver);
推荐阅读
- java - Selenide - 为每个 Junit 5 测试创建新驱动程序
- command-line-interface - NativeScript CLI 基础知识:设置后没有 main-page.xml 或 app.css 文件
- javascript - 将列表 Ajax(Json) 传递给 Controller C# MVC
- api - 如何确定 API 调用期间调用的所有函数的执行时间?
- amazon-web-services - Alexa 部署到 us-west-2?
- terminal - 如何以及是否在没有 Ncurses 的情况下为文本着色
- matlab - 如何在MATLAB中的图形的ylabel上写一个方程?
- php - 在进行注册之前检查用户是否登录
- asp.net-core-2.1 - 如何在 .net core 2 项目中启用 cors 在 apache2 服务器中运行
- sql - 列的 Netezza 时间戳数据类型