Top Banner
© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Olivier Klein 奧樂凱 Solutions Architect, Greater China April 2016 Build Mobile Apps using AWS SDKs and Mobile Hub
51

Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Apr 16, 2017

Download

Technology

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Olivier Klein 奧樂凱Solutions Architect, Greater China

April 2016

Build Mobile Apps using

AWS SDKs and Mobile Hub

Page 2: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Manage users and identity providers

and sync prefs across devices

Securely access

cloud resources

Test across multiple devices

and operating systems

Track active users,

engagement

Run stateless custom

code without servers

Store user-generated content

and share it

Deliver content quickly globally

Bring users back to your app by sending

messages reliably

Store and query fast NoSQL data

across users and devices

Collect real-time event logs

and take actions quickly

Page 3: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 4: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

SDKs

Java Python (boto) PHP .NET Ruby Node.js

iOS Android Go

JavaScript

C++

Page 5: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

OK let’s build an App!

Page 6: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 7: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

• Authenticates your users

• Facebook, Google,

Amazon,Twitter, OpenID

• Anonymous

• Manages the users and

synchronize data across

multiple devices

• Allows secure communication

with other AWS services

Amazon Cognito

Amazon

Cognito

Page 8: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Initialize the Cognito Client

CognitoCachingCredentialsProvider cognitoProvider =

new CognitoCachingCredentialsProvider(

myActivity.getContext(), // get the context for the current activity

"AWS_ACCOUNT_ID",

"COGNITO_IDENTITY_POOL_ID",

"arn:aws:iam::AWS_ACCOUNT_ID:role/UNAUTHENTICATED_ROLE",

"arn:aws:iam::AWS_ACCOUNT_ID:role/AUTHENTICATED_ROLE",

Regions.US_EAST_1

);

// Create a service client with the provider

AmazonDynamoDB client = new AmazonDynamoDBClient(cognitoProvider);

Page 9: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Store and Synchronize Data

CognitoSyncManager syncClient = new

CognitoSyncManager(myActivity.getContext(),

COGNITO_POOL_ID, Regions.YOUR_REGION, cognitoProvider);

Dataset dataset = client.openOrCreateDataset("myDataset");

dataset.put("myKey", "my value");

String value = dataset.get("myKey");

dataset.remove("myKey");

dataset.synchronizeOnConnectivity(this, syncCallback);

Page 10: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 11: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Control access to your AWS resources

• Create users, groups or roles

• Fine grained control access control with IAM

policies

• Control who can do what from where

• Permit resource access social identities

• Easily add multi factor authentication using

hardware tokens or smartphone apps

Identity and Access Management (IAM)

Page 12: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

{

"Effect":"Allow",

"Action":["s3:*"],

"Resource":"*"

}

{

"Effect": "Allow",

"Action": ["cognito-sync:*"],

"Resource": "*"

}

{

"Effect": "Deny",

"Action": ["dynamodb:*"],

"Resource": "*"

}

Allow

Actions:

All S3

Sync store Operations

Resource:

All resources within

these services

Deny

Actions:

All DDB Operations

Resource:

All resources

Access Policy for IAM Role

Page 13: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Allow

Actions:

S3 Get/Put operations

Resource:

Only to a specific part

of bucket to that identity

