【发布时间】:2021-04-16 09:10:04
【问题描述】:
我正在使用一个服务 (BlockAppsService) 来检查哪个应用程序在前台。当某些应用程序处于前台时,我想在设备上启动主应用程序并向用户显示 Toast 消息。一切正常,显示 Toast,但无法启动家庭应用程序。
我BlockAppsService类的相关代码:
private boolean blockApp(AppCacheInfo appInfo, String packageInForeground) {
String toastMessage = appInfo == null ? getString(R.string.this_app) : appInfo.getLabel() + " "
+ getString(R.string.toast_error_distracting_app);
postToastOnMainThread(toastMessage);
launchHome();
}
private void postToastOnMainThread(String toastMessage) {
// Post the toast on the UI thread.
getMainHandler().post(() -> {
Utils.showToast(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT);
});
}
private void launchHome() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
private Handler getMainHandler() {
if (mainHandler == null) {
mainHandler = new Handler(getMainLooper());
}
return mainHandler;
}
例如,启动我自己的 MainActivity 而不是主应用程序也不起作用。
有趣的是,当我打开 Android 设置并通过这些方法阻止它时,它正在工作。只是其他应用程序没有:我没有遇到任何异常,家庭应用程序只是无法通过startActivity() 启动。
有人知道这里发生了什么吗?
非常感谢!
【问题讨论】:
标签: android android-service android-launcher start-activity