Uploaded from an android

How to Upload Images to Firebase from an Android App

Firebase is a mobile and web application development platform, and Firebase Storage provides secure file uploads and downloads for Firebase apps. In this post, you’ll build an Android application with the ability to upload images to Firebase Storage.

Firebase Setup

If you don’t have a Firebase account yet, you can create one at the Firebase home page.

Once your account is set up, go to your Firebase console, and click the Add Project button to add a new project.

Enter your project details and click the Create Project button when done. On the next page, click on the link to Add Firebase to your Android app.

Enter your application package name. My application package is com.tutsplus.code.android.tutsplusupload. Note that the package name is namespaced with a unique string that identifies you or your company. An easy way to find this is to open your MainActivity file and copy the package name from the top.

When done, click on Register App. On the next page, you will be given a google-services.json to download to your computer. Copy and paste that file into the app folder of your application. (The path should be something like TutsplusUpload/app.)

Set Firebase Permissions

To allow your app access to Firebase Storage, you need to set up permissions in the Firebase console. From your console, click on Storage, and then click on Rules.

Paste the rule below and publish.

This will allow read and write access to your Firebase storage.

Create the Application

Open up Android Studio, and create a new project. You can call your project anything you want. I called mine TutsplusUpload.

Before you proceed, you’ll need to add a couple of dependencies. On the left panel of your Android Studio, click on Gradle Scripts.

Open build.gradle (Project: TutsplusUpload), and add this line of code in the dependencies block.

Next, open build.gradle (Module: app) to add the dependencies for Firebase. These go in the dependencies block also.

Finally, outside the dependencies block, add the plugin for Google Services.

Save when done, and it should sync.

Set Up the MainActivity Layout

The application will need one activity layout. Two buttons will be needed—one to select an image from your device, and the other to upload the selected image. After selecting the image you want to upload, the image will be displayed in the layout. In other words, the image will not be set from the layout but from the activity.

In your MainActivity layout, you will use two layouts—nesting the linear layout inside the relative layout. Start by adding the code for your relative layout.

The RelativeLayout takes up the whole space provided by the device. The LinearLayout will live inside the RelativeLayout , and will have the two buttons. The buttons should be placed side by side, thus the orientation to be used for the LinearLayout will be horizontal.

Here is the code for the linear layout.

From the above code, you can see that both buttons have ids assigned. The ids will be used to target the button from the main activity such that when the button gets clicked, an interaction is initiated. You will see that soon.

Below the LinearLayout , add the code for the ImageView .

You can also see that the ImageView has an id ; you will use this to populate the layout of the selected image. This will be done in the main activity.

Get MainActivity Up

Navigate to your MainActivity , and start by declaring fields. These fields will be used to initialize your views (the buttons and ImageView ), as well as the URI indicating where the image will be picked from. Add this to your main activity, above the onCreate method.

PICK_IMAGE_REQUEST is the request code defined as an instance variable.

Now you can initialize your views like so:

In the above code, you are creating new instances of Button and ImageView . The instances point to the buttons you created in your layout.

Читайте также:  Командная строка андроид помощь

You have to set a listener that listens for interactions on the buttons. When an interaction happens, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase.

Underneath the initialized views, set the listener for both buttons. The listener looks like this.

This should be in the onCreate() method. As I mentioned above, both buttons call a different method. The Choose button calls the chooseImage() method, while the Upload button calls the uploadImage() method. Let’s add those methods. Both methods should be implemented outside the onCreate() method.

Let’s start with the method to choose an image. Here is how it should look:

When this method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to browse through the device gallery to select the image. startActivityForResult is used to receive the result, which is the selected image. To display this image, you’ll make use of a method called onActivityResult .

onActivityResult receives a request code, result code, and the data. In this method, you will check to see if the request code equals PICK_IMAGE_REQUEST , with the result code equal to RESULT_OK and the data available. If all this is true, you want to display the selected image in the ImageView .

Below the chooseImage() method, add the following code.

Uploading the File to Firebase

Now we can implement the method for uploading the image to Firebase. First, declare the fields needed for Firebase. Do this below the other fields you declared for your class.

storage will be used to create a FirebaseStorage instance, while storageReference will point to the uploaded file. Inside your onCreate() method, add the code to do that—create a FirebaseStorage instance and get the storage reference. References can be seen as pointers to a file in the cloud.

Here is what the uploadImage() method should look like.

When the uploadImage() method is called, a new instance of ProgressDialog is initialized. A text notice showing the user that the image is being uploaded gets displayed. Then a reference to the uploaded image, storageReference.child() , is used to access the uploaded file in the images folder. This folder gets created automatically when the image is uploaded. Listeners are also added, with toast messages. These messages get displayed depending on the state of the upload.

