SNS手机推送

SNS Mobile Push

我目前正在 Xamarin 中开发 Android 应用程序。我正在使用 AWS SNS 推送和 Google Cloud Messenger (GCM)。

我一直在密切关注这个演练: http://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/getting-started-sns-android.html

我一直在使用的代码与那里的代码非常相似。但是,我有一个注册意向服务,其工作方式如下:

  [Service(Exported = false)]
  public class RegistrationIntentService : IntentService
  {
    private static object locker = new object();

    public RegistrationIntentService() : base("RegistrationIntentService") { }

    protected override void OnHandleIntent(Intent intent)
    {
        try
        {
            Logging.LogMessage(Application, "RegistrationIntentService", "Calling InstanceID.GetToken", LogType.Debug);
            lock (locker)
            {
                var instanceID = InstanceID.GetInstance(Application.Context);
                Constants.token = instanceID.GetToken(
                    Constants.senderId, GoogleCloudMessaging.InstanceIdScope, null);

                Logging.LogMessage(Application, "RegistrationIntentService", "GCM Registration Token: " + Constants.token, LogType.Debug);
                /*SendRegistrationToAppServer(token).GetAwaiter().GetResult();

                Log.Info("RegistrationIntentService", "Registered");*/

                SendRegistrationToAppServer(Constants.token).GetAwaiter().GetResult();

                Logging.LogMessage(Application, "RegistrationIntentService", "Registered", LogType.Debug);

                Subscribe(Constants.token);
            } // Release lock

        }
        catch (Exception e)
        {
            Logging.LogMessage(Application, "RegistrationIntentService", "Failed to get a registration token. Exception:\n" + e.ToString(), LogType.Error);
        }
    }

    private async System.Threading.Tasks.Task SendRegistrationToAppServer(string token)
    {
        var config = new AmazonSimpleNotificationServiceConfig()
        {
            RegionEndpoint = RegionEndpoint.USEast1
        };

        var credentials = new BasicAWSCredentials(Constants.accessKeyId, Constants.secretAccessKey);

        Constants.client = new AmazonSimpleNotificationServiceClient(credentials, config);

        Logging.LogMessage(this, "RegistrationIntentService.SendRegistrationToAppServer", "Created client", LogType.Debug);

        if (Constants.createdEndpoint == null)
        {
            var endpoint = new CreatePlatformEndpointRequest()
            {
                PlatformApplicationArn = Constants.endPoint,
                Token = token
            };

            var endpointResponse = await Constants.client.CreatePlatformEndpointAsync(endpoint);
            Logging.LogMessage(this, "RegistrationIntentService.SendRegistrationToAppServer", "Got endpoint. ARN: " + endpointResponse.EndpointArn, LogType.Debug);
            Constants.createdEndpoint = endpointResponse.EndpointArn;
        }

        // Make sure we haven't subscribed yet
        if (Constants.createdEndpoint != null && Constants.subscriptionArn == null)
        {
            var subscription = await Constants.client.SubscribeAsync(Constants.topicARNBeginning + Constants.devicePhoneNumber, "Application", Constants.createdEndpoint);
            Logging.LogMessage(this, "RegistrationIntentService.SendRegistrationToAppServer", "AWS Subscribed", LogType.Debug);
        }
    }

    private bool Subscribe(string token)
    {
        var pubSub = GcmPubSub.GetInstance(Application.Context);
        const string topic = "/topics/global";

        try
        {
            pubSub.Subscribe(token, topic, null);
            Logging.LogMessage(this, "RegistrationIntentService.Subscribe", "GCM Subscribed", LogType.Debug);
            return true;
        }
        catch (Java.IO.IOException)
        {
            try
            {
                pubSub.Unsubscribe(token, topic);

                pubSub.Subscribe(token, topic, null);

                return true;
            }
            catch (Java.IO.IOException)
            {
                Logging.LogMessage(Application, "Subscribe", "Failed to register", LogType.Error);
                return false;
            }
        }
    }
}

我在 MainActivity OnCreate 事件处理程序中使用 StartService() 调用显式启动注册意向服务。我确保设置了文档中要求的所有权限:

