我们的应用使用的服务器可以向手机发送推送通知。但它只能做到这一点,而应用程序至少在后台。一旦作为后台任务(来自任务管理器)被杀死,通知将不再被传递。但是WhatsApp如何做到这一点呢?当我从任务管理器关闭whatsapp时,我仍然收到有关传入消息的通知。
好吧,我可能会提供后台帮助,所以这就是我到目前为止所做的:
private void StartServiceForPushs()
{
Intent intent = new Intent(this, typeof(Activity_MainMenu));
PendingIntent pendingIntent = PendingIntent.GetService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)GetSystemService(Context.AlarmService);
alarm.SetRepeating(AlarmType.RtcWakeup, TimeUtils.CurrentTimeMillis(), 1 * 60000, pendingIntent);
}
这应该设置一个每1分钟检查推送通知的服务 - 但不幸的是,它什么也没做。应用程序完全关闭后,就不会再发布任何消息。任何人都可以帮助我吗?
答案 0 :(得分:1)
好吧,我实际上已经解决了这个问题 - 实际上很简单。只需编写一个返回粘性Start Command Result的服务,如下所示:
[Service]
public class BackgroundService : Service
{
static readonly string TAG = "X:" + typeof(Activity_MainMenu).Name;
static readonly int DELAY_BETWEEN_LOG_MESSAGES = 5000;
static readonly int NOTIFICATION_ID = 10000;
UtcTimestamper timestamper;
Handler handler;
Action runnable;
public override void OnCreate()
{
base.OnCreate();
timestamper = new UtcTimestamper();
handler = new Handler();
runnable = new Action(() =>
{
if (timestamper != null)
{
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
}
});
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) // HIER DRIN MUSS GECALLED WERDEN!
{
DispatchNotificationThatServiceIsRunning();
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnDestroy()
{
base.OnDestroy();
OnCreate();
}
void DispatchNotificationThatServiceIsRunning()
{
Notification.Builder notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.btn_bookoflifeMainMenu)
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText("TESTING");
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_ID, notificationBuilder.Build());
}
}
然后从您应用中的任何活动(例如主菜单)启动您的服务。
这将使应用程序永远在后台运行 - 但在重新启动手机后,应该需要重新启动应用程序。