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

时间:2017-11-09 05:09:59

标签: c# xamarin.forms google-cloud-messaging

我在MainActivity.cs文件中添加了用于生成设备ID的代码。现在我想将该设备令牌传递给我的PCL项目主页,这怎么可能?我还想知道如何在IOS应用程序中生成设备令牌?以及如何将该令牌传递给可移植类库?

代码示例:

 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());            
    }
}

我需要在登录页面按钮Click事件中使用此“我的令牌”数据。这有可能吗?

我的登录页码是

 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);

    }
}

3 个答案:

答案 0 :(得分:1)

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

documentation can be found here

您需要在PCL上创建一个接口,然后在Native项目中引用该接口

实施例: 在PCL中创建类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
    }
}

答案 1 :(得分:1)

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

发送消息:

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

订阅您的虚拟机:

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

答案 2 :(得分:1)

一个方便的解决方案是在某些公共类中定义一个可公开访问的静态cout<<"d"<<*a<<endl; } 属性,例如: StrToken

App
Android上的

和OnCreate:

public static Size Token;