[assembly: UsesPermission(Android.Manifest.Permission.ReceiveBootCompleted)]
[assembly: UsesPermission (Android.Manifest.Permission.Internet)]
[assembly: UsesPermission (Android.Manifest.Permission.WakeLock)]
[assembly: UsesPermission(Android.Manifest.Permission.Vibrate)]
[assembly: UsesPermission("com.google.android.c2dm.permission.RECEIVE")]
[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE", ProtectionLevel = Protection.Signature)]
[assembly: UsesPermission("@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission("com.google.android.c2dm.permission.SEND")]

我的大部分 Android 清单都是通过 AssemblyInfo.cs 和适当的 C# 属性(例如 [Service] 属性)创建的。我在 XML 中唯一明确声明的(除申请外)如下:

<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.gcmmessaging" />
        </intent-filter>
    </receiver>

这是最终清单:

<?xml version="1.0" encoding="UTF-8"?>
<manifest android:installLocation="auto" android:versionName="1.0" android:versionCode="1" package="com.gcmmessaging" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="16"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<permission android:name="com.gcmmessaging.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="com.gcmmessaging.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.SEND"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application android:name="mono.android.app.Application"
             android:allowBackup="true"
             android:debuggable="true"
             android:icon="@drawable/sns_icon_48"
             android:label="ProductName">
             <receiver android:name="com.google.android.gms.gcm.GcmReceiver"
                    android:permission="com.google.android.c2dm.permission.SEND"
                    android:exported="true">
                    <intent-filter>
                        <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
                        <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
                        <category android:name="com.gcmmessaging"/>
                    </intent-filter>
            </receiver>
            <meta-data android:name="com.google.android.gms.version"
                        android:value="@integer/google_play_services_version"/>
            <activity android:name="[ConfigurationName]"
                        android:label="Configuration"/>
            <receiver android:name="md503b8085957a5cb3d4167d0e7cbb2a6b0.GCMBootReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED"/>
                </intent-filter>
            </receiver>
            <service android:name="md503b8085957a5cb3d4167d0e7cbb2a6b0.GCMIntentService" android:exported="false"/>
            <receiver android:name="md503b8085957a5cb3d4167d0e7cbb2a6b0.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
                <!-- It did occur to me to try to put all of these in a single  -->
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
                    <category android:name="com.gcmmessaging"/>
                    </intent-filter>
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
                    <category android:name="com.gcmmessaging"/>
                </intent-filter>
                <intent-filter>
                    <action android:name="com.google.android.gcm.intent.RETRY"/>
                    <category android:name="com.gcmmessaging"/>
                </intent-filter>
            </receiver>
            <activity android:name="[Activityname]" android:label="History"/>
            <service android:name="md503b8085957a5cb3d4167d0e7cbb2a6b0.MyInstanceIdListenerService" android:exported="false">
                <intent-filter>
                    <action android:name="com.google.android.gms.iid.InstanceID"/>
                </intent-filter>
            </service>
            <activity android:name="[ActivityName]" android:icon="@drawable/sns_icon_32" android:label="ProductName">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
            <service android:name="md503b8085957a5cb3d4167d0e7cbb2a6b0.RegistrationIntentService" android:exported="false"/>
            <receiver android:name="md5343e36a1bb0d551a047a1a24886e23d0.NetworkReachability_NetworkStatusChangeBroadcastReceiver"/>
            <provider android:name="com.google.android.gms.measurement.AppMeasurementContentProvider" android:exported="false" android:authorities="com.gcmmessaging.google_measurement_service"/>
            <service android:name="com.google.android.gms.measurement.AppMeasurementService" android:exported="false" android:enabled="true"/>
            <receiver android:name="com.google.android.gms.measurement.AppMeasurementReceiver" android:enabled="true">
                <intent-filter>
                    <action android:name="com.google.android.gms.measurement.UPLOAD"/>
                </intent-filter>
            </receiver>
            <provider android:name="mono.MonoRuntimeProvider" android:exported="false" android:authorities="com.gcmmessaging.mono.MonoRuntimeProvider.__mono_init__" android:initOrder="2147483647"/>
    <!--suppress ExportedReceiver-->
    <receiver android:name="mono.android.Seppuku">
        <intent-filter>
            <action android:name="mono.android.intent.action.SEPPUKU"/>
            <category android:name="mono.android.intent.category.SEPPUKU.com.gcmmessaging"/>
        </intent-filter>
    </receiver>
</application>
</manifest>

这是我的广播接收器:

[BroadcastReceiver(Permission = "com.google.android.c2dm.permission.SEND")]
[IntentFilter(new string[] {
  "com.google.android.c2dm.intent.RECEIVE"}, Categories = new string[] {
  "@PACKAGE_NAME@" })]
[IntentFilter(new string[] {
  "com.google.android.c2dm.intent.REGISTRATION"}, Categories = new string[] {
  "@PACKAGE_NAME@" })]
[IntentFilter(new string[] {
  "com.google.android.gcm.intent.RETRY"}, Categories = new string[] {
  "@PACKAGE_NAME@" })]
public class GCMBroadcastReceiver : WakefulBroadcastReceiver
{
    //private const string TAG = "PushHandlerBroadcastReceiver";

    public override void OnReceive(Context context, Intent intent)
    {
        Logging.LogMessage(context, "GCMBroadcastReceiver.OnReceive", "Received message", LogType.Debug);

        GCMIntentService.RunIntentInService(context, intent);
        SetResult(Result.Ok, null, null);

        Logging.LogMessage(context, "GCMBroadcastReceiver.OnReceive", "Ran intent service", LogType.Debug);
    }
}

我目前收到一个 GCM 令牌并正确订阅 GCM 和 SNS。我仔细检查了那里的 return 代码,我肯定得到了一个看起来有效的 GCM 令牌,我的订阅显示在 SNS 中。我订阅 GCM 的调用成功,没有抛出任何异常。但是,我实际上没有收到任何推送。我知道 AWS 实际上正在发布数据(如果我创建电子邮件订阅,我会收到我发送的所有内容)。我也知道问题不是由我的公司防火墙引起的 - 如果我尝试通过 4G 进行操作,它也会失败。

我的日志中确实出现了以下两个错误: 03-11 16:33:08.914 E/GcmReceiver( 7749):无法解析目标意图服务,跳过类名实施 03-11 16:33:08.914 E/GcmReceiver( 7749):传递消息时出错:找不到 ServiceIntent。

我不确定这些是否是原因。我还没有在网上找到好的解决方案。

有人对尝试什么(或如何进行调试)有任何建议吗?老实说,我在这里有点不知所措。

您正在混合 API,一方面您使用新的 InstanceId API 来获取令牌,另一方面您使用旧的方式使用 wakefulbroadcastreceiver 接收数据,替换您的具有来自 GcmListenerService 的派生类型的接收器,如下所示:

[Service (Exported = false), IntentFilter (new [] { "com.google.android.c2dm.intent.RECEIVE" })]
public class SignalGCMReceiver : GcmListenerService
{

    public override void OnMessageReceived (string from, Bundle data)
    {
        Console.WriteLine(data.ToString());

    }
}

最后在manifest中添加receiver(receiver由服务内部实现):

    <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="@PACKAGE_NAME@" />
        </intent-filter>
    </receiver>