如何将设备令牌从 Android MainActivity 传递给 PCL?

How to pass device token to PCL from Android MainActivity?

我在 MainActivity.cs 文件中添加了用于生成设备 ID 的代码。现在我想将该设备令牌传递到我的 PCL 项目主页,这怎么可能?我也想知道如何在 IOS 应用程序中生成设备令牌?以及如何将该令牌传递给便携式 Class 图书馆?

代码示例:

 public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
        if (Intent.Extras != null)
        {
            foreach (var key in Intent.Extras.KeySet())
            {
                var value = Intent.Extras.GetString(key);
                Log.Debug("Key: {0} Value: {1}", key, value);
            }
        }
        FirebaseApp.InitializeApp(this);
        var instanceId = FirebaseInstanceId.Instance;
        if (FirebaseInstanceId.Instance.Token != null)
            Log.Debug("MyToken", FirebaseInstanceId.Instance.Token.ToString());            
    }
}

我需要这个 "My Token" 登录页面按钮点击事件的数据。这怎么可能?

我的登录页面代码是

 public partial class LoginPage : ContentPage
{
    private readonly DataService _dataService = new DataService();
    public LoginPage()
    {
        InitializeComponent();

    }

    private async Task BtnLogin_ClickedAsync(object sender, EventArgs e)
    {
        var result = await _dataService.Authentication(TxtUserName.Text, TxtPassword.Text,"MyToken");
        if (result.AccessToken != null)
        {
            await Navigation.PushModalAsync(new MainMasterPage());
            GlobalClass.userToken = result;
        }
        else
            await DisplayAlert("", Resource.InvalidMessage, Resource.OkText);

    }
}

欢迎来到依赖注入领域 :)

documentation can be found here

您需要在 PCL 上创建一个界面,然后在您的 Native 项目上引用它

示例: 在您的 PCL

中创建 class DeviceToke.cs
public interface ITextToSpeech
{
    void Speak(string text);
}

然后在您的原生项目中,您可以执行以下操作:

示例代码:

[assembly: Dependency(typeof(TextToSpeechAndroidImpl))]
namespace IocAndDiXamarinForms.Droid
{
    public class TextToSpeechAndroidImpl : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener
    {
        TextToSpeech speaker;
        string toSpeak;

        public void Speak(string text)
        {
            var ctx = Forms.Context; // useful for many Android SDK features
            toSpeak = text;
            if (speaker == null)
            {
                speaker = new TextToSpeech(ctx, this);
            }
            else
            {
                var p = new Dictionary<string, string>();
                speaker.Speak(toSpeak, QueueMode.Flush, p);
            }
        }

        #region IOnInitListener implementation
        public void OnInit(OperationResult status)
        {
            if (status.Equals(OperationResult.Success))
            {
                var p = new Dictionary<string, string>();
                speaker.Speak(toSpeak, QueueMode.Flush, p);
            }
        }
        #endregion
    }
}

您可以使用 the Xamarin messaging center 将消息从特定于平台的 classes 传递回您的 PCL ViewModel。您需要在 VM 中订阅消息,并从 Android 或 iOS class 发送消息。然后您可以将值存储在您的 VM 中,并在用户单击登录时使用它。

正在发送消息:

Xamarin.Forms.MessagingCenter.Send(FirebaseInstanceId.Instance.Token.ToString(), "InstanceId");

正在您的 VM 中订阅:

MessagingCenter.Subscribe<string> (this, "InstanceId", (InstanceId) => {
            // use the InstanceId as required
        });
    });

一个方便的解决方案是在某些 public class 中定义一个 public 可访问的静态 StrToken 属性,例如App:

public static Size Token;

和 Android 上的 OnCreate:

App.StrToken = FirebaseInstanceId.Instance;