Friday 15 April 2016

HB Blog 108: File Upload To Server In Android Programmatically.

A Web service is a method of communication between two electronic devices over a network.They are the integral part of Mobile development. Web service are of various types SOAP, REST, and XML-RPC. For basics of webservices you can follow my blog Basics of Web Services.

In this post, I will show how to upload files from Android mobile devices to the server network using HttpURLConnection class.

A URLConnection with support for HTTP-specific features.
  1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  2. Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().
  4. Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//Async_ImageUpload.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package com.example.harshalbenake.imageupload;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * This async task is used to send ImageUpload to server.
 * Created by <b>Harshal Benake</b> on 10/11/15.
 */
public class Async_ImageUpload extends AsyncTask<String, String, String> {
    private MainActivity mActivity;
    ProgressDialog progressDialog = null;
    private ResponseManager mResponseManager;
    private String status;

    public Async_ImageUpload(MainActivity activity) {
        this.mActivity = activity;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (isConnected(mActivity)) {
            progressDialog = new ProgressDialog(mActivity);
            progressDialog.setProgressStyle(android.R.attr.progressBarStyleLarge);
            progressDialog.setMessage("Loading");
            progressDialog.show();
            progressDialog.setCancelable(false);
        } else {
            System.out.println("Internet lost");
            cancel(true);
        }
    }

    @Override
    public String doInBackground(String... params) {
        if (!isCancelled()) {
            try {
                sendPostDataRegistrationWS();
                if (mResponseManager != null && mResponseManager.response != null
                        && !mResponseManager.response.equalsIgnoreCase("")) {
                    if (mResponseManager.status == ResponseManager.SC_OK) {
                        System.out.println("Async_ImageUpload response: " + mResponseManager.response);
                        JSONObject jsonObject = new JSONObject(mResponseManager.response);
                        status = jsonObject.optString("status");
                        String message = jsonObject.optString("message");
                        if (status != null && status.equalsIgnoreCase("200")) {

                        }
                        return message;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String message) {
        super.onPostExecute(message);
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (message != null && !message.equalsIgnoreCase("")) {
            System.out.println("message: " + message);
        }
    }

    /**
     * This method is use to check the device internet connectivity.
     *
     * @param context
     * @return true :if your device is connected to internet.
     * false :if your device is not connected to internet.
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info == null)
            return false;
        if (info.getState() != NetworkInfo.State.CONNECTED)
            return false;

        return true;
    }


    /**
     * This webservice method is used to send data to server.
     *
     * @return
     */
    public ResponseManager sendPostDataRegistrationWS() {
        ResponseManager responseManager = new ResponseManager();
        responseManager.status = ResponseManager.exception;
        responseManager.response = "Server Error";
        try {
            final String strUrl = mActivity.getResources().getString(R.string.webservice_url);
            String strFilePath = Environment.getExternalStorageDirectory() + File.separator + "hb" + File.separator + "156" + ".jpg";
            File file = new File(strFilePath);
            HttpURLConnection httpURLConnection = null;
            DataOutputStream dataOutputStream = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int maxBufferSize = 1 * 2048 * 2048;
            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(file);
            URL url = new URL(strUrl);
            // Open a HTTP  connection to  the URL
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true); // Allow Inputs
            httpURLConnection.setDoOutput(true); // Allow Outputs
            httpURLConnection.setUseCaches(false); // Don't use a Cached Copy
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            httpURLConnection.setRequestProperty("UploadedImage", file.getName());
            //  conn.setRequestProperty("Params","Registration");
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());

            //first parameter - type
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"parameter\"" + lineEnd + lineEnd
                    + "parameter" + lineEnd);

            //uploaded_file parameter - UploadedImage
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + file.getName() + "\"" + lineEnd);
            dataOutputStream.writeBytes(lineEnd);

            // create a buffer of  maximum size
            int bytesAvailable = fileInputStream.available();
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];
            // read file and write it into form...
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dataOutputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            //close the streams //
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();

            // Execute HTTP Post Request
            String strResponse =  httpURLConnection.getResponseMessage();
            System.out.println("response " + ": " + strResponse);
            int statusCode = httpURLConnection.getResponseCode();
            if (statusCode == HttpStatus.SC_OK) {
                responseManager.status = statusCode;
                responseManager.response = strResponse;
                responseManager.message = "";
            } else {
                responseManager.status = statusCode;
                responseManager.response = ResponseManager.handledResponseMessage(mActivity, statusCode);
                responseManager.message = ResponseManager.handledResponseMessage(mActivity, statusCode);
            }
            return responseManager;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseManager;
    }
}
 

Friday 1 April 2016

HB Blog 107: Android Camera Using Intents And Custom Interface.

Android, Inc. was founded in Palo Alto, California in October 2003 by Andy Rubin (co-founder of Danger), Rich Miner (co-founder of Wildfire Communications, Inc.), Nick Sears (once VP at T-Mobile), and Chris White (headed design and interface development at WebTV) to develop, in Rubin's words, "smarter mobile devices that are more aware of its owner's location and preferences". The early intentions of the company were to develop an advanced operating system for digital cameras. Though, when it was realized that the market for the devices was not large enough, the company diverted its efforts toward producing a smartphone operating system.

The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications. We can develop camera applications using existing camera as well as create our own custom camera based on the requirement of the application.
Using Existing Camera Apps: -
We can use basic intents to start to invoke an existing Android camera application. A camera intent makes a request to capture a picture or video clip through an existing camera app and then returns control back to your application.

The procedure for invoking a camera intent follows these general steps:
    Compose a Camera Intent - Create an Intent that requests an image, using one of these intent types:
     MediaStore.ACTION_IMAGE_CAPTURE - Intent action type for requesting an image from an existing camera application.
    Start the Camera Intent - Use the startActivityForResult() method to execute the camera intent. After you start the intent, the Camera application user interface appears on the device screen and the user can take a picture or video.
    Receive the Intent Result - Set up an onActivityResult() method in your application to receive the callback and data from the camera intent. When the user finishes taking a picture or video (or cancels the operation), the system calls this method.

Building a Camera App: -
Creating custom camera is not as simple as calling intent and few lines of code.

The general steps for creating a custom camera interface for your application are as follows:
    Detect and Access Camera - Create code to check for the existence of cameras and request access.
    Create a Preview Class - Create a camera preview class that extends SurfaceView and implements the SurfaceHolder interface. This class previews the live images from the camera.
    Build a Preview Layout - Once you have the camera preview class, create a view layout that incorporates the preview and the user interface controls you want.
    Setup Listeners for Capture - Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.
    Capture and Save Files - Setup the code for capturing pictures or videos and saving the output.
    Release the Camera - After using the camera, your application must properly release it for use by other applications.