在Android中,我们可以有不同的进程(例如另一个进程中的一个服务)。
但是,我注意到 CookieManager(来自 android.webkit.CookieManager)不会在整个过程中同步其新设置的 Cookie。
我在 MainActivity 中有一个设置 Cookie 的函数
cookieManager.setCookie(url, cookieString)
cookieManager.flush()
如果我在 MainActivity 或 MainService(同一进程中的服务)中读取它,那么我可以读取它。
val cookie = cookieManager.getCookie(url)
但是,如果我在OtherService(另一个进程中的服务)中读取它,那么它可能不会得到它。
为了清楚地证明这一点,我创建了一个应用程序,如下所示。您可以在此处获取代码
1.全新安装应用
- 安装新创建的应用程序
- 点击Main Process Service:Log(TrackingMe)显示没有Cookie Set<正确>
- 点击Other Process Service:Log(TrackingMe)显示没有Cookie Set<正确>
- 点击 Write Cookie 将 cookie 写入 CookieManager
- 点击Main Process Service:Log(TrackingMe)显示Cookie Set<正确>
- 点击Other Process Service:Log(TrackingMe)显示没有Cookie Set<不正确>
2.杀死应用程序并重新启动应用程序
- 杀死并重新启动应用程序(不要删除应用程序数据)
- 点击Main Process Service:Log(TrackingMe)显示Cookie Set<正确>
- 点击Other Process Service:Log(TrackingMe)显示Cookie Set<正确>
- 点击 Clear Cookie 将所有 Cookie 清空到 CookieManager
- 点击Main Process Service:Log(TrackingMe)显示没有Cookie Set<正确>
- 点击Other Process Service:Log(TrackingMe)显示Cookie Set<不正确>
这一发现
- 其他进程服务不会从 CookieManager 获取更新的 cookie。只能在App被杀死并重启后才能获得。
问题:
- 我们如何让其他进程服务立即从 CookieManager 获取 Cookie?(无需重启App?)