Photo Sharing App Part II: Understanding OSS Functions & Creating UI-阿里云开发者社区

开发者社区> 芷沁> 正文

Photo Sharing App Part II: Understanding OSS Functions & Creating UI

简介: We will build a photo sharing Android app with real-time image uploading and downloading functionality using Alibaba Cloud OSS.
+关注继续查看

Practices_of_De_duplication_and_Image_Search_Services

By Sai Sarath Chandra, Alibaba Cloud Tech Share Author and Alibaba Cloud MVP

In Last section, we have created the workspace setup and required STS credentials using "Resource Access Management" to access the Object Storage Service of Alibaba Cloud. In this section will be creating the Android application and will also be bootstrapping the user interface of the application, we will also be discussing the various synchronous and asynchronous functionalities of the object storage service Android SDK provided by Alibaba Cloud and we will also see the working of the image processing capabilities of the Alibaba Cloud using Android.

Creating Android project:

Create an Android project with the name you prefer. I provided the name "Photo Sharing". If you use the same settings as I used you don't need to change much of the code and in this way you can prevent the address cause by the code changes.

1

Select the min SDK and device compatibility, I am targeting the devices with minimum API level 19 or later only phone and tablet.

2

Select empty activity and proceed further.

3

Keep all the default values as given and click finish.

4

let the Android Studio to build code and open the project.

Creating the User Interface:

Setting up Gradle:

Open your application level gradle file and update the dependency section with the given below code.

implementation fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:27.0.2'
testImplementation 'junit:junit:4.12'
compile 'com.aliyun.dpa:oss-android-sdk:2.4.5'
compile 'com.github.jkwiecien:EasyImage:1.3.1'
implementation 'com.github.bumptech.glide:glide:4.4.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'
implementation 'com.android.support:recyclerview-v7:27.0.2'
compile group: 'commons-io', name: 'commons-io', version: '2.6'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
compile 'com.android.support:cardview-v7:27.0.2'

once the gradle file is being updated please synchronise the changes and make sure everything compile successfully with no errors / warnings

This gradle file contains the dependencies for both Object Storage Service (OSS) SDK from Alibaba cloud, their interdependencies and also some of the support libraries which we will use in creating the user interface of the application.

Creating activity XML:

we will create for XML files for the complete UI of the application.

activity_welcome.xml

This screen will be shown as the first screen of the application the responsibility of the screen is to navigate the user between the upload file section and view images option. Please create the file name as mentioned under layout folder and copy the following code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/uploadFiles"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_margin="8dp"
        android:textSize="24sp"
        android:textColor="#FFFFFF"
        android:text="UPLOAD FILES"
        android:background="#303F9F"/>

    <Button
        android:id="@+id/viewImages"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_margin="8dp"
        android:textColor="#FFFFFF"
        android:textSize="24sp"
        android:background="#388E3C"
        android:text="VIEW IMAGES" />

</LinearLayout>

Just to give a view how approximately it looks once this is done. Please find the image below:

5

activity_main.xml

Once the user selects the "Upload Files" option then the user will be navigated here.

This screen will be responsible for providing the user the ability to upload a picture from camera gallery and documents. the screen will also provide the capability for various image processing functionalities like resize, crop, rotate, watermarking etc...

please create the file as the name mentioned and replace the file content with the following code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/cameraBtn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="#E91E63"
            android:src="@drawable/ic_camera_enhance_white_24dp" />

        <ImageButton
            android:id="@+id/galleryBtn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="#9C27B0"
            android:src="@drawable/ic_view_24dp" />

        <ImageButton
            android:id="@+id/documentsBtn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="#F44336"
            android:src="@drawable/ic_folder_24dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        android:layout_weight="4"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:id="@+id/resizeImg"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#00ACC1"
                android:text="Resize" />

            <Button
                android:id="@+id/cropImg"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#7CB342"
                android:text="Crop" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:id="@+id/rotateImg"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#FDD835"
                android:text="Rotate" />

            <Button
                android:id="@+id/sharpenImg"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#F4511E"
                android:text="Sharpen"
                android:textColor="#FFFFFF" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:id="@+id/watermarkImg"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#757575"
                android:text="Add Watermark"
                android:textColor="#FFFFFF" />

        </LinearLayout>

    </LinearLayout>


