import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpStatus;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* @author Tushar Sonu Lambole
*
*/
/*
* ImageView img = (ImageView) findViewById(R.id.img_logo); new
* ImageDownloaderManager( getApplicationContext(), img,
* "http://....../Speciality/dentist.png"
* , Environment.getExternalStorageDirectory() + "/ABC/Login", 4);
*/
public class ImageDownloaderManager {
ImageView mImageView;
String mImageServerUrl;
int mImageVersion;
String mImageLocationLocal;
String mImageName;
String mImageOldName;
Context mContext;
boolean imageIsOnDevice = false;
int mImageWidth = 0;
int mImageHeight = 0;
public ImageDownloaderManager(Context context, ImageView imageView,
String imageUrlServer, String imageLocationLocal, int imageVersion,
int imageWidth, int imageHeight) {
mContext = context;
mImageView = imageView;
mImageServerUrl = imageUrlServer;
mImageVersion = imageVersion;
mImageLocationLocal = imageLocationLocal;
mImageWidth = imageWidth;
mImageHeight = imageHeight;
new ImageDownload().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private boolean GenerateImageNameWithVersion() {
// sending result to indicate names are generated or not
boolean result = false;
try {
mImageName = null;
mImageOldName = null;
if (mImageServerUrl != null) {
if (mImageServerUrl.length() > 0) {
String[] strUrlSplit = mImageServerUrl.split("/");
if (strUrlSplit.length > 0) {
String strImageName = strUrlSplit[strUrlSplit.length - 1];
String fileExtension = strImageName
.substring(strImageName.lastIndexOf('.') + 1);
String fileName = strImageName.substring(0,
strImageName.indexOf('.'));
mImageName = fileName + String.valueOf(mImageVersion)
+ "." + fileExtension;
mImageOldName = fileName
+ String.valueOf(mImageVersion - 1) + "."
+ fileExtension;
result = true;
}
} else {
staticUtilsMethods
.SysOutPrint("Image server Url length is Zero");
}
} else {
staticUtilsMethods.SysOutPrint("Image server Url is null");
}
} catch (Exception e) {
staticUtilsMethods
.LogIt("ImageDownloaderManager-GenerateImageNameWithVersion() "
+ staticUtilsMethods.getStackTrace(e));
}
return result;
}
private boolean CheckImagePresentOnDevice() {
boolean result = false;
try {
if (mImageName != null) {
File imageFile = new File(mImageLocationLocal + "/"
+ mImageName);
if (imageFile.exists()) {
result = true;
}
} else {
staticUtilsMethods
.SysOutPrint("CheckImagePresentOnDevice: Image file name is null");
}
} catch (Exception e) {
staticUtilsMethods
.LogIt("ImageDownloaderManager-CheckImagePresentOnDevice() "
+ staticUtilsMethods.getStackTrace(e));
}
return result;
}
private void CheckAndDeletePreviousImage() {
try {
if (mImageOldName != null) {
File imageFile = new File(mImageLocationLocal + "/"
+ mImageOldName);
if (imageFile.exists()) {
imageFile.delete();
} else {
staticUtilsMethods
.SysOutPrint("CheckAndDeletePreviousImage: Old Image file not found");
}
} else {
staticUtilsMethods
.SysOutPrint("CheckAndDeletePreviousImage: Image file name is null");
}
} catch (Exception e) {
staticUtilsMethods
.LogIt("ImageDownloaderManager-CheckAndDeletePreviousImage() "
+ staticUtilsMethods.getStackTrace(e));
}
}
private void DownloadAndSaveImageToDevice() {
HttpURLConnection urlConnection = null;
OutputStream stream = null;
File dir = new File(mImageLocationLocal);
try {
if (!dir.exists()) {
dir.mkdirs();
}
stream = new FileOutputStream(mImageLocationLocal + "/"
+ mImageName);
URL uri = new URL(mImageServerUrl);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpStatus.SC_OK) {
InputStream inputStream = urlConnection.getInputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) != -1) {
stream.write(b, 0, length);
}
inputStream.close();
stream.close();
// Set image is downloaded and ready for use
imageIsOnDevice = true;
// if (inputStream != null) {
// Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// bitmap.compress(CompressFormat.JPEG, 80, stream);
//
// mImageView.setImageBitmap(bitmap);
// mImageView.invalidate();
// }
} else {
staticUtilsMethods
.SysOutPrint("CheckAndDeletePreviousImage: Error downloading image from");
}
} catch (Exception e) {
urlConnection.disconnect();
staticUtilsMethods
.SysOutPrint("CheckAndDeletePreviousImage: Error downloading image : "
+ e.getMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
private void SetImageToImageView() {
try {
String imageLocalPathWithName = "file://" + mImageLocationLocal
+ "/" + mImageName;
imageLocalPathWithName = imageLocalPathWithName.replace(" ", "%20");
// Set image width and Height if passed
if (mImageHeight > 0 && mImageWidth > 0) {
Picasso.with(mContext).load(imageLocalPathWithName)
.resize(mImageWidth, mImageHeight).into(mImageView);
} else {
Picasso.with(mContext).load(imageLocalPathWithName)
.into(mImageView);
}
} catch (Exception e) {
staticUtilsMethods
.LogIt("ImageDownloaderManager-SetImageToImageView() "
+ staticUtilsMethods.getStackTrace(e));
}
}
class ImageDownload extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
// Generate name
if (GenerateImageNameWithVersion()) {
// Assign image
if (CheckImagePresentOnDevice()) {
imageIsOnDevice = true;
} else {
DownloadAndSaveImageToDevice();
CheckAndDeletePreviousImage();
}
}
} catch (Exception e) {
staticUtilsMethods
.LogIt("ImageDownloaderManager-ImageDownload-doInBackground() "
+ staticUtilsMethods.getStackTrace(e));
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Because of picasa used we forced to load image on main thread.
if (imageIsOnDevice) {
SetImageToImageView();
}
}
}
}