import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by Dev51 on 6/3/2015.
*/
public class CommonUtils {
public static final String secretKey = "?q5ZWFaFEbRs8=Wx";
// Used for get current date as per desire format
public static String getUserFormatedCurentDate(String pattern) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(cal.getTime());
}
// This function is needed for get User's desire formatted date with UTC timezone
public static String getUserFormatedDate(String pattern, String dateFromResponse) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date mDateFromResponse = sdf.parse(dateFromResponse);
sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
return sdf.format(mDateFromResponse);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// hide keyboard
public static void hideKeyboard(Activity activity) {
if (activity.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
0);
}
}
//This function is needed because time has only hours and min and need to be converted into 12 hour format
public static String get12HourFormatedTime(String StartDateTime) {
String splitDate = "";
try {
SimpleDateFormat fromUser = new SimpleDateFormat("HH:MM");
SimpleDateFormat myFormat = new SimpleDateFormat("HH:mm a");
splitDate = myFormat.format(fromUser.parse(StartDateTime));
} catch (Exception e) {
e.printStackTrace();
}
return splitDate;
}
/*// This function is for get date sufix
public static String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}*/
// Used to get diffrence of date into words
public static String getDifferenceInWords(String dateFromResponse) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date mDateFromResponse = sdf.parse(
dateFromResponse); //prints-> Mon Sep 30 02:46:19 CST 2013
Calendar calObj = Calendar.getInstance();
Date dateFromSystem = calObj.getTime();
String calculated_time_difference = "";
long difference = dateFromSystem.getTime() - mDateFromResponse.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = difference / daysInMilli;
difference = difference % daysInMilli;
long elapsedHours = difference / hoursInMilli;
difference = difference % hoursInMilli;
long elapsedMinutes = difference / minutesInMilli;
difference = difference % minutesInMilli;
long elapsedSeconds = difference / secondsInMilli;
Log.e("elapsedDays", "" + elapsedDays);
Log.e("elapsedHours", "" + elapsedHours);
Log.e("elapsedMinutes", "" + elapsedMinutes);
Log.e("elapsedSeconds", "" + elapsedSeconds);
if (elapsedDays > 5) {
calculated_time_difference = getUserFormatedDate("MMMM dd, yyyy", dateFromResponse);
} else if (elapsedDays == 1) {
calculated_time_difference = String.valueOf(elapsedDays) + " " + "day ago";
} else if (elapsedDays > 1 && elapsedDays <= 5) {
calculated_time_difference = String.valueOf(elapsedDays) + " " + "days ago";
} else if (elapsedHours != 0 && elapsedHours < 24) {
if (elapsedHours == 1) {
calculated_time_difference = String.valueOf(elapsedHours) + " " + "hour ago";
} else if (elapsedHours > 1 && elapsedHours < 24) {
calculated_time_difference = String.valueOf(elapsedHours) + " " + "hours ago";
}
} else if (elapsedMinutes != 0 && elapsedMinutes < 60) {
if (elapsedMinutes == 1) {
calculated_time_difference = String.valueOf(elapsedMinutes) + " " + "min ago";
} else if (elapsedMinutes > 1 && elapsedMinutes < 60) {
calculated_time_difference = String.valueOf(elapsedMinutes) + " " + "min ago";
}
} else {
calculated_time_difference = "Now";
}
Log.i("posted time:", calculated_time_difference);
return calculated_time_difference;
} catch (Exception e) {
Log.e("error on get post time", e + "");
e.printStackTrace();
return "";
}
}
public static Uri getLocalBitmapUri(Bitmap bmp, String name) {
// Extract Bitmap from ImageView drawable
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
name + ".jpeg");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 75, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public static void Downloadimage(String ImageURl, Activity activity, String name,View view) {
File dir, file;
String url = ImageURl.replaceAll(" ", "%20");
// Store image to External public directories type is picture and subdirectory is "app name"
dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/" + activity.getResources().getString(R.string.app_name) + "/");
if (!dir.exists()) {
dir.mkdirs();
}
file = new File(dir, ImageURl);
if (!file.exists()) {
DownloadManager mgr = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(activity.getString(R.string.IMAGE_PREFIX_URL) + url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false).setTitle("Downloading " + name + "'s Catalog");
request.setDescription("Enjoy the full catalog!");
Log.i("downloadUri", downloadUri.getLastPathSegment());
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/"
+ activity.getResources().getString(R.string.app_name), downloadUri.getLastPathSegment());
request.allowScanningByMediaScanner();
mgr.enqueue(request);
} else {
// Toast.makeText(activity, "Image Already Downloaded", Toast.LENGTH_SHORT).show();
mDisplaySnackBarMessage("Image Already Downloaded",view);
}
}
public static String getDeviceId() {
// To get the device id
String deviceId = Settings.Secure.getString(RapidCommApplication.getApplicationContext.getContentResolver(), Settings
.Secure.ANDROID_ID);
return deviceId;
}
// To restart main activity
public static void restartActivity(Activity activity) {
Intent restartActivity = activity.getIntent();
activity.finish();
activity.startActivity(restartActivity);
}
// To get screen size of the device we are working on
public static int deviceSpecification(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float widthDpi = metrics.xdpi;
float heightDpi = metrics.ydpi;
float widthInches = widthPixels / widthDpi;
float heightInches = heightPixels / heightDpi;
//The size of the diagonal in inches is equal to the square root of the height in inches
// squared plus the width in inches squared.
double diagonalInches = Math.sqrt(
(widthInches * widthInches) + (heightInches * heightInches));
Log.i("CommonsUtil diagonalInches", (int) diagonalInches + "*****************");
return (int) diagonalInches;
}
@Deprecated
public static int getScreenOrientation(Activity activity) {
Display getOrient = activity.getWindowManager().getDefaultDisplay();
int orientation;
if (getOrient.getWidth() == getOrient.getHeight()) {
orientation = Configuration.ORIENTATION_SQUARE;
} else {
if (getOrient.getWidth() < getOrient.getHeight()) {
orientation = Configuration.ORIENTATION_PORTRAIT;
} else {
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
Log.i("CommonsUtil orientation", orientation + "***********");
return orientation;
}
public static void mDisplaySnackBarMessage(String mMessage, View mView) {
Snackbar snackbar = Snackbar.make(mView, mMessage + "", Snackbar.LENGTH_SHORT);
View sbView = snackbar.getView();
sbView.setBackgroundResource(R.color.list_background);
snackbar.show();
}
}