</LinearLayout>

To show how it looks after you have done this step. Please find the Image below.

You might not get the exact similar look as we didn't add the fonts programmatically as we targeting the user's Android KitKat 4.4. After we add the fonts programmatically we can see the changes in the Android Application directly.

6

activity_img_recycler.xml

When the user selects view images option in the welcome screen then the user will be navigated to this particular screen in the screen will be using recycler view of Android support library to show the list of images which are fetched from the server in real time and show the images which are applied with the image processing functionalities.

A brief background of recycler view as this is the advance form of list view which uses less memory and creates high-performance list which are very fluid and very memory efficient. we will discuss more when we create the Core Java code for the same.

Please create the file and copy the code as displayed:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />

</LinearLayout>

recyclerview_row.xml

This particular XML is used for displaying the images in the recycler view this XML depicts the UI for the single row in the recycler view.

please create the file as mentioned and copy the corresponding code to the file from below:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content"
    >
    <!-- A CardView that contains a TextView -->
    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        card_view:cardCornerRadius="4dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/imageView"
                android:src="@drawable/placeholder"
                android:adjustViewBounds="false"/>

            <TextView
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/imageView"
                android:id="@+id/imageName"
                android:textAlignment="center"
                android:textSize="18sp"
                android:textStyle="bold"
                android:textColor="#000000"
                android:text="Image Name"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>
</LinearLayout>

Understanding OSS (Object Storage Service) Android SDK

Unlike other Android projects we have created till now where we use Java SDK and use the downloaded jar files into the application. the OSS Android SDK provides both synchronous and asynchronous functionality, this means there is no need for you to create separate asynchronous task to run the UI related code in your application.

if you have little experience with RX Java it will be little easy to understand how the asynchronous code execute in a synchronous block to give a brief background of how asynchronous code execute

Everything in reactive languages uses event based mechanism to notify the methods or the observers

•The code with his executive and producing the result is called observable
•The code which listen for the updates of the observable is called observer
•When the observable complete the execution it notifies the observer that the code execution is completed and provides the result to the observer on to their on success method.

The main advantage of asynchronous or event based coding is that we can prevent so many NullPointer exception and we can write high performance code and again that is a discussion by itself.

Fortunately, we not need to understand or implement all the low-level functionalities of an event based asynchronous coding in our application as this is already handled by Alibaba cloud team and provides high level functions which are very easy to understand and use. for example, now we see the uploading task in an asynchronous fashion where we need to implement couple of methods to achieve this functionality and this is very easy. You will feel very comfortable once you understand the asynchronous coding as this reduces the complexities posed by AsyncTask. Please find the below code:

