문제

I have an app that circles around the main activity (a main menu). In each other app there is an option menu item that directs to this activity.

At first, I always started a new main activity when this item was selected. Using the intent bundle, I did tell the main activity that some initializations I do on a fresh start were not necessary.

However, I didn't quite like the overall behavior. I stumbled upon android:launchMode="SingleTask" and this seemed to help: now I don't recreate my main menu activity all the time; also, if I press the "back" button I come back straight to the home screen. This feels quite nicely like a proper "main" menu.

My problem now is this: if I run another activity of my app, press home button and then reopen my app (e.g. using "last apps"), then I don't go back to the last activity, but to the main one. The other activity is destroyed.

Any ideas how I can implement the behavior of SingleTask without only being able to return to one activity?

도움이 되었습니까?

해결책

If your other activities are declared normally with activity defaults in Android, then going back to your app should take you to the same activity where you left off (using the hardware home button)

However remember that the Android system kills applications when it requires system resources. So your app may have been killed when you went to the other application. Then when you get back to your app, the default launcher activity will be restarted, which is your Menu activity.

To get back to the main activity from any activity, do this:

public static void goHome(Context context) {
        final Intent intent = new Intent(context, HomeActivity.class); //give name of your main activity class here
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

That will clear the activity stack and get you back to your main activity. As you declared singleTop, it will bring the existing main activity to the foreground. The flag Intent.FLAG_ACTIVITY_CLEAR_TOP will remove all activities in the stack on top of the main activity. (I am assuming you are within the same application).

Now, all your other activities only need to include a button whose click listener invokes the method goHome();

From your main activity, if you press the hardware back button, it should exit your app.

다른 팁

Why not call finish() on the activities that were created by the main activity? This way you return to the main activity, without creating a new one...

I think you should save the state of you activity before starting another activity, and then resume your activity whenever you come back on last activity. see Activity Life cycle from Android http://developer.android.com/guide/topics/fundamentals/activities.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top