使用AWS SNS将设备订阅到主题

时间:2015-03-25 15:43:38

标签: android amazon-web-services amazon-sns

我想构建一个客户端Android应用,该应用使用GCMAmazon SNS进行推送通知。 该应用程序的一个功能是建议用户订阅特定主题/主题。用户完成订阅后,他应该只获得他订阅的那些SNS通知。 问题是,是否可以在客户端进行订阅?

1 个答案:

答案 0 :(得分:0)

如果你知道主题的ARN(我使用Lambda函数从服务器获取),那就是。代码看起来像这样(请注意,它不是异步的,所以不要在UI线程上使用它):

    AWSMobileClient.initializeMobileClientIfNecessary(getApplicationContext());
    PushManager pushManager = AWSMobileClient.defaultMobileClient().getPushManager();

    AWSCredentials awsCredentials = new BasicAWSCredentials(key, secret);
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if(proxyHost != null){
        clientConfiguration.setProxyHost(proxyHost);
        if(proxyPort != null){
            clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
        }
    }
    clientConfiguration.setProtocol(isSecure ? Protocol.HTTPS : Protocol.HTTP);
    AmazonSNSClient snsClient = new AmazonSNSClient(awsCredentials, clientConfiguration);
    snsClient.setRegion(Region.getRegion(Regions.US_EAST_1));

    ListTopicsResult listTopicsResult = snsClient.listTopics();

    for (Topic topic : listTopicsResult.getTopics()) {
        Log.d(TAG, "found sns topic" +topic.getTopicArn());
    }

    if (listTopicsResult.contains(topicArn){
        Log.d(TAG, "subscribing to " +topicArn);
        subscribeReq = new SubscribeRequest()
                .withTopicArn(topicArn)
                .withProtocol("application")
                .withEndpoint(pushManager.getEndpointArn());

        SubscribeResult subscribeResult = snsClient.subscribe(subscribeReq);

        Log.d(TAG, "subscription arn " +subscribeResult.getSubscriptionArn());
    }else{
        Log.e(TAG, "subscription failed! ARN doesn't exist");
    }