我找到了这个问题的解决办法。我将上述代码替换为以下代码:
PackageManager pm = getActivity().getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(getActivity(), CustomLauncherActivity.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
writeSetupFlag(true);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
注意添加到意图中的标志(
FLAG_ACTIVITY_NEW_TASK
和
FLAG_ACTIVITY_SINGLE_TOP
)以及
startActivityForResult
简单地说是“startActivity”。
writeSetupFlag
将标志写入
SharedPreferences
指示已显示选择器:
private void writeSetupFlag(boolean bInSetup) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getString(R.string.setup_flag_active), bInSetup);
editor.commit();
}
这使我们能够确定之前是否显示过选择器。因此,假设用户在选择过程中选择了错误的主页活动(即不是我们的活动),将显示主页屏幕。重新启动应用程序将触发读取写入的标志,我们可以检测到显示了选择器,但用户选择了错误的启动器。
因此,我们可以首先检查我们的活动是否设置为主启动器:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(context, CustomLauncherActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_ALL);
pm.setComponentEnabledSetting(new ComponentName(context, CustomLauncherActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
String currentHomePackage = resolveInfo.activityInfo.packageName;
String customlauncherpackage = context.getApplicationContext().getPackageName();
现在,如果我们的活动不是主启动器,我们将检查设置标志:
if (!currentHomePackage.equals(customlauncherpackage)) {
boolean bChooserShown;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
bChooserShown = sharedPreferences.getBoolean(getString(R.string.setup_flag_active), false);
if (bChooserShown) {
//Display a dialog to the user indicating that they selected the wrong launcher before and will have to reset the launcher from settings.
... dialog here ...
//Then redirect to settings
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
Intent i = new Intent(Settings.ACTION_HOME_SETTINGS, null);
startActivityForResult(i, REQUEST_LAUNCH_HOME_SETTINGS);
} else {
Intent i = new Intent(Settings.ACTION_SETTINGS, null);
startActivityForResult(i, REQUEST_LAUNCH_HOME_SETTINGS);
}
}
else {
//do chooser process
}
所以通过在
共享引用
当我们显示选择器时,我们可以从用户选择错误的主启动器应用程序中恢复。