如何在非活动类中使用Xamarin.Firebase.Auth并得到通知?

时间:2018-10-30 02:03:51

标签: c# android firebase xamarin.android firebase-authentication

我想将FirebaseAuth封装到类 AuthService 中。

我也可以登录。。但是我无法从Firebase获取该事件,因为它无法在AuthService类内通知我的侦听器。

当我从LoginActivity中按下登录按钮时,我可以在控制台中看到用户已登录。

  

10-29 21:45:34.519 D / FirebaseAuth(28144):通知ID令牌侦听器有关用户(mvBkX8YferS6XVdqnUeSLu2yldp2)。

     

10-29 21:45:34.527 D / FirebaseApp(28144):通知身份验证状态侦听器。

     

10-29 21:45:34.528 D / FirebaseApp(28144):通知了0个身份验证状态侦听器。

这是AuthService类:

 public class AuthService : Java.Lang.Object, IOnSuccessListener, IOnFailureListener
{
    public User CurrentUser;
    private FirebaseAuth firebaseAuth;

    private static AuthService _instance = null;
    private static System.Object _mutex = new object();

    public IntPtr Handle {get;}

    public static AuthService GetInstance()
    {
        if (_instance == null)
        {
            lock (_mutex) // now I can claim some form of thread safety...
            {
                if (_instance == null)
                {
                    _instance = new AuthService();
                }
            }
        }
        return _instance;
    }

    public AuthService()
    {
       Initialise();
    }

    private void Initialise()
    {
        this.firebaseAuth = FirebaseAuth.Instance;

        if (FirebaseAuth.Instance.CurrentUser != null)
        {
            this.CurrentUser = User.GetInstance();
        }
    }

    public FirebaseUser GetUser()
    {
        FirebaseUser user;

        if (FirebaseAuth.Instance.CurrentUser != null)
        {
            user = FirebaseAuth.Instance.CurrentUser;
        }
        else
        {
            user = null;
        }
        return user;
    }


    public void SignInWithEmailAndPassword(string email, string password)
    {
        FirebaseAuth.Instance.SignInWithEmailAndPassword(email, password)
            .AddOnSuccessListener(this)
            .AddOnFailureListener(this);
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        this.CurrentUser = User.GetInstance();

        MyApplication.Context.StartActivity(typeof(MainActivity));
    }
  }
}

LoginActivity:

 public class LoginActivity : Activity
{
    AuthService _AuthService;
    private EditText loginMail;
    private EditText loginPassword;
    private Button buttonLogin;
    private Button buttonGoToCreateAccount;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_login);

        loginMail = FindViewById<EditText>(Resource.Id.emaillogin);
        loginPassword = FindViewById<EditText>(Resource.Id.passwordlogin);
        buttonLogin = FindViewById<Button>(Resource.Id.loginbutton);

        buttonLogin.Click += (sender, e) =>
        {
        AuthService.GetInstance().SignInWithEmailAndPassword(loginMail.Text, loginPassword.Text);
        };
    }
}

为什么将OnSuccess侦听器实现为非活动类却无法获取事件。我已经使FirebaseAuth可以直接从Activity直接工作,但是我想封装身份验证。

有人暗示吗?

1 个答案:

答案 0 :(得分:0)

我终于设法做到了。

这是身份验证 AuthListeners 的侦听器类:

 public class AuthListener : Java.Lang.Object, IOnSuccessListener, IOnFailureListener
{
    public delegate void OnAuthFailure(string error);
    public event OnAuthFailure OnAuthFailureEvent;

    public delegate void OnAuthSuccess();
    public event OnAuthSuccess OnAuthSuccessEvent;

    public AuthListener()
    {
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        Console.WriteLine("success");
        OnAuthSuccessEvent?.Invoke();
    }

    public void OnFailure(Java.Lang.Exception e)
    {
        Console.WriteLine("failure: " + e.Message);
        OnAuthFailureEvent?.Invoke(e.Message);
    }
}

这是 AuthService 类:

 public class AuthService
{
    private FirebaseAuth firebaseAuth;

    public AuthService()
    {
       Initialise();
    }

    private void Initialise()
    {
        this.firebaseAuth = FirebaseAuth.Instance;
    }    

    public void SignInWithEmailAndPassword(string email, string password, AuthListener authListener)
    {
        FirebaseAuth.Instance.SignInWithEmailAndPassword(email, password)
            .AddOnSuccessListener(authListener)
            .AddOnFailureListener(authListener);
    }

    public void CreateUserWithEmailAndPassword(string email, string password, string userName, AuthListener authListener)
    {
        FirebaseAuth.Instance.CreateUserWithEmailAndPassword(email, password)
            .AddOnFailureListener(authListener)
            .AddOnSuccessListener(authListener);
    }

    public void SignOut()
    {
        FirebaseAuth.Instance.SignOut();
    }
}

然后在login || create_account活动||片段中,我只调用Auth服务并从AuthListeners订阅该事件。

具有 LoginActivity 的示例:

 public class LoginActivity : Activity
{
    AuthListener _authListener;
    AuthService _authService;

    private EditText loginMail;
    private EditText loginPassword;
    private Button buttonLogin;
    private Button buttonGoToCreateAccount;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_login);

        _authListener = new AuthListener();
        _authService = new AuthService();
        Subscribe();

        loginMail = FindViewById<EditText>(Resource.Id.emaillogin);
        loginPassword = FindViewById<EditText>(Resource.Id.passwordlogin);
        buttonLogin = FindViewById<Button>(Resource.Id.loginbutton);
        buttonGoToCreateAccount = FindViewById<Button>(Resource.Id.goto_create_account);


        buttonLogin.Click += (sender, e) =>
        {
            _authService.SignInWithEmailAndPassword(loginMail.Text, loginPassword.Text, this._authListener );
        };

        buttonGoToCreateAccount.Click += (sender, e) =>
        {
            UnSubscribe();

            StartActivity(typeof(CreateAccountActivity));
            Finish();
        };
    }

    private void UnSubscribe()
    {
        _authListener.OnAuthFailureEvent -= ShowErrorDialog;
        _authListener.OnAuthSuccessEvent -= AuthSuccess;
    }

    private void Subscribe()
    {
        _authListener.OnAuthFailureEvent += ShowErrorDialog;
        _authListener.OnAuthSuccessEvent += AuthSuccess;
    }

    private void AuthSuccess()
    {
        StartActivity(typeof(DashboardActivity));
        Finish();
    }

    private void ShowErrorDialog(string error)
    {
        this.RunOnUiThread(() =>
        {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.SetTitle("Error");
            alertDialog.SetMessage(error);
            alertDialog.SetNeutralButton("Try again!", delegate
            {
                alertDialog.Dispose();
            });
            alertDialog.Show();
        });
    }
}

我现在可以说我封装了Firebase Authenticate服务,因此,如果有一天我最终想离开firebase来使用另一项服务,那将不会是一团糟,或者至少是一团糟。