我在Android和学习方面是全新的,我注意到OnBackPressed带你进入了游戏的前一个布局,现在我添加了这段代码,它关闭了OnBackPressed的应用程序。
@Override
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
super.onBackPressed();
}我的问题是,当你再次开始游戏,它会带你回到以前的布局,而不是主要布局。举个例子,你有4个活动,当我开始游戏时,它会带我去活动3,我怎样才能避免这种情况?
<application
android:allowBackup="true"
android:icon="@mipmap/icon1"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".StartGame"
android:label="@string/app_name"
android:screenOrientation="portrait"/>
<activity
android:name=".MathQuestions"
android:label="@string/app_name"
android:screenOrientation="portrait"
/>
<activity android:name=".HighScores"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity android:name=".HowToPlay" >
</activity>
</application>
发布于 2015-09-02 20:17:58
修改标志:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 并调用finish()而不是super.onBackPressed();
我读了一些书,发现:
此启动模式还可与FLAG_ACTIVITY_NEW_TASK一起使用,效果良好:如果用于启动任务的根活动,它将将当前正在运行的该任务实例带到前台,然后将其清除到根状态。例如,在从通知管理器启动活动时,这一点尤其有用。
来自CLEAR_TOP的文档
编辑:另一个解决方案。
好吧,这对你没用,让我们这样做:
创建一个扩展应用程序的自定义类,您大部分时间不需要这样做,但在这里会有所帮助。叫它MyApp.java
public class MyApp extends Application {
private HashSet<Activity> mActivities;
@Override
public void onCreate(){
super.onCreate();
mActivities = new HashSet<Activity>();
}
public void addActivity(Activity activity){
if(!mActivities.contains(activity))
mActivities.add(activity);
}
public void removeActivity(Activity activity){
if(mActivities.contains(activity))
mActivities.remove(activity);
}
public void close(){
for(Activity activity : mActivities){
activity.finish();
}
}并将其添加到应用程序标记中的android清单中(保持rest不变):
<application
android:name=".MyApp"
...
...现在,在每个活动中调用以下内容:
@Override
public void onStart(){
super.onStart();
((MyApp) getApplication()).addActivity(this);
}因此,现在每个活动都存储在您自己的HashSet中,当您需要它时,就可以优雅地完成它。
与其调用意图,不如现在就这样做:
@Override
public void onBackPressed(){
((MyApp) getApplication()).close();
}所有的活动都完成了,资源被释放了,当你回到应用程序的时候,它将在你的家庭活动中。现在,对于活动被破坏或停止的情况,您可能不需要removeActivity调用,但是这个解决方案应该有效。就像我说的,这是多一点的工作,但会解决你的问题。
发布于 2015-09-02 20:18:25
你并没有真正关闭你的应用程序。使用该代码,您只需最小化您的应用程序(模仿主页按钮行为)。我相信,如果您在finish()调用之后调用startActivity(homeIntent),它将按您的意愿工作。
https://stackoverflow.com/questions/32362198
复制相似问题