Set Permission in the App

Finally, you need to request permission that your application will make use of. Without this, users of your application will not be able to browse their device gallery and connect to the internet with your application. Doing this is easy—simply paste the following in your AndroidManifest file. Paste it just above the application element tag.

This requests for permission to use the internet and read external storage.

Testing the App

Now go ahead and run your application! You should be able to select an image and successfully upload it to Firebase. To confirm the image uploaded, go back to your console and check in the Files part of your storage.

Conclusion

Firebase provides developers with lots of benefits, and file upload with storage is one of them. Uploading images from your Android application requires you to work with Activities and Intents. By following along with this tutorial, your understanding of Activities and Intents has deepened. I hope you enjoyed it!

Check out some of our other posts for more background about Activities and Intents, or take a look at some of our other tutorials on using Firebase with Android!

Источник

Android image and video upload

Cloudinary provides support for uploading media directly from your mobile application to your Cloudinary account, without going through your servers first. This method allows for faster uploading and a better user experience. It also reduces load on your servers and reduces the complexity of your applications.

You can also take advantage of upload presets for predefining upload parameters. For details on all the available upload parameters, see the Media upload documentation and the upload method of the Upload API Reference.

For security reasons, mobile applications shouldn’t contain your Cloudinary account credentials. You can use a signed upload, but that requires generating an authentication signature on your backend. In most cases, you will probably use unsigned uploads that generally provide all the functionality you need for your mobile application, while restricting upload options that require more security.

Читайте также:  Через навител навигатор для андроид

MediaManager upload method

The upload request is managed by the MediaManager’s upload method, which accepts the file to upload as its only parameter. The file can be specified as either: the path to the local file, a byte array, a Resource ID, or a URI.

The upload request is then dispatched to a background queue via the MediaManager’s dispatch method, optionally with a set of fully customizable rules and limits letting you choose when each upload request should actually run and how. Requests are automatically rescheduled to be retried later if a recoverable error is encountered (e.g. network disconnections, timeouts). The upload results are dispatched asynchronously and global callbacks can be defined, as well as specific callbacks per request.

The following simple example uploads an image called imageFile.jpg using the default signed upload settings:

Unsigned upload

Unsigned upload is an option for performing upload without the need to generate a signature on your backend. Unsigned upload options are controlled by an upload preset: to use this feature, you first need to enable unsigned uploading for your Cloudinary account from the Upload Settings page.

An upload preset is used to define which upload options will be applied to images that are uploaded unsigned with that preset specified. You can edit the preset at any point in time (or create additional upload presets), to define the parameters that will be used for all images that are uploaded unsigned from your mobile application.

The following simple example uploads an image called imageFile.jpg using an upload preset called sample_preset :

The method returns a requestId that can be used to identify the upload request.

Signed upload

Signed uploads require a signature which needs to be created using your api_secret. You should never expose your secret in client side code and therefore you need to to generate an authentication signature on your backend. Android signed upload with backend support should be implemented in conjunction with one of Cloudinary’s backend frameworks (Java, .NET, etc). The various backend frameworks implement helpers to be used in conjunction with iOS, as well as automatically generate the authentication signature for the upload.

To implement signed uploads from an Android device to your Cloudinary account you must provide a class that implements the SignatureProvider interface. You class must implement a synchronous HTTPS call to your backend signature generation endpoint, which must return an object with a timestamp, your API key, and the signature itself.

To enable signed uploads you need to update your call to the MediaManager’s init method with the name of an instance of your class ( init(Context, SignatureProvider, Map) ). Your class will be implemented whenever an upload must be signed.

Upload options

Use the MediaManager’s option method to add an upload parameter to the upload request. The method accepts 2 parameters: the first specifies the name of the upload parameter and the second its value. For example, to upload an image called samplepic.jpg and set the public_id option to sample1 :

If you want to include more than one upload parameter in the request you can either chain another option method for each parameter, or use the MediaManager’s options method to pass a Map of all parameters. Note that if you use the options method it must come before any other method passing upload parameters.

For example, to upload an image called dog.jpg , set the public_id to my_dog , and add the tag animal :

Which is equivalent to:

Timeout options

The Android SDK offers 2 extra parameters for overriding the default timeout values when trying to upload a file:

  • connect_timeout — the maximum amount of time in milliseconds to wait for a connection to be established.
  • read_timeout — the maximum amount of time in milliseconds to wait for data available for read.

