Push-уведомления не приходят

Я разрабатываю приложение для Android с помощью Xamarin, а для push-уведомлений использую PushSharp. У меня проблемы с получением push-уведомлений, когда приложение не запущено (например, после перезагрузки). Вот сервисный код:

[BroadcastReceiver(Permission=GCMConstants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { GCMConstants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "com.xxx" })]
    [IntentFilter(new string[] { GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "com.xxx" })]
    [IntentFilter(new string[] { GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "com.xxx" })]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
    public class PushHandlerBroadcastReceiver : PushHandlerBroadcastReceiverBase<PushHandlerService>
    {
        //IMPORTANT: Change this to your own Sender ID!
        //The SENDER_ID is your Google API Console App Project ID.
        //  Be sure to get the right Project ID from your Google APIs Console.  It's not the named project ID that appears in the Overview,
        //  but instead the numeric project id in the url: eg: https://code.google.com/apis/console/?pli=1#project:785671162406:overview
        //  where 785671162406 is the project id, which is the SENDER_ID to use!
        public static string[] SENDER_IDS = new string[] {"1234"};

        public const string TAG = "PushSharp-GCM";
    }

А вот и созданный appManifest:

 <receiver android:permission="com.google.android.c2dm.permission.SEND" android:name="xxx.PushHandlerBroadcastReceiver">
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.xxx" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="com.xxx" />
      </intent-filter>
      <intent-filter>
        <action android:name="com.google.android.gcm.intent.RETRY" />
        <category android:name="com.xxx" />
      </intent-filter>
    </receiver>
    <service android:name="xxx.PushHandlerService" />

Мой сервисный код очень простой:

[Service] //Must use the service tag
    public class PushHandlerService : PushHandlerServiceBase
    {
        public PushHandlerService () : base (PushHandlerBroadcastReceiver.SENDER_IDS)
        {
        }

        protected override void OnRegistered (Context context, string registrationId)
        {
            ...
        }

        protected override void OnUnRegistered (Context context, string registrationId)
        {
            ...

        }

        protected override void OnMessage (Context context, Intent intent)
        {
            ...
        }

        protected override bool OnRecoverableError (Context context, string errorId)
        {
            ...
        }

        protected override void OnError (Context context, string errorId)
        {
            ...
        }

        void createNotification (string title, string desc, Intent intent)
        {
            ...
        }
    }

Я что-то упускаю? почему служба не запускается после перезагрузки телефона. Стоит ли что-то делать в широковещательном приемнике? Следует ли мне регистрироваться в push-уведомлениях в конструкторе службы (для обработки случая, когда приложение еще не запущено)?


person Amit Raz    schedule 01.05.2014    source источник


Ответы (1)


Если ваша служба не запускается при перезагрузке, вы можете добавить BroadcastReceiver в свой проект, который запускает ее:

[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class MyBootReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        MyNotificationService.RunIntentInService(context, intent);
        SetResult(Result.Ok, null, null);
    }
}

Если вы используете PushSharp, вам, вероятно, удастся добавить этот фильтр к реализации PushHandlerBroadcastReceiverBase.

person Cheesebaron    schedule 02.05.2014
comment
Я пробовал это, но похоже, что он игнорирует этот тип широковещательного приемника ... Я изо всех сил пытаюсь понять, почему ... - person Amit Raz; 03.05.2014
comment
Вчера я работал с уведомлениями весь день, когда я попытался перезагрузить устройство и не смог воспроизвести проблему здесь при использовании фильтра намерений. Итак, вы, должно быть, делаете что-то не так, или, может быть, у вас есть диспетчер задач, убивающий вещи. - person Cheesebaron; 03.05.2014
comment
Я сделаю еще один шанс и посмотрю, что произойдет - person Amit Raz; 03.05.2014
comment
Я пробовал это, но это не работает :( Я очень расстроен. Я просто не получаю трансляцию boot_completed. - person Amit Raz; 08.05.2014