I'm using a Service (BlockAppsService) that checks which app is in the foreground. When certain apps are in the foreground, I want to launch the home application on the device and show a Toast message to the user. Everything is working fine, the Toast is displayed, but launching the home app is not working.
The relevant code from my BlockAppsService class:
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;
}
Launching, for example, my own MainActivity instead of the home app also doesn't work.
The interesting thing is that when I open the Android settings and I block it through these methods, it is working. It's just that with other apps, it doesn't: I don't get any exceptions, the home app just doesn't launch through startActivity().
Anyone knows what's going on here?
Many thanks!