如何阻止多个活动在主页按钮上启动

时间:2014-05-09 16:52:15

标签: android android-intent android-activity android-background

我的应用有两项活动MAINLOGIN

我的应用的工作流程如下,MAINlauncher

 MAIN - If user logged in, show MAIN
 MAIN - If user NOT logged in, show LOGIN and close finish MAIN

以下是一个可行的方案。

 User launches the app -> sees LOGIN screen
 User logs in, sees the MAIN screen
 User presses back button on phone, sees the phone's screen again (NOT the LOGIN screen again)   

下面是一个不能正常工作的场景。

 User launches the app -> sees LOGIN screen
 Presses middle button on the phone to send app to background
 User launches the app again -> sees the LOGIN screen (here another instance of the login screen is being created...)
 User logs in, sees the MAIN screen
 User presses back button on phone, sees the LOGIN screen again!

如何解决这种情况,因此如果按下或未按下手机上的中间按钮并不重要,则始终只有一个登录屏幕实例?

这是我的代码:

主要

       @Override
       public void onStop() {
          super.onStop();
          finish();
       } 

       if (TextUtils.isEmpty(authToken)) {
            Intent login = new Intent(getApplicationContext(), LoginActivity.class);
            startActivityForResult(login, LOGIN_ACTIVITY);
            finish();
        }

LOGIN

    mAccountManager.addAccountExplicitly(account, accountPassword, null);
    mAccountManager.setAuthToken(account, authtokenType, authtoken);
    mAccountManager.setPassword(account, accountPassword);
    startActivity(new Intent(getApplicationContext(), MainActivity.class));

更新

1 个答案:

答案 0 :(得分:1)

使用此代码..

 @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
        // Activity was brought to front and not created, 
        // Thus finishing this will get us to the last viewed activity 
        finish(); 
        return; 
    } 

    // Regular activity creation code... 
} 

此代码始终使应用程序打开您离开的最后一个活动