我目前正在构建一个需要身份验证的 ICS 4.0+ Android 应用程序。我遇到的问题是在以下情况下处理登录状态检查:
- 用户首先打开应用
- 用户在关闭(恢复)后返回应用
我正在寻找的行为是,如果应用程序从内存中删除并重新打开,则会出现“正在加载...”启动画面,然后当用户在恢复时返回到应用程序时,出现几乎不明显的启动画面(仍然在内存中)。
我目前用于检查的代码是:
public static void checkUserStatus(Context context, boolean isPassive) {
Log.d(TAG, "Checking user status..");
// User is logged in and has cc
if ( APIUtil.isLoggedIn() && UserAccount.getCreditCards().size() > 0 && isPassive == false) {
Intent intent = new Intent(context, OtherActivity.class);
context.startActivity(intent);
// User is logged in but has no cc
} else if (APIUtil.isLoggedIn() && UserAccount.getCreditCards().size() == 0) {
Intent intent = new Intent(context, ManageCCActivity.class);
context.startActivity(intent);
// User is not logged in
} else if(isPassive == false) {
Intent intent = new Intent(context, HomeActivity.class);
context.startActivity(intent);
}
}
checkUserStatus 在每个 Activity 的 onResume() 中被调用。这个想法是它会检查这个并相应地重定向,但行为古怪且不一致,而且感觉很糟糕。
有没有验证流程的例子?想法?有什么建议吗?
最佳答案
我使用过并看到其他使用效果很好的模式看起来像这样:
- 将用于确定用户是否已登录以及是否具有有效数据的逻辑封装到
Service
中,然后运行该Service
绑定(bind)(意味着您永远不会启动或阻止它,你绑定(bind)它... docs link for more on that )。 - 实现一个基础
Activity
实现,它在onStart()
中绑定(bind)到服务,并在onStop()
中解除绑定(bind)。这允许Service
在您从一个Activity
移动到另一个时保持运行。让任何需要访问此信息的Activity
继承自此基础(可能是每个Activity
)。 - 让
Service
仅在启动时检查它需要的信息,并返回结果。
这创建的是一个(相当)单一的授权检查实例,它仅在应用程序启动或用户离开后返回时进行检查,而不会在您从一个 Activity
移动到其他。它还允许它在用户过早离开时优雅地完成任何长时间运行的操作,因为所有工作都在 Service
中完成。
关于android - 您如何处理 Android 身份验证后的重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13499277/