【问题标题】:Android Setting New default home in codeAndroid 在代码中设置新的默认主页
【发布时间】:2014-08-14 10:17:45
【问题描述】:

我有一个想要设置为默认主屏幕的应用程序,但我遇到了一个奇怪的问题。

我有一个允许用户选择默认主屏幕的设置。

我使用以下代码允许他们选择默认活动:

Intent selector = new Intent(Intent.ActionMain);
selector.AddCategory(Intent.CategoryHome);
selector.AddCategory(Intent.CategoryDefault);
selector.SetComponent(new ComponentName("android", "com.android.internal.app.ResolverActivity"));

StartActivity(selector);

当前没有设置默认值,我运行该代码并选择我的应用作为默认值并告诉它始终使用它。

现在,我再次运行代码,并告诉它使用不同的 Activity(不是我的)并始终使用它。

问题是,如果默认设置,它永远不会切换到任何不同的东西。

我见过其他允许您执行此操作的应用程序,所以我遗漏了一些东西,我只是不知道是什么。

我正在我的三星 Galaxy S4 上进行测试,API 级别设置为 14。

【问题讨论】:

  • 使用startActivity(selector) 而不是StartActivity(selector)
  • 这是 Xamarin 和 C#,该更改无法编译。
  • 作为后续,我尝试了以下方法:stackoverflow.com/questions/13167583/…,但它似乎不起作用。在三星 Galaxy4 和三星 Galaxy5 上使用 API14 进行测试。

标签: android xamarin


【解决方案1】:

好的,我找到了问题的答案。

答案在这里: http://www.trustydroid.com/2014/05/19/force-show-default-app-chooser-dialog/

您应该记住的一件事是组件名称必须正确。显然在 API14 下,如果类名不正确,它会忽略该组件(并像它一样工作)。所以它经历了启用组件、启动选择器、然后禁用组件的动作。但是,它永远不会保存新的默认值。

在我尝试在 API19 下编译后,操作系统抛出了一个异常,导致我修复了它工作时遇到的问题(这是一个不正确的类名)。

一旦我把它理顺了,它就完全按照我的意愿去做了。

为了完整起见,这里是代码:

像这样创建一个 FakeActivity:

[Activity(Label = "FakeLauncher", Enabled = false)]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryHome, Intent.CategoryDefault })]
public class FakeLauncher : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Create your application here
    }
}

然后,无论您想在哪里更改默认主页,都可以运行以下代码:

 ComponentName componentName = new ComponentName(Application.PackageName, "<fake activity class name>");
 PackageManager.SetComponentEnabledSetting(componentName, Android.Content.PM.ComponentEnabledState.Enabled, Android.Content.PM.ComponentEnableOption.DontKillApp);

 Intent tempIntent = new Intent(Intent.ActionMain);
 tempIntent.AddCategory(Intent.CategoryHome);

 StartActivity(tempIntent);

 PackageManager.SetComponentEnabledSetting(componentName, Android.Content.PM.ComponentEnabledState.Disabled, Android.Content.PM.ComponentEnableOption.DontKillApp);

【讨论】:

    【解决方案2】:

    如果您仍然收到组件名称不正确的异常

    Unhandled Exception:
    Java.Lang.IllegalArgumentException: Component class FakeLauncher does not exist in com.application.name
    

    您可以像这样在 Xamarin 中获得正确的“假活动类名称”:

    string className = Java.Lang.Class.FromType(typeof(FakeLauncher)).Name;
    

    组件名称可以很随意,像这样:md546c42bb6607ccd24974e44efa088a043.FakeLauncher

    【讨论】:

      猜你喜欢
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多