前段时间项目需求需要接入亚马逊的S3云服务存储视频、图片资源,但是发现网上关于Android 端Amazon S3的资料写的都不是特别充足,于是专门写一篇给需要接入此功能的作为参考。
1.准备工作
- 首先你得去Amazon平台注册一个账号传送门
注册账号以后在你的电脑上安装CLI,这个工具是为应用创建,集成和管理AWS云服务。 - 假如你还没有安装:node.js和npm请点击连接下载最新版本
- 安装成功以后在AS的Terminal里面输入 node -v 查看当前node 版本
输入npm -v 查看当前npm版本
- npm更新命令:npm-check 检查更新 npm-upgrade更新,保证正在运行至少运行Node.js的版本大于8.11+,NPM版本大于5.x
2.开始接入
-
先依赖一下所需要的架包
//AWS implementation 'com.amazonaws:aws-android-sdk-s3:2.12.+' implementation('com.amazonaws:aws-android-sdk-mobile-client:[email protected]') { transitive = true } implementation('com.amazonaws:aws-android-sdk-auth-userpools:[email protected]') { transitive = true } implementation 'org.testng:testng:6.9.6' //Base SDK implementation 'com.amazonaws:aws-android-sdk-core:2.12.+' //AppSync SDK implementation 'com.amazonaws:aws-android-sdk-appsync:2.7.+' implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
-
在清单文件里添加
-
输入命令
npm install -g @aws-amplify/cli
输入命令 amplify configure
输入完成以后如图提示跳转到官网去进行用户创建和配置根据网站提示操作
创建完成用户以后会有一个用户的KeyID和Secret access key 记得保存下来
- 在控制台Enter后会提示你选择地区我这里选择的是美国东部,控制台选择的地区和你的桶地区一致。配置好你在官网创建的Access key ID和Secret access key,之后Enter再创建你的文件名。
输入命令 amplify init
初始化配置
- 输入命令
amplify push
最后输入命令 amplify update api
我这里已经配置好了就直接显示了
- 这个时候去你的项目里
./app/src/main/res/raw
查看 可以看见存在一个awsconfiguration.json
的配置文件,Buket
是你的桶名,Region
则是你的地区,之后需要更换桶名和地区直接在这更换就好了。
3.代码部分
- 由于从2.7.0版开始TransferService将不会自动启动或停止TransferUtility。所以你必须在你的
Application
里面添加以下代码去启动TransferService服务。
//AWS 上传
mAWSAppSyncClient = AWSAppSyncClient.builder()
.context(getApplicationContext())
.awsConfiguration(new AWSConfiguration(getApplicationContext()))
.build();
getApplicationContext().startService(new Intent(getApplicationContext(), TransferService.class));
- 上传文件代码,我这里上传一张图片作为案例。Constants类里填好自己的Key和**
private static String IMAGE_DATA_NAME = "public/user2"+DateUtil.getYear()+""+DateUtil.getMonth()+""+DateUtil.getDay()+""+ RandomUntil.getNewRandomCode(6)+".jpg";
//上传头像地址(用于下次加载图片)
private static String PAHT = Constants.AMAZON_S3_PIC + IMAGE_DATA_NAME;
/**
* 上传到AWS
*/
private void AwsTest() {
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails userStateDetails) {
Log.i(TAG, "AWSMobileClient initialized. User State is " + userStateDetails.getUserState());
}
@Override
public void onError(Exception e) {
Log.e(TAG, "Initialization error.", e);
}
});
uploadWithTransferUtility();
}
public void uploadWithTransferUtility() {
AWSCredentials credentials = new BasicAWSCredentials(Constants.AMAZON_S3_KEY, Constants.AMAZON_S3_KEY_PWD);
TransferUtility transferUtility =
TransferUtility.builder()
.context(getApplicationContext())
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.s3Client(new AmazonS3Client(credentials))
.build();
TransferObserver uploadObserver =
transferUtility.upload(
IMAGE_DATA_NAME,
new File(mImageCropPath));
// Attach a listener to the observer to get state update and progress notifications
uploadObserver.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED == state) {
// Handle a completed upload.
LogUtil.d(TAG,"AWS上传图片:"+IMAGE_DATA_NAME+"成功");
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
int percentDone = (int)percentDonef;
Log.d("YourActivity", "ID:" + id + " bytesCurrent: " + bytesCurrent
+ " bytesTotal: " + bytesTotal + " " + percentDone + "%");
}
@Override
public void onError(int id, Exception ex) {
// Handle errors
LogUtil.d(TAG,"AWS上传图片:"+IMAGE_DATA_NAME+"失败");
PAHT = "";
}
});
// If you prefer to poll for the data, instead of attaching a
// listener, check for the state and progress in the observer.
if (TransferState.COMPLETED == uploadObserver.getState()) {
// Handle a completed upload.
}
Log.d("YourActivity", "Bytes Transferred: " + uploadObserver.getBytesTransferred());
Log.d("YourActivity", "Bytes Total: " + uploadObserver.getBytesTotal());
}
- 在你需要下载的
Activity
的onCreat
方法中添加
/**
* AWS下载
*/
private void AwsDownld() {
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails userStateDetails) {
Log.i(TAG, "AWSMobileClient initialized. User State is " + userStateDetails.getUserState());
}
@Override
public void onError(Exception e) {
Log.e(TAG, "Initialization error.", e);
}
});
downloadWithTransferUtility();
}
private void downloadWithTransferUtility() {
TransferUtility transferUtility =
TransferUtility.builder()
.context(getApplicationContext())
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.s3Client(new AmazonS3Client(AWSMobileClient.getInstance()))
.build();
TransferObserver downloadObserver =
transferUtility.download(
"public/s3Key.txt",
new File("/path/to/file/localFile.txt"));
// Attach a listener to the observer to get state update and progress notifications
downloadObserver.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED == state) {
// Handle a completed upload.
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float)bytesCurrent/(float)bytesTotal) * 100;
int percentDone = (int)percentDonef;
Log.d("Your Activity", " ID:" + id + " bytesCurrent: " + bytesCurrent + " bytesTotal: " + bytesTotal + " " + percentDone + "%");
}
@Override
public void onError(int id, Exception ex) {
// Handle errors
}
});
// If you prefer to poll for the data, instead of attaching a
// listener, check for the state and progress in the observer.
if (TransferState.COMPLETED == downloadObserver.getState()) {
// Handle a completed upload.
}
Log.d("Your Activity", "Bytes Transferred: " + downloadObserver.getBytesTransferred());
Log.d("Your Activity", "Bytes Total: " + downloadObserver.getBytesTotal());
}
}
- 最后上传成功后就可以在Amazon S3控制台的桶里查看了
总结
Amazon S3上传、下载只是其中两个比较简单一些的操作,还有跟踪转移、暂停、恢复删除、推送、验证等等一系列操作。