-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMvGeneral.java
1038 lines (909 loc) · 31.5 KB
/
MvGeneral.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* AndroidWithoutStupid Java Library
* Created by V. Subhash
* http://www.VSubhash.com
* Released as Public Domain Software in 2014
*/
package com.vsubhash.droid.androidwithoutstupid;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.Activity;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.view.View;
import android.webkit.URLUtil;
/**
* This class provides general-purpose routines. Most methods can be called
* statically while a few require an instance.
*
* <pre class="mv">
MvGeneral.setClipBoardText("Hello, world!");
...
MvGeneral mvg = new MvGeneral(MyActivity.this);
mvg.playSound(R.raw.my_audio_file);
* </pre>
*
* @author V. Subhash (<a href="http://www.VSubhash.com/">www.VSubhash.com</a>)
* @version 2017.09.01
*
*/
public class MvGeneral {
ClipboardManager mClipboardManager;
Context mApplicationContext;
MvMediaPlayer mMvMediaPlayer = null;
SharedPreferences moPrefs = null;
public static Ringtone moRingTone;
/**
* Specifies whether MediaPlayer routines such as {@link #playSound(int)}
* need to play audio. Use this field to mute all calls to such routines.
*
*/
public boolean mIsSoundOn = true;
/**
* Creates a new instance and initializes it with the context of specified
* activity.
*
* @param aoCallingActivity
* activity whose context needs to be used to initialize this
* instance
*/
public MvGeneral(Activity aoCallingActivity) {
mApplicationContext = aoCallingActivity.getApplicationContext();
mClipboardManager =
(ClipboardManager) mApplicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
moPrefs = PreferenceManager.getDefaultSharedPreferences(mApplicationContext);
}
/**
* Creates a new instance and initializes it with specified context. Use this
* constructor in services.
*
* @param aoApplicationContext
* context used to initialize this instance
*/
public MvGeneral(Context aoApplicationContext) {
mApplicationContext = aoApplicationContext;
mClipboardManager =
(ClipboardManager) mApplicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
moPrefs = PreferenceManager.getDefaultSharedPreferences(mApplicationContext);
}
/**
* Stop {@link #playRingTone() playing the current ring tone}.
*/
public void stopRingTone() {
if (moRingTone != null) {
if (moRingTone.isPlaying()) {
moRingTone.stop();
}
}
}
/**
* Play the the {@link #moRingTone current ring tone}.
*
* @return whether it was successful
*/
public boolean playRingTone() {
if (moRingTone == null) {
Uri oAlarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
moRingTone = RingtoneManager.getRingtone(mApplicationContext, oAlarmUri);
}
if (mIsSoundOn) {
if (moRingTone != null) {
if (moRingTone.isPlaying()) {
moRingTone.stop();
}
moRingTone.play();
return(true);
}
}
return(false);
}
/**
* Plays a sound file specified by its resource ID.
* @param aiSoundResource resource ID of the sound file
*/
public void playSound(int aiSoundResource) {
if (mIsSoundOn) {
mMvMediaPlayer = new MvMediaPlayer(mApplicationContext, aiSoundResource);
}
}
/**
* Stops the instance media player if it is playing.
*/
public void stopSound() {
if (mMvMediaPlayer != null) {
try {
if (mMvMediaPlayer.mPlayer != null) {
if (mMvMediaPlayer.mPlayer.isPlaying()) {
mMvMediaPlayer.mPlayer.pause();
mMvMediaPlayer.mPlayer.stop();
mMvMediaPlayer.mPlayer.release();
}
}
} catch (Exception e) {
}
}
}
/**
* Launches an specified by its package name.
*
* @param asPackageName name of the package
*/
public void launchApp(String asPackageName) {
try {
launchApp(asPackageName, false);
} catch (Exception e) {
MvMessages.logMessage("Package not found: " + asPackageName);
}
}
/**
* Launches an app specified by its package name.
*
* @param asPackageName package name of the app
* @param abThrow whether to throw {@link NameNotFoundException} if app is not found
* @throws NameNotFoundException if the package or app is not found
*/
public void launchApp(String asPackageName, boolean abThrow) throws NameNotFoundException {
Intent oLaunchIntent;
PackageManager oPackageManager;
if (asPackageName != null) {
oPackageManager = mApplicationContext.getPackageManager();
oLaunchIntent = oPackageManager.getLaunchIntentForPackage(asPackageName);
if (oLaunchIntent != null) {
oLaunchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
oLaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mApplicationContext.startActivity(oLaunchIntent);
} else {
if (abThrow) {
throw(new NameNotFoundException());
}
}
}
}
/**
* Displays a launcher dialog for specified file.
*
* @param asFilePath pathname of the file
*/
public void launchFile(String asFilePath) {
launchFile(asFilePath, "");
}
/**
* Displays a launcher dialog for specified file.
*
* @param asFilePath pathname of the file
* @param asMimeType mimetype of the file
*/
public void launchFile(String asFilePath, String asMimeType) {
Intent oFileLaunchIntent = null;
String asFilePathLowerCase = asFilePath.toLowerCase();
if (asFilePathLowerCase.endsWith(".3gp") ||
asFilePathLowerCase.endsWith(".amv") ||
asFilePathLowerCase.endsWith(".asf") ||
asFilePathLowerCase.endsWith(".dat") ||
asFilePathLowerCase.endsWith(".flv") ||
asFilePathLowerCase.endsWith(".ogv") ||
asFilePathLowerCase.endsWith(".mov") ||
asFilePathLowerCase.endsWith(".mpeg") ||
asFilePathLowerCase.endsWith(".mpg") ||
asFilePathLowerCase.endsWith(".mp4") ||
asFilePathLowerCase.endsWith(".m4v") ||
asFilePathLowerCase.endsWith(".mkv") ||
asFilePathLowerCase.endsWith(".vob") ||
asFilePathLowerCase.endsWith(".wmv")
) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "video/mp4");
} else if (
asFilePathLowerCase.endsWith(".ogg") ||
asFilePathLowerCase.endsWith(".mp3") ||
asFilePathLowerCase.endsWith(".m4a") ||
asFilePathLowerCase.endsWith(".spx") ||
asFilePathLowerCase.endsWith(".wav") ||
asFilePathLowerCase.endsWith(".wma")
) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "audio/mpeg");
} else if (
asFilePathLowerCase.endsWith(".bmp") ||
asFilePathLowerCase.endsWith(".gif") ||
asFilePathLowerCase.endsWith(".jpeg") ||
asFilePathLowerCase.endsWith(".jpg") ||
asFilePathLowerCase.endsWith(".png") ||
asFilePathLowerCase.endsWith(".tiff") ||
asFilePathLowerCase.endsWith(".tiff")
) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "image/jpeg");
} else if (asFilePathLowerCase.endsWith("odt")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/vnd.oasis.opendocument.text");
} else if (asFilePathLowerCase.endsWith(".doc") || asFilePathLowerCase.endsWith(".docx")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/vnd.msword");
} else if (asFilePathLowerCase.endsWith(".xls") || asFilePathLowerCase.endsWith(".xlsx")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse(asFilePath), "application/vnd.ms-excel");
} else if (asFilePathLowerCase.endsWith("ods")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/vnd.oasis.opendocument.spreadsheet");
} else if (
asFilePathLowerCase.endsWith(".ppt") || asFilePathLowerCase.endsWith(".pps") ||
asFilePathLowerCase.endsWith(".pptx") || asFilePathLowerCase.endsWith(".ppsx")
) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/vnd.ms-powerpoint");
} else if (asFilePathLowerCase.endsWith("odp")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/vnd.oasis.opendocument.presentation");
} else if (asFilePathLowerCase.endsWith(".pdf")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/pdf");
} else if ((asFilePathLowerCase.endsWith(".txt")) ||
(asFilePathLowerCase.endsWith(".text"))) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "text/plain");
} else if ((asFilePathLowerCase.endsWith(".zip")) ||
(asFilePathLowerCase.endsWith(".rar"))) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "");
} else if ((asFilePathLowerCase.endsWith(".htm")) ||
(asFilePathLowerCase.endsWith(".html"))) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "text/html");
} else if (asFilePathLowerCase.endsWith(".apk")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), "application/vnd.android.package-archive");
} else if (!asMimeType.contentEquals("")) {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setDataAndType(Uri.parse("file://" + asFilePath), asMimeType);
} else {
oFileLaunchIntent = new Intent(Intent.ACTION_VIEW);
oFileLaunchIntent.setData(Uri.parse("file://" + asFilePath));
}
if (oFileLaunchIntent != null) {
try {
oFileLaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mApplicationContext.startActivity(oFileLaunchIntent);
} catch (Exception e) {
MvMessages.logMessage("Sorry. There was an error launching the file.");
e.printStackTrace();
}
}
}
public static String escapeXml(String asText) {
StringBuilder oXmlBuff = new StringBuilder();
if (asText == null) { return(""); };
for (int i = 0; i < asText.length(); i++) {
char c = asText.charAt(i);
switch (c) {
case '<':
oXmlBuff.append("<");
break;
case '>':
oXmlBuff.append(">");
break;
case '\"':
oXmlBuff.append(""");
break;
case '&':
oXmlBuff.append("&");
break;
case '\'':
oXmlBuff.append("'");
break;
default:
if (c > 0x7e) {
oXmlBuff.append("&#" + ((int) c) + ";");
} else
oXmlBuff.append(c);
}
}
return(oXmlBuff.toString());
}
/**
* Returns text in the clipboard memory.
* @return text in the clipboard (empty string if clipboard contains no data)
* @see #setClipboardText(String)
*/
public String getClipboardText() {
String sReturn ="";
if (mClipboardManager.getText() != null) {
sReturn = mClipboardManager.getText().toString();
}
return(sReturn);
}
/**
* Copies specified text to clipboard memory.
* @param asTextToCopy text that needs to be copied to the clipboard
* @see #getClipboardText()
*/
public void setClipboardText(String asTextToCopy) {
if (asTextToCopy != null) {
mClipboardManager.setText(asTextToCopy);
} else {
mClipboardManager.setText("");
}
}
/**
* Returns version name of the application with specified context.
*
* @param aoApplicationContext
* context whose version name needs to be known
* @return package version name
*/
public static String getPackageVersionName(Context aoApplicationContext) {
String sPackageName, sVersionName = "";
sPackageName = aoApplicationContext.getPackageName();
try {
sVersionName = aoApplicationContext.getPackageManager().getPackageInfo(sPackageName, 0).versionName;
} catch (NameNotFoundException e) {
MvMessages.logMessage("Error in package info: " + e.getMessage());
e.printStackTrace();
}
return(sVersionName);
}
/**
* Returns version code of the application with specified context.
*
* @param aoApplicationContext
* context whose version code needs to be known
* @return version code
*/
public static int getPackageVersionCode(Context aoApplicationContext) {
String sPackageName;
int iVersionCode = 0;
sPackageName = aoApplicationContext.getPackageName();
try {
iVersionCode = aoApplicationContext.getPackageManager().getPackageInfo(sPackageName, 0).versionCode;
} catch (NameNotFoundException e) {
MvMessages.logMessage("Error in package info: " + e.getMessage());
e.printStackTrace();
}
return(iVersionCode);
}
/**
* Returns name of specified constant in specified class.
*
* @param aoTargetClass class containing the constant
* @param aiConstant value whose corresponding name is required
* @return name of the constant
*/
@SuppressWarnings("rawtypes")
public static String getFieldName(Class aoTargetClass, int aiConstant) {
String sResult = "";
for (Field oField : aoTargetClass.getDeclaredFields()) {
try {
if (oField.getInt(null) == aiConstant) {
sResult = oField.getName();
}
} catch (IllegalArgumentException e) {
MvMessages.logMessage("Error: getFieldName(Class, int) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (IllegalAccessException e) {
MvMessages.logMessage("Error: getFieldName(Class, int) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
}
}
return(sResult);
}
/**
* Returns an underscore-delimited string containing specified date stamp.
* You could use this method, say, for time-stamping generated files.
*
* @param dtInput date or time for which the date stamp needs to be created
* @return date stamp
*/
public static String getTimeStamp(Date dtInput) {
SimpleDateFormat oDateFormat;
String sTimestamp;
oDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
if (dtInput == null) {
dtInput = new Date();
}
sTimestamp = oDateFormat.format(dtInput);
return(sTimestamp);
}
/**
* Returns current date with hours, minutes, and seconds set to 0.
*
* @return current date with hours, minutes, and seconds set to 0
*/
public static Date getCurrentDateWithZeroedTime() {
Date dtReturn = new Date();
dtReturn.setHours(0);
dtReturn.setMinutes(0);
dtReturn.setSeconds(0);
return(dtReturn);
}
/**
* Returns current date in "dd MMMM yyyy" format.
*
* @return current date
*/
public static String getCurrentDate() {
Date dt = new Date();
String sReturn = "";
DateFormat oDF = new SimpleDateFormat("dd MMMM yyyy");
sReturn = oDF.format(dt);
return(sReturn);
}
/**
* Returns current time in "HH:mm:ss" format.
*
* @return current time
*/
public static String getCurrentTime() {
Date dt = new Date();
String sReturn = "";
DateFormat oDF = new SimpleDateFormat("HH:mm:ss");
sReturn = oDF.format(dt);
return(sReturn);
}
/**
* Returns current datetime in "dd MMMM yyyy HH:mm:ss".
*
* @return current datetime
*/
public static String getCurrentDateTime() {
Date dt = new Date();
String sReturn = "";
DateFormat oDF = new SimpleDateFormat("dd MMMM yyyy HH:mm:ss");
sReturn = oDF.format(dt);
return(sReturn);
}
/**
* Returns string array (that can be used in the WHERE IN clause of a SQL
* query) from an integer list.
*
* @param olArray
* integer list that needs to be converted
* @return string containing the WHERE IN array (including the opening and
* closing brackets)
*/
public static String getSqlInArrayFromIntegerList(ArrayList<Integer> olArray) {
StringBuffer oRetBuff = new StringBuffer();
int i;
if (olArray == null) {
oRetBuff.append("()");
} else if (olArray.size() == 0) {
oRetBuff.append("()");
} else if (olArray.size() == 1) {
oRetBuff.append("(").append(olArray.get(0)).append(")");
} else {
oRetBuff.append("(");
for (i = 0; i < olArray.size(); i++) {
oRetBuff.append(olArray.get(i));
if (i != olArray.size()-1) {
oRetBuff.append(",");
}
}
oRetBuff.append(")");
}
return(oRetBuff.toString());
}
/**
* Returns specified date in SQL format with leading zeroes wherever required.
*
* @param adDateToBeConverted
* date that needs to be formatted
* @return date in SQL format
*/
public static String getSqlDate(Date adDateToBeConverted) {
StringBuffer sRet = new StringBuffer();
sRet.append(adDateToBeConverted.getYear() + 1900);
if (adDateToBeConverted.getMonth() < 10) {
sRet.append("-0");
} else {
sRet.append("-");
}
sRet.append(adDateToBeConverted.getMonth());
if (adDateToBeConverted.getDate() < 10) {
sRet.append("-0");
} else {
sRet.append("-");
}
sRet.append(adDateToBeConverted.getDate());
if (adDateToBeConverted.getHours() < 10) {
sRet.append(" 0");
} else {
sRet.append(" ");
}
sRet.append(adDateToBeConverted.getHours());
if (adDateToBeConverted.getMinutes() < 10) {
sRet.append(":0");
} else {
sRet.append(":");
}
sRet.append(adDateToBeConverted.getMinutes());
if (adDateToBeConverted.getSeconds() < 10) {
sRet.append(":0");
} else {
sRet.append(":");
}
sRet.append(adDateToBeConverted.getSeconds());
return(sRet.toString());
}
/**
* A fail-safe method to obtain a date from a string. Currently, very useful
* in parsing date strings encountered in RSS/ATOM XML feeds.
*
* @param asDate
* date string that needs to be parsed
* @return parsed date instance
*/
public static Date getDateFromString(String asDate) {
Date dtReturn;
DateFormat formatter;
formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
try {
dtReturn = formatter.parse(asDate);
} catch (ParseException e) {
formatter = new SimpleDateFormat("dd-MM-yy HH:mm");
try {
dtReturn = formatter.parse(asDate);
} catch (ParseException e2) {
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
dtReturn = formatter.parse(asDate);
} catch (ParseException e3) {
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
dtReturn = formatter.parse(asDate);
} catch (ParseException e4) {
formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
dtReturn = formatter.parse(asDate);
} catch (ParseException e5) {
formatter = new SimpleDateFormat("MMM dd, yyyy HHmm");
try {
dtReturn = formatter.parse(asDate);
} catch (ParseException e6) {
try {
dtReturn = new Date(asDate); // leaving it to JRE's best guess
} catch (IllegalArgumentException e7) {
dtReturn = new Date(); // defaults to current date
}
}
}
}
}
}
}
return(dtReturn);
}
/**
* Returns specified string after replacing all non-alphanumeric characters
* with underscore ('_') character. Makes it safe for use in URLs and file
* names.
*
* @param asInput string that needs to converted
* @return transformed string
*/
public static String getEasyString(String asInput) {
return(getEasyString(asInput, '_'));
}
/**
* Returns specified string after replacing all non-alphanumeric
* and non-ANSI characters with specified character. Makes it safe for
* use in URLs and file names.
*
* @param asInput
* string that needs to be transformed
* @param acPreferredSeparator
* character with which all non-alphanumeric characters need to be
* replaced with
* @return transformed string
*/
public static String getEasyString(String asInput, char acPreferredSeparator) {
String sRet, sSeparator;
if (asInput == null) {
sRet = "";
} else if (asInput.length() < 1) {
sRet = "";
} else {
if (acPreferredSeparator == Character.forDigit(0, 10)) {
sSeparator = "_";
} else {
sSeparator = Character.toString(acPreferredSeparator);
}
sRet = asInput;
sRet = sRet.replaceAll("[^A-Za-z0-9]", sSeparator);
sRet = sRet.replaceAll(sSeparator + sSeparator, sSeparator);
sRet = sRet.replaceAll(sSeparator + sSeparator, sSeparator);
}
return(sRet);
}
/**
* Returns a random nummber (below {@link Integer#MAX_VALUE});
* @return a random number
*/
public static int getRandomNumber() {
return(getRandomNumber(Integer.MAX_VALUE));
}
/**
* Returns a random number below specified number.
* @param iLimit number below which the random number needs to be found
* @return the random number
*/
public static int getRandomNumber(int iLimit) {
int iRet;
Random rnd = new Random();
if (iLimit < 4) {
iRet = rnd.nextInt(4);
} else {
iRet = rnd.nextInt(iLimit);
}
return(iRet);
}
public static boolean isHttpUrl(String asUrl) {
boolean bRet = false;
try {
URL oURL = new URL(asUrl);
URI oURI = oURL.toURI();
if (oURI.getScheme().contentEquals("http") || oURI.getScheme().contentEquals("https")) {
bRet = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return(bRet);
}
/**
* Starts a synchronous download from specified URL and save it
* to specified file path. This method should not be called in
* the UI thread. It is suitable for {@link IntentService} where
* the download needs to happen sequentially.
*
* @param asURL address from which the file needs to be download
* @param asFile path to which the file needs to be saved
* @return download information
*/
public static MvException startSyncDownload(String asURL, String asFile) {
return(startSyncDownload(asURL, asFile, false, ""));
}
/**
* Starts a synchronous download from specified URL and save it
* to specified file path. This method should not be called in
* the UI thread. It is suitable for {@link IntentService} where
* the download needs to happen sequentially. The specified
* user agent (browser or http client program) will be mimicked to
* download the file.
*
* @param asURL address from which the file needs to be download
* @param asFile path to which the file needs to be saved
* @param asUserAgent user agent string of the http client that needs to be mimicked
* @return download information
*/
public static MvException startSyncDownload(String asURL, String asFile, String asUserAgent) {
return(startSyncDownload(asURL, asFile, false, "", asUserAgent));
}
/**
* Starts a synchronous download from specified URL and save it
* to specified file path or directory. This method should not be called in
* the UI thread. It is suitable for {@link IntentService} where
* the download needs to happen sequentially. if abGuessFileName is true,
* then the method tries to guess the download file name from the URL or from the
* specfied mime type. If abGuessFileName is false, then the method is same as
* calling {@link #startSyncDownload(String, String)} and other parameters will
* be ignored.
*
* @param asURL address from which the file needs to be download
* @param asPath file or directory pathname (depending on abGuessFileName)
* @param abGuessFileName whether the file name should be guessed from asURL
* @param asMimeType mime type of the download
* @return download information
*/
public static MvException startSyncDownload(String asURL, String asPath, boolean abGuessFileName, String asMimeType) {
return(startSyncDownload(asURL, asPath, abGuessFileName, asMimeType, ""));
}
/**
* Starts a synchronous download from specified URL and save it
* to specified file path or directory. This method should not be called in
* the UI thread. It is suitable for {@link IntentService} where
* the download needs to happen sequentially. if abGuessFileName is true,
* then the method tries to guess the download file name from the URL or from the
* specfied mime type. If abGuessFileName is false, then the method is same as
* calling {@link #startSyncDownload(String, String)} and other parameters will
* be ignored. The specified user agent (browser or http client program) will be
* mimicked to download the file.
*
* @param asURL address from which the file needs to be download
* @param asPath file or directory pathname (depending on abGuessFileName)
* @param abGuessFileName whether the file name should be guessed from asURL
* @param asMimeType mime type of the download
* @param asUserAgent user agent string of the http client that needs to be mimicked
* @return download information
*/
public static MvException startSyncDownload(String asURL, String asPath, boolean abGuessFileName, String asMimeType, String asUserAgent) {
URL oURL;
HttpURLConnection moURLConnection;
MvException oRet = new MvException();
byte[] buf = new byte[1024];
int n = 0;
String sDownloadedFile, sDownloadPath;
if (abGuessFileName) {
sDownloadedFile = URLUtil.guessFileName(asURL, null, asMimeType);
sDownloadPath = asPath + "/" + sDownloadedFile;
} else {
sDownloadPath = asPath;
}
try {
oURL = new URL(asURL);
moURLConnection = (HttpURLConnection) oURL.openConnection();
if (asUserAgent.length() > "Mozilla".length()) {
moURLConnection.setRequestProperty("User-Agent", asUserAgent);
//MvMessages.logMessage("Mimicking" + asUserAgent);
//MvMessages.logMessage("Mimicking");
}
moURLConnection.setConnectTimeout(5000);
// Handle redirects
int iResponseCode = moURLConnection.getResponseCode();
if ((iResponseCode == HttpURLConnection.HTTP_MOVED_TEMP) ||
(iResponseCode == HttpURLConnection.HTTP_MOVED_PERM) ||
(iResponseCode == HttpURLConnection.HTTP_SEE_OTHER)) {
if (moURLConnection.getHeaderField("Location") != null) {
String sNewUrl = moURLConnection.getHeaderField("Location");
MvMessages.logMessage("Redirected to " + sNewUrl);
oURL = new URL(sNewUrl);
moURLConnection = (HttpURLConnection) oURL.openConnection();
} else {
MvMessages.logMessage("Redirected but no new location");
oRet.mbSuccess = false;
oRet.msProblem = "Redirected but no new location";
oRet.msPossibleSolution = "Check headers";
return(oRet);
}
}
moURLConnection.connect();
BufferedInputStream in = new BufferedInputStream(moURLConnection.getInputStream());
try {
FileOutputStream of = new FileOutputStream(asPath);
do {
n = in.read(buf, 0, 1024);
if (n != -1) {
of.write(buf, 0, n);
} else {
of.flush();
in.close();
of.close();
}
} while(n != -1);
oRet.mbSuccess = true;
oRet.moResult = sDownloadPath;
} catch (IOException e) {
oRet.mbSuccess = false;
oRet.mException = e;
oRet.msProblem = "There is a local storage issue.";
oRet.msPossibleSolution = "A writable location is required.";
e.printStackTrace();
}
} catch (MalformedURLException e) {
oRet.mbSuccess = false;
oRet.mException = e;
oRet.msProblem = "This is an invalid URL (link).";
oRet.msPossibleSolution = "A valid URL (link) is required.";
e.printStackTrace();
} catch (UnknownHostException e) {
oRet.mbSuccess = false;
oRet.mException = e;
oRet.msProblem = "There is no Internet connection or the website does not exist.";
oRet.msPossibleSolution = "An working Internet connection or a valid website address is required.";
e.printStackTrace();
} catch (FileNotFoundException e) {
oRet.mbSuccess = false;
oRet.mException = e;
oRet.msProblem = "The link (URL) is broken or missing.";
oRet.msPossibleSolution = "An existing link (URL) is required.";
e.printStackTrace();
} catch (IOException e) {
oRet.mbSuccess = false;
oRet.mException = e;
oRet.msProblem = "There is no network connection.";
oRet.msPossibleSolution = "A good connection to the network is required.";
e.printStackTrace();
}
return oRet;
}
public static boolean[] convertToArray(ArrayList<Boolean> aoList) {
boolean[] arrbReturn = null;
if (aoList != null && aoList.size() > 0) {
arrbReturn = new boolean[aoList.size()];
int i = 0;
for (Boolean oListItem : aoList) {
arrbReturn[i++] = oListItem.booleanValue();
}
}
return(arrbReturn);
}
public static ArrayList<Boolean> convertToList(boolean[] aarrbList) {
ArrayList<Boolean> oReturnList = new ArrayList<Boolean>();
if (aarrbList != null && aarrbList.length > 0) {
for (boolean bArrayValue: aarrbList) {
oReturnList.add(bArrayValue);
}
}
return(oReturnList);
}
public static String convertByteArrayToHexString(byte[] arrBytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[arrBytes.length * 2];
for (int i = 0; i < arrBytes.length; i++ ) {
int j = arrBytes[i] & 0xFF;
hexChars[i * 2] = hexArray[j >>> 4];
hexChars[i * 2 + 1] = hexArray[j & 0x0F];
}
return(new String(hexChars));
}
private class MvMediaPlayer implements MediaPlayer.OnCompletionListener {
MediaPlayer mPlayer;
public MvMediaPlayer(Context aContext, int aiSoundResource) {
super();
mPlayer = MediaPlayer.create(aContext, aiSoundResource);
if (mPlayer != null) {
mPlayer.setOnCompletionListener(this);
mPlayer.start();
}
}
@Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
}
public MvMediaPlayer(Context aoContext, Uri aoAlarmUri) {