C# Xamarin Android后台服务
我已经学习了一些关于自定义服务的教程,这些教程都是关于在应用程序处于后台或被杀死时运行(包括Xamarin的),但我自己没能让它工作 我假装的是: 1-Firebase服务向设备发送通知。此服务在后台/非后台工作 2-每当fcm服务执行时,我的自定义服务必须执行一个小功能。特别是如果应用程序在后台/被杀死。 如果应用程序在前台运行,我的服务也会运行 有人能指出我在哪里失败了吗?(或者帮助我了解更好的后台服务?) 到目前为止,我的代码是: 海关服务C# Xamarin Android后台服务,c#,android,xamarin,background,xamarin.android,C#,Android,Xamarin,Background,Xamarin.android,我已经学习了一些关于自定义服务的教程,这些教程都是关于在应用程序处于后台或被杀死时运行(包括Xamarin的),但我自己没能让它工作 我假装的是: 1-Firebase服务向设备发送通知。此服务在后台/非后台工作 2-每当fcm服务执行时,我的自定义服务必须执行一个小功能。特别是如果应用程序在后台/被杀死。 如果应用程序在前台运行,我的服务也会运行 有人能指出我在哪里失败了吗?(或者帮助我了解更好的后台服务?) 到目前为止,我的代码是: 海关服务 FIREBASE实现 我不久前解决了我的问题,
FIREBASE实现
我不久前解决了我的问题,因为我看到没有其他人回答,我将发布我的解决方案,以防其他人有此问题: 失败的原因很简单,就是从未在后台调用OnMessageReceived。我通过使用HandleIntent绕过了这个问题,这使得我的后台服务变得不必要,因为:(类是相同的):
附加说明 HandleIntent无法使用RemoteMessage类型,因此(如果我没有弄错的话)它无法检索通知的正文 需要一个自定义通知发送者,以便能够以json的形式手动检索正文 我就是这样建造我的: (警告:代码可能不太整洁。我达到了用头敲击键盘的阶段D:):
我的道歉,我没有说清楚。我现在正在编辑它。firebase服务在后台工作正常或已终止。我失败的是在那些情况下把我的定制服务附加到它上。抱歉迟到了,你可以用来实现这个功能,一个前景服务,它有一个更高的优先级,所以操作系统会考虑它最后被杀死,它避免了你的服务自动瞌睡,以节省电池在以后的API。
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using ME.Leolin.Shortcutbadger;
namespace App1
{
[Service]
public class Badge_Service : Service
{
int n = 0;
public IBinder Binder { get; private set; }
public override IBinder OnBind(Intent intent)
{
Log.Debug("SS", "OnBind");
this.Binder = new Badge_Binder(this);
add_up(n); //custom function
return this.Binder;
}
public override bool StopService(Intent name)
{
return base.StopService(name);
}
public void add_up(int count)
{
count++;
ShortcutBadger.ApplyCount(ApplicationContext, count);
}
}
public class Badge_Binder : Binder
{
public Badge_Service Service { get; private set; }
public Badge_Binder(Badge_Service Service)
{
this.Service = Service;
}
}
public class Badge_Conection : Java.Lang.Object, IServiceConnection
{
MyFirebaseMessagingService activity;
public bool IsConnected { get; private set; }
public Badge_Binder Binder { get; private set; }
public Badge_Conection(MyFirebaseMessagingService activity)
{
IsConnected = false;
Binder = null;
this.activity = activity;
}
public void OnServiceDisconnected(ComponentName name)
{
Log.Debug("SS", "Disconnected");
IsConnected = false;
Binder = null;
}
public void OnServiceConnected(ComponentName name, IBinder Service)
{
Binder = Service as Badge_Binder;
IsConnected = this.Binder != null;
Log.Info("SS", "Connected");
}
}
}
using Android.App;
using Android.Content;
using Firebase.Iid;
using Android.Support.V7.App;
using Android.Media;
using Firebase.Messaging;
namespace App1
{
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseServices : FirebaseInstanceIdService
{
public override void OnTokenRefresh()
{
base.OnTokenRefresh();
MClass.IDfcm = FirebaseInstanceId.Instance.Token; //MClass just stores variables for later use.
Android.Util.Log.Debug("Refreshed Token:", MClass.IDfcm);
}
}
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage msg)
{
base.OnMessageReceived(msg);
sendNotification(msg.GetNotification().Body);
Intent serviceToStart = new Intent(this, typeof(Badge_Service));
BindService(serviceToStart, new Badge_Conection(this), Bind.AutoCreate);
}
private void sendNotification(string msg)
{
var activity = new Intent(this, typeof(LogIn)); //LogIn is my MainActivity
activity.AddFlags(ActivityFlags.ClearTop);
var screen = PendingIntent.GetActivity(this, 0, activity, PendingIntentFlags.OneShot);
var sound = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
var notif = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.Icon)
.SetContentTitle("New Notification")
.SetContentText(msg)
.SetAutoCancel(true)
.SetSound(sound)
.SetContentIntent(screen);
var controller = NotificationManager.FromContext(this);
controller.Notify(0, notif.Build());
}
}
}
public override void HandleIntent(Intent intent)
{
string msg = intent.GetStringExtra("body");
if (msg == null) msg = "New Notification";
ShortcutBadger.ApplyCount(this, Global.countNotifications());
sendNotification(msg);
}
public static string signalFCM(string msg, string user_firebase_id) //This must be gathered by storing a firebase_id created by an android device.
{
try
{
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = user_firebase_id,
notification = new // *** THIS IS HOW FIREBASE SENDS THEM BY DEFAULT
{
body = msg,
title = "MyAPP",
sound = "Enabled"
},
// **** THIS IS THE CUSTOM EXTRA TO RETRIEVE ITS CONTENT ****
data = new
{
body = msg,
title = "MyAPP",
payload = "1"
}
// ******************
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", APP_KEY)); //This must be gathered from the Firebase Console APP page
tRequest.Headers.Add(string.Format("Sender: id={0}", APP_ID)); //This must be gathered from the Firebase Console APP page
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
return sResponseFromServer;
}
}
}
}
}
catch (Exception ex) { return ex.Message; }
}
}