Activity 从服务调用时重新启动

Activity restarts when called from service

我的应用程序中有一个浮动按钮服务(例如 facebook messenger) 当点击时,我的 activity returns 来自后台,但它并没有像缩小时那样 return ,它再次开始调用 onCreate ,任何知道是什么导致了这种行为?

在我的清单中,活动是 属性 :

            android:launchMode="singleTask"

我的服务是这样调用它的:

    Intent i = new Intent(FloatingViewService.this, DrawerActivity2.class);
    i.putExtra("fromController",true);
    i.setFlags(FLAG_FROM_BACKGROUND);
    FloatingViewService.this.startActivity(i);

我的主要问题是 activity 我有一个网络视图,每次单击按钮时它都会重新加载并调用 activity 而不是保持原样。

更新后这是我在清单中的activity

        <activity
        android:name=".DrawerActivity2"
        android:configChanges="orientation"
        android:launchMode="singleTop"
        android:screenOrientation="portrait"
        android:theme="@style/OtherTheme"/>

更新 2

值得一提的是,它是一个位于应用程序中的库。

我尝试使用此代码打开 activity :

Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(intent);

它打开了第一个(原始应用程序的)activity 而不是打开的那个。

我们将不胜感激任何帮助

你需要:

<activity
        android:name=".DrawerActivity2"
        android:launchMode = "singleInstance" />

我只能想象你的 FLAG_FROM_BACKGROUND 是什么意思。我想知道它是否这样调用是因为你之前遇到过一些像 "activity could be launched without FLAG_NEW_TASK from applicationContext bla bla" 这样的崩溃。随便。

因此,如果您有 Intent.FLAG_ACTIVITY_NEW_TASK,您将始终在 NEW_TASK 中实例化您的 DrawerActivity2。它永远是,你知道 "new one" activity。 将 launchMode 更改为 singleTop 不会给出预期的结果。 Read about launchModes and Flags here

请注意,您不能在 TASK 内使用 ApplicationContext(或 Service 扩展的 BaseContext/ContextWrapper)启动 Activity。为此,你必须使用Activity的上下文开始新的Activity

大约 Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(intent); 可能它按预期工作

The current implementation looks first for a main activity in the category Intent.CATEGORY_INFO, and next for a main activity in the category Intent.CATEGORY_LAUNCHER. Returns null if neither are found.

Android developers source

然后你问

my activity returns from the background, it starts over calling onCreate once more , any idea what causes this behavior ?

我的假设是FLAG_FROM_BACKGROUND:

Intent i = new Intent(FloatingViewService.this, DrawerActivity2.class);
    i.putExtra("fromController",true);
    i.setFlags(FLAG_FROM_BACKGROUND); /*is it really Intent.FLAG_ACTIVITY_NEW_TASK ???*/
    FloatingViewService.this.startActivity(i);

如何解决?可能以 ActivityContext 而不是 ApplicationContext 开始 Activity。但这是另一回事。并且无法推荐 "good" 如何实施它的方法。

我认为如果您使用 launchMode singleTop 和 i.setFlags(FLAG_ACTIVITY_NEW_TASK) 它应该可以工作,但前提是 activity 位于堆栈顶部。

如果您不能确保 activity 在堆栈顶部,值得尝试将 launchMode 设置为 singleTask 和 i.setFlags(FLAG_ACTIVITY_NEW_TASK)