Wednesday 14 March 2018

HB Blog 153: Microsoft Azure Storage In Android.

Azure Blob storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data, such as text or binary data.

Blob storage is ideal for:
  • Serving images or documents directly to a browser.
  • Storing files for distributed access.
  • Streaming video and audio.
  • Writing to log files.
  • Storing data for backup and restore, disaster recovery, and archiving.
  • Storing data for analysis by an on-premises or Azure-hosted service.
  • Objects in Blob storage can be accessed from anywhere in the world via HTTP or HTTPS. Users or client applications can access blobs via URLs. 
Blob storage exposes three resources: your storage account, the containers in the account, and the blobs in a container. The following diagram shows the relationship between these resources.
Storage Account
All access to data objects in Azure Storage happens through a storage account.

Container
A container organizes a set of blobs, similar to a folder in a file system. All blobs reside within a container. A storage account can contain an unlimited number of containers, and a container can store an unlimited number of blobs.

Blob
Azure Storage offers three types of blobs -- block blobs, append blobs, and page blobs (used for VHD files).
Block blobs store text and binary data, up to about 4.7 TB. Block blobs are made up of blocks of data that can be managed individually.
Append blobs are made up of blocks like block blobs, but are optimized for append operations. Append blobs are ideal for scenarios such as logging data from virtual machines.
Page blobs store random access files up to 8 TB in size. Page blobs store the VHD files that back VMs.
All blobs reside within a container. A container is similar to a folder in a file system. You can further organize blobs into virtual directories, and traverse them as you would a file system.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//MainActivity.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package com.example.azure;

import java.io.FileOutputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.BlobContainerPermissions;
import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType;
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.ListBlobItem;

public class MainActivity extends Activity {
 public static final String ACCOUNT_NAME = "xxxACCOUNT_NAMExxx";
 public static final String ACCOUNT_KEY = "xxxACCOUNT_KEYxxx";
 public static final String CONTAINER_REF = "xxxCONTAINER_REFxxx";
 public static final String FILENAME = "xxxFILENAMExxx";
 public static final String STORAGE_CONNECTION_STRING = "DefaultEndpointsProtocol=http;"+ "AccountName=" + ACCOUNT_NAME + ";" + "AccountKey=" + ACCOUNT_KEY;
 public static final String STORED_ZIP_FILE_LOCATION = Environment.getExternalStorageDirectory().getPath();
 private CloudBlobContainer mContainer;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Button button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    new Thread(new Runnable() {
     public void run() {
      downloadViaAzure();
     }
    }).start();
    
   }
  });
 }

 public void downloadViaAzure() {
  try {
   // Retrieve storage account from connection-string.
   CloudStorageAccount storageAccount = CloudStorageAccount
     .parse(STORAGE_CONNECTION_STRING);
   // Create the blob client.
   CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
   // Get a reference to a container.
   // The container name must be lower case
   mContainer = blobClient.getContainerReference(CONTAINER_REF);
   // Create the container if it does not exist.
   mContainer.createIfNotExists();
  } catch (Exception e) {
   e.printStackTrace();
  }
  // Create a permissions object.
  BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
  // Include public access in the permissions object.
  containerPermissions
    .setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
  // Set the permissions on the container.
  try {
   mContainer.uploadPermissions(containerPermissions);
  } catch (StorageException e1) {
   e1.printStackTrace();
  }

  try {
   // Retrieve storage account from connection-string.
   CloudStorageAccount storageAccount = CloudStorageAccount
     .parse(STORAGE_CONNECTION_STRING);
   // Create the blob client.
   CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
   // Retrieve reference to a previously created container.
   CloudBlobContainer container = blobClient
     .getContainerReference(CONTAINER_REF);
   // Loop over blobs within the container and output the URI to each
   // of them.
   for (ListBlobItem blobItem : container.listBlobs()) {
     System.out.println("uri " +blobItem.getUri());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

  try {
   // Retrieve storage account from connection-string.
   CloudStorageAccount storageAccount = CloudStorageAccount
     .parse(STORAGE_CONNECTION_STRING);
   // Create the blob client.
   CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
   // Retrieve reference to a previously created container.
   CloudBlobContainer container = blobClient
     .getContainerReference(CONTAINER_REF);
   // Loop through each blob item in the container.
   for (ListBlobItem blobItem : container.listBlobs()) {
    // If the item is a blob, not a virtual directory.
    if (blobItem instanceof CloudBlob) {
     // Download the item and save it to a file with the same
     // name.
     CloudBlob blob = (CloudBlob) blobItem;
     blob.download(new FileOutputStream(STORED_ZIP_FILE_LOCATION
       + FILENAME));
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public class AsyncDownloadViaAzure extends AsyncTask<String, Void, Boolean> {
     private ProgressDialog mProgressDialog;

  @Override
     protected void onPreExecute() {
      super.onPreExecute();
      mProgressDialog = new ProgressDialog(MainActivity.this);
      mProgressDialog.setMessage("Downloading...");
      mProgressDialog.setCancelable(false);
      mProgressDialog.show();
     }
     
  @Override
  protected Boolean doInBackground(String... params) {
   try {
    downloadViaAzure();
   } catch (Exception e) {
    return false;
   }
   return true;
  }
  
  @Override
  protected void onPostExecute(Boolean result) {
   super.onPostExecute(result);
   mProgressDialog.dismiss();
  }
     
    }
}