使用AWS SNS将设备订阅到主题
我想构建一个使用GCM
和Amazon SNS
进行推送通知的客户端Android应用程序。 该应用程序的功能之一是建议用户订阅特定的主题/主题。 在用户完成订阅后,他只能得到他订阅的SNS通知。 问题是,是否有可能在客户端进行订阅?
是的,如果你知道主题的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");
}
链接地址: http://www.djcxy.com/p/32159.html