By default, these timeout values vary between different mobile devices. You can override the default timeout values, and give a single value to all devices, by adding these parameters with the option method.

For example, to upload an image and set both timeouts to 10 seconds:

Callbacks

You can track upload progress by getting callbacks on the following events: onStart , onProgress , onSuccess , onError , and onReschedule . The upload results are dispatched asynchronously, with 2 options for adding callback functionality:

  1. Implement the UploadCallBack interface for specific callbacks per request.
  2. Extend the ListenerService for global callbacks, even when your app has been shut down, or is running in the background.
Читайте также:  Android device manager для андроид

Implement the UploadCallBack interface

Create a class that implements the UploadCallBack interface, and add functionality by overriding specific callback events with your own code. Use the MediaManager’s callback method to add the name of an instance of your class to the upload request. The callback is specific to the current upload request only. The following example includes some example code for the onProgress event:

Extend the ListenerService

Extend the ListnerService service, and add functionality by overriding specific callback events with your own code. Callback events for all upload requests will be routed to your service, even when your app has been shut down, or is running in the background.

The following example includes some example code extending the ListnerService :

Make sure to register your class in the manifest, with both a service tag and a cloudinaryCallbackService meta-data tag, both within the application tag.

For example, if your class is called UploadListner :

Preprocess uploads

Use the preprocess method to make changes to an image before initiating the upload request.

Preprocess image uploads

Image preprocessing is defined by an object of type ImageProcessChain that loads the image with a BitmapDecoder using the specified size, runs predefined processing steps, and then saves the image with a BitmapEncoder using the specified format and quality. The following types of processing steps are currently available:

Step Type Parameter Description
Limit (width, height) Scales down the image to fit within a bounding box of the given dimensions.
DimensionsValidator (min_width, max_width, min_height, max_height) Verifies the minimum and maximum dimensions for the image. Throws an error if the image does not fit within these dimensions.
Crop (point, point) Crops the image as defined by two points that reference the corners of the desired rectangle (any two points that create a diagonal within the image is a valid crop).
BitmapEncoder (format, quality) Saves the image using the given format (JPEG, PNG or WEBP) and quality.

To limit an image to a size of 1000×1000 pixels, make sure that the image is at least 10×10 pixels in size and change the format to WEBP with a quality of 80:

The limitDimensionsChain shortcut method can be used instead of loading the decoder and adding the limit step separately. For example, the following code accomplishes the same as the example code above:

To crop the image to a rectangle given by the points 250,250 and 750,750:

Preprocess video uploads

Video preprocessing is defined by an object of type VideoProcessChain for preprocessing a video. The following types of processing steps are currently available:

Step Type Parameter Description
Transcode (FrameRate, Width, Height, KeyFramesInterval, TargetAudioBitrateKbps, and TargetVideoBitrateKbps) Transcodes a video according to the given parameters.

For example, to transcode a video to a frame rate of 30 frames/sec, a size of 1280×720 pixels, a keyframe interval of 3 seconds, an audio bitrate of 128 Kbps, and a video bitrate of 3 Mbps:

Upload policy

Use the policy method to configure the MediaManager’s upload request to run under specific circumstances. The policy is defined by an object of type UploadPolicy that has the following properties:

Property Type Description
networkPolicy NetworkType Limit the upload to a specific type of network connection
Possible values:
-UploadPolicy.NetworkType.NONE
-UploadPolicy.NetworkType.ANY( default )
-UploadPolicy.NetworkType.UNMETERED
requiresCharging boolean Upload only when the mobile device is currently charging. Default: false
requiresIdle boolean Upload only when the mobile device is currently idle. Default: false
maxRetries int The maximum number of times to retry the upload. Default: 5
backoffCriteria backoffMillis, backoffPolicy The backoff policy to implement before retrying.
backoffMillis long The time to wait in milliseconds before retrying. Default: 120000 (2 minutes)
backoffPolicy BackoffPolicy Whether the time between successive upload attempts increases linearly (2, 4, 6, 8, etc) or exponentially (2, 4, 8, 16, etc)
Possible values:
-UploadPolicy.BackoffPolicy.LINEAR
-UploadPolicy.BackoffPolicy.EXPONENTIAL (default)

For example, to request that a specific upload runs only on an unmetered network (e.g. wifi), with a maximum of 7 retries, and waits 5 minutes before retrying with a linear backoff policy:

Immediate upload

If you need to start an upload immediately with no delay, you can use the startNow method to bypass the managed upload process controlled by the policy method. The startNow method replaces the dispatch method, and you will also need to pass an Android context instance when calling the method.

For example, to start an upload immediately:

Источник

Оцените статью