我试图通过推送通知将消息显示在手机屏幕上,而不仅仅是在设备的下拉菜单中。 现在,我可以从FireBase获取消息并提醒用户它已到达。这适用于前景和背景。但我想在屏幕上出现某种计数器或警报。也许在标签或文本框中。这适用于Android应用程序,但该项目是使用PCL在Xamari Forms中构建的。
我的令牌类:
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class ForegroundMessages: FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnMessageReceived(RemoteMessage message)
{
//Log.Debug(TAG, "From: " + message.From);
//Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
base.OnMessageReceived(message);
SendNotification(message.GetNotification().Body);
}
private void SendNotification(string body)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
Log.Debug(TAG, "Notification Message Body: " + body);
var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
var notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentTitle("Notification")
.SetContentText(body)
.SetAutoCancel(true)
.SetSound(defaultSoundUri)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
}
我的前台消息传递类:
[Activity(Label = "Watson", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
MobileBarcodeScanner.Initialize(Application);
base.OnCreate(bundle);
// this is registering the services
ServiceContainer.Register<IWebService>(() => new WebService());
ServiceContainer.Register<ISettings>(() => new Settings());
// This is getting the IMEI number this method is unique to android
var telephonyManager = (TelephonyManager)GetSystemService(TelephonyService);
string imei = telephonyManager.DeviceId;
global::Xamarin.Forms.Forms.Init(this, bundle);
Task.Run(() => {
var instanceId = FirebaseInstanceId.Instance;
instanceId.DeleteInstanceId();
Android.Util.Log.Debug("TAG", "{0} {1}", instanceId.Token, instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));
});
LoadApplication(new App(imei));
}
}
对MainActivity进行了一些更改:
{{1}}
似乎有很多这方面的教程,但他们注销调试。这对于实际应用来说基本上是无用的。 如何将消息显示在视图或屏幕上?它甚至不必是一个消息,它甚至可以只是听众知道消息何时到达并提醒用户并让用户选择在弹出窗口或另一个屏幕上阅读消息。
感谢任何帮助。