· 6 years ago · Apr 07, 2019, 10:58 AM
1import android.app.Activity;
2import android.app.DownloadManager;
3import android.content.Context;
4import android.content.Intent;
5import android.content.res.Configuration;
6import android.graphics.Bitmap;
7import android.net.Uri;
8import android.os.Environment;
9import android.provider.Settings;
10import android.support.design.widget.Snackbar;
11import android.util.DisplayMetrics;
12import android.util.Log;
13import android.view.Display;
14import android.view.View;
15import android.view.inputmethod.InputMethodManager;
16import java.io.File;
17import java.io.FileOutputStream;
18import java.io.IOException;
19import java.text.SimpleDateFormat;
20import java.util.Calendar;
21import java.util.Date;
22import java.util.Locale;
23
24/**
25 * Created by Dev51 on 6/3/2015.
26 */
27public class CommonUtils {
28
29 public static final String secretKey = "?q5ZWFaFEbRs8=Wx";
30
31 // Used for get current date as per desire format
32 public static String getUserFormatedCurentDate(String pattern) {
33 Calendar cal = Calendar.getInstance();
34 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
35 return sdf.format(cal.getTime());
36 }
37
38 // This function is needed for get User's desire formatted date with UTC timezone
39 public static String getUserFormatedDate(String pattern, String dateFromResponse) {
40 try {
41 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
42 Date mDateFromResponse = sdf.parse(dateFromResponse);
43 sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
44 return sdf.format(mDateFromResponse);
45 } catch (Exception e) {
46
47 e.printStackTrace();
48 return null;
49 }
50 }
51
52 // hide keyboard
53 public static void hideKeyboard(Activity activity) {
54 if (activity.getCurrentFocus() != null) {
55 InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(
56 Activity.INPUT_METHOD_SERVICE);
57 inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
58 0);
59 }
60 }
61
62 //This function is needed because time has only hours and min and need to be converted into 12 hour format
63 public static String get12HourFormatedTime(String StartDateTime) {
64 String splitDate = "";
65 try {
66 SimpleDateFormat fromUser = new SimpleDateFormat("HH:MM");
67 SimpleDateFormat myFormat = new SimpleDateFormat("HH:mm a");
68
69 splitDate = myFormat.format(fromUser.parse(StartDateTime));
70 } catch (Exception e) {
71
72 e.printStackTrace();
73 }
74 return splitDate;
75 }
76
77 /*// This function is for get date sufix
78 public static String getDayNumberSuffix(int day) {
79
80 if (day >= 11 && day <= 13) {
81
82 return "th";
83 }
84
85 switch (day % 10) {
86
87 case 1:
88 return "st";
89
90 case 2:
91 return "nd";
92
93 case 3:
94 return "rd";
95
96 default:
97 return "th";
98 }
99 }*/
100
101 // Used to get diffrence of date into words
102 public static String getDifferenceInWords(String dateFromResponse) {
103 try {
104 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
105 //sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
106 Date mDateFromResponse = sdf.parse(
107 dateFromResponse); //prints-> Mon Sep 30 02:46:19 CST 2013
108 Calendar calObj = Calendar.getInstance();
109 Date dateFromSystem = calObj.getTime();
110
111 String calculated_time_difference = "";
112 long difference = dateFromSystem.getTime() - mDateFromResponse.getTime();
113 long secondsInMilli = 1000;
114 long minutesInMilli = secondsInMilli * 60;
115 long hoursInMilli = minutesInMilli * 60;
116 long daysInMilli = hoursInMilli * 24;
117
118 long elapsedDays = difference / daysInMilli;
119 difference = difference % daysInMilli;
120
121 long elapsedHours = difference / hoursInMilli;
122 difference = difference % hoursInMilli;
123
124 long elapsedMinutes = difference / minutesInMilli;
125 difference = difference % minutesInMilli;
126
127 long elapsedSeconds = difference / secondsInMilli;
128
129 Log.e("elapsedDays", "" + elapsedDays);
130 Log.e("elapsedHours", "" + elapsedHours);
131 Log.e("elapsedMinutes", "" + elapsedMinutes);
132 Log.e("elapsedSeconds", "" + elapsedSeconds);
133
134 if (elapsedDays > 5) {
135 calculated_time_difference = getUserFormatedDate("MMMM dd, yyyy", dateFromResponse);
136 } else if (elapsedDays == 1) {
137 calculated_time_difference = String.valueOf(elapsedDays) + " " + "day ago";
138 } else if (elapsedDays > 1 && elapsedDays <= 5) {
139 calculated_time_difference = String.valueOf(elapsedDays) + " " + "days ago";
140 } else if (elapsedHours != 0 && elapsedHours < 24) {
141
142 if (elapsedHours == 1) {
143 calculated_time_difference = String.valueOf(elapsedHours) + " " + "hour ago";
144 } else if (elapsedHours > 1 && elapsedHours < 24) {
145 calculated_time_difference = String.valueOf(elapsedHours) + " " + "hours ago";
146 }
147 } else if (elapsedMinutes != 0 && elapsedMinutes < 60) {
148
149 if (elapsedMinutes == 1) {
150 calculated_time_difference = String.valueOf(elapsedMinutes) + " " + "min ago";
151 } else if (elapsedMinutes > 1 && elapsedMinutes < 60) {
152 calculated_time_difference = String.valueOf(elapsedMinutes) + " " + "min ago";
153 }
154 } else {
155 calculated_time_difference = "Now";
156 }
157 Log.i("posted time:", calculated_time_difference);
158
159 return calculated_time_difference;
160 } catch (Exception e) {
161 Log.e("error on get post time", e + "");
162 e.printStackTrace();
163 return "";
164 }
165 }
166
167 public static Uri getLocalBitmapUri(Bitmap bmp, String name) {
168 // Extract Bitmap from ImageView drawable
169 // Store image to default external storage directory
170 Uri bmpUri = null;
171 try {
172 File file = new File(
173 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
174 name + ".jpeg");
175 file.getParentFile().mkdirs();
176 FileOutputStream out = new FileOutputStream(file);
177 bmp.compress(Bitmap.CompressFormat.JPEG, 75, out);
178 out.close();
179 bmpUri = Uri.fromFile(file);
180 } catch (IOException e) {
181 e.printStackTrace();
182 }
183 return bmpUri;
184 }
185
186 public static void Downloadimage(String ImageURl, Activity activity, String name,View view) {
187 File dir, file;
188 String url = ImageURl.replaceAll(" ", "%20");
189
190 // Store image to External public directories type is picture and subdirectory is "app name"
191 dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
192 + "/" + activity.getResources().getString(R.string.app_name) + "/");
193
194 if (!dir.exists()) {
195 dir.mkdirs();
196 }
197 file = new File(dir, ImageURl);
198
199
200
201 if (!file.exists()) {
202 DownloadManager mgr = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
203 Uri downloadUri = Uri.parse(activity.getString(R.string.IMAGE_PREFIX_URL) + url);
204 DownloadManager.Request request = new DownloadManager.Request(downloadUri);
205 request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
206 request.setAllowedOverRoaming(false).setTitle("Downloading " + name + "'s Catalog");
207 request.setDescription("Enjoy the full catalog!");
208 Log.i("downloadUri", downloadUri.getLastPathSegment());
209 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/"
210 + activity.getResources().getString(R.string.app_name), downloadUri.getLastPathSegment());
211 request.allowScanningByMediaScanner();
212 mgr.enqueue(request);
213 } else {
214 // Toast.makeText(activity, "Image Already Downloaded", Toast.LENGTH_SHORT).show();
215 mDisplaySnackBarMessage("Image Already Downloaded",view);
216 }
217 }
218
219
220 public static String getDeviceId() {
221 // To get the device id
222 String deviceId = Settings.Secure.getString(RapidCommApplication.getApplicationContext.getContentResolver(), Settings
223 .Secure.ANDROID_ID);
224 return deviceId;
225 }
226
227 // To restart main activity
228 public static void restartActivity(Activity activity) {
229 Intent restartActivity = activity.getIntent();
230 activity.finish();
231 activity.startActivity(restartActivity);
232 }
233
234 // To get screen size of the device we are working on
235 public static int deviceSpecification(Activity activity) {
236 DisplayMetrics metrics = new DisplayMetrics();
237 activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
238
239 int widthPixels = metrics.widthPixels;
240 int heightPixels = metrics.heightPixels;
241
242 float widthDpi = metrics.xdpi;
243 float heightDpi = metrics.ydpi;
244
245 float widthInches = widthPixels / widthDpi;
246 float heightInches = heightPixels / heightDpi;
247
248 //The size of the diagonal in inches is equal to the square root of the height in inches
249 // squared plus the width in inches squared.
250 double diagonalInches = Math.sqrt(
251 (widthInches * widthInches) + (heightInches * heightInches));
252
253 Log.i("CommonsUtil diagonalInches", (int) diagonalInches + "*****************");
254 return (int) diagonalInches;
255 }
256
257 @Deprecated
258 public static int getScreenOrientation(Activity activity) {
259 Display getOrient = activity.getWindowManager().getDefaultDisplay();
260 int orientation;
261 if (getOrient.getWidth() == getOrient.getHeight()) {
262 orientation = Configuration.ORIENTATION_SQUARE;
263 } else {
264 if (getOrient.getWidth() < getOrient.getHeight()) {
265 orientation = Configuration.ORIENTATION_PORTRAIT;
266 } else {
267 orientation = Configuration.ORIENTATION_LANDSCAPE;
268 }
269 }
270
271 Log.i("CommonsUtil orientation", orientation + "***********");
272 return orientation;
273 }
274
275 public static void mDisplaySnackBarMessage(String mMessage, View mView) {
276 Snackbar snackbar = Snackbar.make(mView, mMessage + "", Snackbar.LENGTH_SHORT);
277 View sbView = snackbar.getView();
278 sbView.setBackgroundResource(R.color.list_background);
279 snackbar.show();
280 }
281}