如何在 Android 上的所有片段中保留对 Web 服务的身份验证?

How to persist authentication to web service in all fragments on Android?

我正在使用 Odoo 服务。我的应用程序中有 3 个片段。

在我需要登录服务的每个片段中:

OdooClient odoo;
odoo = new OdooClient.Builder(getActivity()).setHost(host).build();

odoo.setOnConnectListener(new OdooConnectListener() {
   @Override
   public void onConnected(OdooVersion version) {
     Log.i(TAG,"onConnected");
     Log.i(TAG,odoo.getDatabases().toString());
     odoo.authenticate(username,password,db,loginCallback);
   }
 });

有没有一种方法可以对所有片段进行一次验证?我可以在 MainActivity 上进行身份验证,但我无法获取对象的引用。

您可以在单例中进行身份验证,init 在主 Activity(传递上下文和主机)中,然后仅在 Fragments

中获取引用

编辑

public class Odoo {
public static OdooClient CLIENT;
public static void init(Context context,String host) {
     CLIENT=new OdooClient.Builder(context).setHost(host).build();
}

现在可以在 Main 中调用 init Activity

Odoo.init(this,host);

然后在片段中获取引用

Odoo.CLIENT.setOnConnectedListener(...);