我有一个使用初始屏幕和选择屏幕的应用程序,如以下 list 所示:
<application
android:name="com.example.CoolApp"
android:label="@string/app_name"
android:icon="@drawable/app_icon_debug"
android:theme="@style/Theme.NoBackground">
<activity
android:name="com.example.Splash"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:noHistory="true"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="coolappscheme"/>
</intent-filter>
</activity>
<activity
android:name="com.example.ChoiceActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden"/>
</application>
初始屏幕显示约 2 秒,然后通过以下代码导航到 ChoiceActivity
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
... some stuff for showing the Splash screen ...
Thread mythread = new Thread() {
@Override
public void run() {
try {
.. animation stuff for fading in ...
while (splashActive && ms < splashTime) {
if(!paused)
ms=ms+100;
sleep(100);
}
} catch(Exception e) {
} finally {
Intent intent = new Intent(Splash.this, ChoiceActivity.class);
startActivity(intent);
}
}
};
现在,这段代码显然有很多问题(首先是作者为什么决定使用单独的 Thread
而不是 AsyncTask
。但是,把如果用户执行以下操作,这些东西暂时放在一边:
- 启动应用程序并查看启动画面。
- 强制应用程序进入后台(例如,用户接到电话,或者可能只是点击“主页”按钮)。
然后,当 Thread
完成时(即到达 finally
block 并创建 Intent
),新的 ChoiceActivity
被创建,但它也将应用程序带到前台。我想禁用此行为。也就是说,我希望加载 Activity ,但应用程序保留在后台。如果那不可能,那么我希望应用程序延迟加载新的 Activity
(//any//new Activity
) 直到应用程序恢复。
我怎样才能做到这一点?
最佳答案
Activity 应该在前台运行。有一个给定的生命周期,它基于用户与应用程序的交互方式。因此,您实际上不应该尝试“在后台开始您的 Activity ”,因为它没有意义……您可以做的是以某种方式改变 Activity 对来自外部事件的 react 方式…… 例如,您可以在 Activity 中创建一个新的 boolean 字段,每次在 onPause() 中将其设置为 false,在 onResume() 中设置为 true...
然后您可以在启动新 Activity 时检查它,实际上只有在 true 时才启动它。否则只需将该字段设置为 true,然后在 onResume() 中在该字段为真时启动 Activity 。
您还应该考虑到,后台 Activity 可能随时被系统终止。 Activity 应该释放所有系统资源并在它进入后台时停止它的工作。只有这样你才能确保你的应用程序不会进入不可预测的状态。 对于后台任务,您应该使用服务,这些服务基本上是“没有 UI 的 Activity ”(我相信我没有这么说过)- 您的应用程序的一部分在后台运行。
关于java - 即使启动了新 Activity ,也让应用程序留在后台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945226/