PutObjectRequest put = new PutObjectRequest(getString(R.string.Bucket_Name), "Demo_Picture_1.png", filePath);
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }
    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exception
        if (clientExcepion != null) {
            // Local exception, such as a network exception
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Service exception
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Initially the PutRequest object is created with all the required parameters like Bucket name, Image key in the file path and then we set the progress call back on this request. This is as similar as "onProgress" method in the AsyncTask. This will be triggered whenever there is an update on the Task.

then we create the task by sending the request along with the 2 ovverrided implementations called "onSuccess" and "onFailure"

onSuccess :

This method is triggered after the successful operation and it carries the result we can use the result to know the status based on the implementation provided

onFailure :

If the execution failed due to any reason this particular method will be triggered and it carries the request along with the client exception or the service exception you can use it to find about the detailed information, stackTrace and reason of occurrence.

Then maybe some scenario where you need to use the AsyncTask in conjunction with the asynchronous code due to the synchronous code in between the multiple asynchronous blocks.

Summary

In this part, we understood the synchronous way of using OSS service of Alibaba cloud and we even created the UI of the application in next section we will be discussing and creating the Java code for the same and provide multiple functionalities to the UI which we have created and we even discuss about the image processing capabilities and how to use them in our Android application.

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
阿里云服务器怎么设置密码?怎么停机?怎么重启服务器?
如果在创建实例时没有设置密码,或者密码丢失,您可以在控制台上重新设置实例的登录密码。本文仅描述如何在 ECS 管理控制台上修改实例登录密码。
4037 0
阿里云服务器端口号设置
阿里云服务器初级使用者可能面临的问题之一. 使用tomcat或者其他服务器软件设置端口号后,比如 一些不是默认的, mysql的 3306, mssql的1433,有时候打不开网页, 原因是没有在ecs安全组去设置这个端口号. 解决: 点击ecs下网络和安全下的安全组 在弹出的安全组中,如果没有就新建安全组,然后点击配置规则 最后如上图点击添加...或快速创建.   have fun!  将编程看作是一门艺术,而不单单是个技术。
3976 0
使用OpenApi弹性释放和设置云服务器ECS释放
云服务器ECS的一个重要特性就是按需创建资源。您可以在业务高峰期按需弹性的自定义规则进行资源创建,在完成业务计算的时候释放资源。本篇将提供几个Tips帮助您更加容易和自动化的完成云服务器的释放和弹性设置。
7630 0
阿里云服务器安全组设置内网互通的方法
虽然0.0.0.0/0使用非常方便,但是发现很多同学使用它来做内网互通,这是有安全风险的,实例有可能会在经典网络被内网IP访问到。下面介绍一下四种安全的内网互联设置方法。 购买前请先:领取阿里云幸运券,有很多优惠,可到下文中领取。
9341 0
windows server 2008阿里云ECS服务器安全设置
最近我们Sinesafe安全公司在为客户使用阿里云ecs服务器做安全的过程中,发现服务器基础安全性都没有做。为了为站长们提供更加有效的安全基础解决方案,我们Sinesafe将对阿里云服务器win2008 系统进行基础安全部署实战过程! 比较重要的几部分 1.
5002 0
阿里云ECS云服务器初始化设置教程方法
阿里云ECS云服务器初始化是指将云服务器系统恢复到最初状态的过程,阿里云的服务器初始化是通过更换系统盘来实现的,是免费的,阿里云百科网分享服务器初始化教程: 服务器初始化教程方法 本文的服务器初始化是指将ECS云服务器系统恢复到最初状态,服务器中的数据也会被清空,所以初始化之前一定要先备份好。
2902 0
阿里云服务器如何登录?阿里云服务器的三种登录方法
购买阿里云ECS云服务器后如何登录?场景不同,云吞铺子总结大概有三种登录方式: 登录到ECS云服务器控制台 在ECS云服务器控制台用户可以更改密码、更换系统盘、创建快照、配置安全组等操作如何登录ECS云服务器控制台? 1、先登录到阿里云ECS服务器控制台 2、点击顶部的“控制台” 3、通过左侧栏,切换到“云服务器ECS”即可,如下图所示 通过ECS控制台的远程连接来登录到云服务器 阿里云ECS云服务器自带远程连接功能,使用该功能可以登录到云服务器,简单且方便,如下图:点击“远程连接”,第一次连接会自动生成6位数字密码,输入密码即可登录到云服务器上。
16318 0
+关注
芷沁
https://www.alibabacloud.com/blog/
417
文章
1
问答
文章排行榜
最热
最新
相关电子书
更多
文娱运维技术
立即下载
《SaaS模式云原生数据仓库应用场景实践》
立即下载
《看见新力量:二》电子书
立即下载