Table of Contents
Setup AWS SDK in Android for S3 Upload/Download
Ok so we already have lots of documentation and articles regarding this topic but very few are beginner friendly or contains all the steps i.e. from the creation of S3 bucket to setting up the AWS SDK in an android app. So here is an article on how to add this functionality to your app.
Setup S3 Bucket
- Firstly, go to the Amazon S3 Console and click on
Create bucket
- Type in the bucket name.
Eg: aws_upload_test
- Select the region for which you want the bucket to be created and click on
Create
- Grant public access to the bucket if you wish to access it from anywhere and through any authenticated mode.
- Now store this bucket name and region safely. If you have a backend, you could store it there using a RESTful API
Setup an Identity Pool Id
- Before going to the below link, make sure you are in the right region. For eg: Asia Pacific (Mumbai) ap-south-1 for India
- Go to AWS Cognito and choose
Manage Identity Pools
- Click
Create New Identity Pool
button on the top left of the console. - Give a name for the Identity pool and check
Enable access to unauthenticated identities
under theUnauthenticated Identities
section, clickCreate pool
button on the bottom right. - To enable Cognito Identities to access your resources, expand the
View Details
section to see the two roles that are to be created. Make a note of theunauth
role whose name is of the formCognito_<IdentityPoolName>Unauth_Role
. Now clickAllow
button in the bottom right of the console. - Under
Get AWSCredentials
section, in the code snippet to createCognitoCachingCredentialsProvider
, find the Identity pool ID and the AWS region and make note of them. You will need to add to the sample application later.
Setup Permissions
- Go to Amazon IAM Console and select “Roles”.
- Select the
unauth
role you just created in step 1, which is of the formCognito_<IdentityPoolName>Unauth_Role
. - Select
Attach Policy
, then findAmazonS3FullAccess
and attach it it to the role. - Note: This will grant users in the identity pool full access to all buckets and operations in S3. In a real app, you should restrict users to only have access to the resources they need.
Setup AWS SDK in Android
Add Libraries
Add the following libraries in your app/build.gradle :-
Review Permissions
Make sure following permissions are present in your project’s Manifest
file :-
Initialize SDK
Create a single instance of AmazonS3Client
throughout your application by adding below lines in your Application Class
. You’ll need to pass the IdentityPoolId
that we created above.
Upload a File
Conclusion
Well there you go, now you know how to setup a S3 bucket, configure the AWS SDK for android and upload an image.
If you have any questions or suggestions, please post them below. I would be more than happy to receive feedback from the community.