Subscribe a device to a topic with AWS SNS

I want to build a client Android app which uses GCM and Amazon SNS for push notifications. One of the features of the app is to propose a user to subscribe to a specific topic/topics. After user did the subscription he should get only those SNS notifications he subscribed to. The question is whether it's possible to do the subscription on a client side?


Yes if you know the ARN of the topic (which I'm using a Lambda function to get from the server). The code looks something like this (Note that it's not async so don't use it on the UI thread):

    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");
    }
链接地址: http://www.djcxy.com/p/32160.html

上一篇: 将单个iOS消息发布到多个AWS SNS主题

下一篇: 使用AWS SNS将设备订阅到主题