我想以某种方式存储设备令牌,因为以后可能需要它。例如,用户启动我的应用程序,执行OnNewToken,然后获得设备令牌。现在,我想存储令牌,因为当用户在几天后重新启动我的应用程序时,可能再次需要令牌。我认为当用户重新启动我的应用程序时,不会再次执行OnNewToken,但是我不确定吗?因此,我想存储令牌,如果再次执行OnNewToken来存储新令牌,则只覆盖其值。
此外,我想在另一个类(例如Game1.cs)中使用Android设备令牌。
如何存储设备令牌并在另一个类中获取字符串?
我试图用SharedPrefManager存储令牌,但是它不起作用。我收到错误消息,但不知道如何解决该问题:
SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
错误CS0103:名称'SharedPrefManager'在当前上下文中不存在
错误CS0103:名称'getApplicationContext'在当前上下文中不存在
MyFirebaseMessagingService.cs:
using System;
using Android.App;
using Android.Content;
using Android.Util;
using Firebase.Messaging;
using ggdgdgd.Android;
using System.Collections.Generic;
using Android.Support.V4.App;
namespace Androidproject
{
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnNewToken(string token)
{
Log.Debug(TAG, "Refreshed token: " + token);
storeToken(refreshedToken);
}
private void storeToken(String token)
{
SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
}
public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "From: " + message.From);
var body = message.GetNotification().Body;
var title = message.GetNotification().Title;
Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
SendNotification(body, title, message.Data);
}
void SendNotification(string messageBody, string Title, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(Activity1));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this,
Activity1.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, Activity1.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.Icon)
.SetContentTitle(Title)
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(Activity1.NOTIFICATION_ID, notificationBuilder.Build());
}
}
}
答案 0 :(得分:0)
相当于SharedPreferences
的Xamarin.Android是一个名为ISharedPreferences
的接口。
您可能会这样:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Android.App.Application.Context)
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutString ("key_for_your_token", token);
// editor.Commit(); // older APIs
editor.Apply(); // newer APIs
并获取值:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Android.App.Application.Context)
string token = prefs.GetString ("key_for_your_token", "");