{

"Effect": "Allow”,

"Action": ["s3:GetObject","s3:PutObject"],

"Resource": ["arn:aws:s3:::

myBucket/amazon/myapp/${cognito-identity.amazonaws.com:sub}"]

}

Allow

Actions:

DDB Get/Put operations

Resource:

Only to a specific cells in

the database

{

"Effect": "Allow”,

"Action": ["dynamodb:GetItem", "dynamodb:PutItem"],

"Resource" : [ "arn:aws:dynamodb:REGION:12345:table/TABLE_NAME”],

"Condition": {

"ForAllValues:StringEquals”:{

"dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"],

"dynamodb:Attributes”: ["Wins","Losses”,"TopScore",”DateTime" ]

},

}

Access Policy Restriction (Policy Variables)

Page 14: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 15: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

AWS Device Farm

• Test your app on real devices in the

AWS cloud

• Fully managed and scalable test

platform

• Many different smartphone and tablet

models available

• Full built-in test suite

• Integration with custom frameworks

(e.g. Appium, Calabash etc.)

AWS Device

Farm

Page 16: Build Mobile Apps using AWS SDKs and AWS Mobile Hub
Page 17: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 18: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile Analytics

• Allows to collect, visualize and

understand your mobile app

usage

• Scales seamlessly to billions of

events per day

• You retain full control and

ownership of the data

Amazon Mobile

Analytics

Page 19: Build Mobile Apps using AWS SDKs and AWS Mobile Hub
Page 20: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Get insights into app

specific actions that

your users take

Examples

Track the number of

Likes/Shares in a

news app

Player abort rates

per level in a game

Number of songs

playedin a music app

In-app purchase item

popularity

Custom Events

Page 21: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Initialize Mobile Analytics

// Within your activity

private static MobileAnalyticsManager analytics;

// Within your activity onCreate()

try {

AnalyticsConfig options = new AnalyticsConfig();

options.withAllowsWANDelivery(true);

analytics = MobileAnalyticsManager.getOrCreateInstance(

getApplicationContext(),

"YOU MOBILE ANALYTICS APP ID",

Regions.US_EAST_1,

cognitoProvider

);

} catch(InitializationException ex) {

Log.e(this.getClass().getName(), "Failed to initialize Mobile Analytics", ex);

}

Page 22: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 23: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

AWS Lambda

• Run your code in the cloud, fully

managed and highly-available

• Triggered through API calls or

state changes in your setup (S3,

DynamoDB, SNS, Kinesis)

• Scales automatically to match

the incoming event rate

• Charged per 100ms execution

time

Amazon

Kinesis

Amazon Lambda

Amazon

S3

Amazon

DynamoDBAmazon API

Gateway

Amazon

SNS

Page 24: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Adding a Lambda Backend to your App

Initialize the LambdaFactory and define the Interface for the functions

Call synchronize on the dataset

Create the Lambda Function

lambda = new LambdaInvokerFactory(context, Regions.US_WEST_2, provider);

//interface

@LambdaFunction(functionName="cloudFunction”)

String localFunction(String nameInfo);

lambda.localFunction(“Hello From “); // this will output “Hello From Lambda”

exports.handler = function(event, context) {

context.done(null, event + 'Lambda'); // SUCCESS with message

};

Page 25: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

How to build an even better backend?

Back-end logic DatabaseMobile

Page 26: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Microservices with API Gateway and Lambda

Amazon

Lambda

Amazon API

Gateway

Amazon

DynamoDB

Microservice

Page 27: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon API Gateway

• Fully managed and scalable RESTful

API gateway service

• Powered through our content

delivery network via our 53 global

edge locations

• Provides DDoS protection and

throttling capabilities

• Multiple API stages which you define

(e.g. dev, test, prod)

AWS Lambda

Amazon API

Gateway

Amazon

EC2

AWS API

On-prem

server

Page 28: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

When to choose API Gateway vs. Direct SDK?

• Amazon API Gateway adds an additional layer

between your mobile users and your logic and

data stores in order to:

• Allow back-end logic to be interchanged without

mobile app code modifications

• Ability to throttle individual users or requests

• Protect against DDoS attacks including

counterfeit requests (Layer 7) and SYN floods

(Layer 3)

• Provides a caching layer for your calls

• Enables CORS for all AWS service for web apps

Page 29: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 30: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon S3 & Amazon CloudFront

• Amazon S3

• Highly available object storage

• Designed for 99.999999999% durability

• Offers HTTP / HTTPS endpoint to objects

• Amazon CloudFront

• Content Delivery Network with 54 edge

locations across the world

• Caches content on edge locations for low

latency

Amazon S3

Amazon

CloudFront

Page 31: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

// Creating the transfer utility

AmazonS3 s3 = new AmazonS3Client(cognitoProvider);TransferUtility transferUtility =

new TransferUtility(s3, getApplicationContext());

// Upload file

TransferObserver observer = transferUtility.upload(bucket, filename, file);

// Download image

TransferObserver observer = transferUtility.download(bucket, filename, file);

Use Transfer Utility for S3

Page 32: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 33: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon SNS Mobile Push Notifications

• Amazon SNS is a fully

managed, cross-platform

mobile push intermediary

service

• Fully scalable to millions

of devices

• Allows to create topics

(e.g. per geo, interest,

usage pattern etc.)

Amazon SNS

Apple APNS

Google GCM

Amazon ADM

Windows WNS and

MPNS

Baidu CP

Android Phones and Tablets

Apple iPhones and iPads

Kindle Fire Devices

Android Phones and Tablets in China

iOS

Windows Phone Devices

Amazon

SNS

Page 34: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

AmazonSNSClient snsClient = new AmazonSNSClient();

CreatePlatformEndpointRequest request = new CreatePlatformEndpointRequest()

.withPlatformApplicationArn(platformApplicationArn)

.withToken(deviceToken);

//register deviceCreatePlatformEndpointResult result =

snsClient.createPlatformEndpoint(request);

Device Registration – Code example

Page 35: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

var sns = new SNS({ region: ’ap-southeast-1’});

// send message to single device (could also be a topic)

var endpointArn = 'arn:aws:sns:ap-southeast-1:12345678:endpoint/5d3954e1-7d68-365a-80c2-95ae98ae4336';

// Message to send

var message = ’New player just joined your game!';

sns.sendMessage(endpointArn, message, function(err, messageId) {

if (err)

console.log(’Error occured with device %s', endpointArn);

});

Send Push Notifications via AWS Lambda

Page 36: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 37: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon DynamoDB

• Schemaless Data Model

• Seamless scalability

• No storage or throughput limits

• Consistent low latency performance

• High durability and availability

• Replicated across 3 facilities

DynamoDB

table

items

attributes

Fully Managed NoSQL Database Service

Page 38: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

@DynamoDBTable(tableName = ”User")

public static class User {

private String hash, nickname, avatar;

private int score;

@DynamoDBHashKey(attributeName = ”hash")

public String getHash() {

return hash;

}

public void setHash(String hash) {

this.hash = hash;

}

@DynamoDBAttribute(attributeName=”nickname")

public String getNickanme() {

return nickname;

}

...

hash nickname avatar score

abce6 Oli4 s3://bkt/av1.jpg 1500

feru64 LoLZ s3://bkt/lolz56.jpg 800

4568c L33t s3://bkt2/cat.png 750

Table: User

Object Mapper Example - Class

Page 39: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

// Create a user object

User user = new User();

note.setHash(”abce64”);

note.setNickname(”Oli4");

note.setAvatar(”s3://mybucket/av1.jpg");

note.setScore(0);

// Save user object to DynamoDB

mapper.save(user);

// Update score and save user again

user.setScore(user.getScore()+100);

mapper.save(user);

// Load another user

User anotherUser = mapper.load(User.class,”asian_tiger_1234”);

Object Mapper Example – Store and Update

Page 40: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 41: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Stream in Real Time: Amazon Kinesis

• Real-Time Data Processing over

large distributed streams

• Elastic capacity that scales to

millions of events per second

• React In real-time upon incoming

stream events

• Reliable stream storage

replicated across 3 facilitiesAmazon Kinesis

Page 42: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

KinesisRecorder

String kinesisDirectory = "YOUR_UNIQUE_DIRECTORY";

KinesisRecorder recorder = new KinesisRecorder(

cognitoProvider,

Regions.AP_SOUTHEAST_1,

getDir(kinesisDirectory, MODE_PRIVATE));

recorder.saveRecord(”Message1".getBytes(),"MyStreamName");

recorder.saveRecord(”Message2".getBytes(),"MyStreamName");

recorder.submitAllRecords();

Page 43: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Process and Notify in AWS Lambda

exports.handler = function(event, context) {

event.Records.forEach(function(record) {

payload = new Buffer(record.kinesis.data, 'base64').toString('ascii');

UserEvent event = new UserEvent(payload);

if (event.position == TREASURE_BONUS_COORD) {

var message = ’You found the special treasure!';

sns.sendMessage(endpointArn, message);

}

});

context.succeed();

};

Page 44: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Page 45: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Great, AWS has all we need, but it’s a bit complex!

Page 46: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

AWS Mobile Hub

• Allows to build mobile apps within

minutes

• Single integrated console to use all

AWS services for mobile

• Automatically provisions all necessary

AWS services based on selected features

• Automatic code generation for iOS

(Objective-C / Swift) and Android

• Uses security best practices with

AWS IAM

Page 47: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

AWS Mobile Hub

Page 48: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Create a project and add features

Page 49: Build Mobile Apps using AWS SDKs and AWS Mobile Hub
Page 50: Build Mobile Apps using AWS SDKs and AWS Mobile Hub
Page 51: Build Mobile Apps using AWS SDKs and AWS Mobile Hub

Thank you!

Olivier Klein 奧樂凱Solutions Architect, Greater China