import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AppUtil implements AppConstansts {
private Context mContext;
public AppUtil(Context Context) {
mContext = Context;
}
/***
* Check if the Email is valid or not
*
* @param email
* @return
*/
public boolean isEmailValid(String email) {
String regExpn = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
return false;
}
}
/***
* Display snack bar for network error
*
* @param View
*/
public void displayNoInternetSnackBar(View View, final AppCallbackListener listener) {
final Snackbar snackbar = Snackbar
.make(View, "No internet connection!", Snackbar.LENGTH_LONG);
snackbar.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
snackbar.dismiss();
listener.onAppCallback(AppConstansts.SNACKBAR_RETRY);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById
(android.support.design.R.id.snackbar_text);
textView.setTextColor(mContext.getResources().getColor(R.color.app_color));
snackbar.show();
}
/***
* Display snack bar for network error
*
* @param View
*/
public void displayNoInternetSnackBar(View View) {
Snackbar snackbar = Snackbar
.make(View, "No internet connection!", Snackbar.LENGTH_LONG)
/*.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
})*/;
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
android.view.View sbView = snackbar.getView();
TextView textView = (TextView)
sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
/***
* Display message
*
* @param view
* @param Message
*/
public static void displaySnackBarWithMessage(View view, String Message) {
Snackbar.make(view, Message, Snackbar.LENGTH_LONG).show();
}
public static void displayToastWithMessage(Context context, String Message) {
Toast.makeText(context, Message, Toast.LENGTH_LONG).show();
}
/***
* @param ctx
* @param Message
*/
public void displayAlertDailog(Context ctx, String Message) {
AlertDialog.Builder builder =
new AlertDialog.Builder(ctx, R.style.AppCompatAlertDialogStyle);
builder.setMessage(Message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
//builder.setNegativeButton("Cancel", null);
builder.show();
}
/***
* To check the internet connection
*
* @return
*/
public boolean getConnectionState() {
ConnectivityManager cm = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null)
return false;
else
return true;
}
/***
* Display Alert Message
*
* @param Msg
*/
public void displayAlert(String Msg) {
AlertDialog.Builder myAlertDialog
= new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle);
myAlertDialog.setTitle(R.string.app_name);
myAlertDialog.setMessage(Msg);
myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// do something when the OK button is clicked
}
});
myAlertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) { // do something
}
});
myAlertDialog.show();
}
/***
* get Hash Key
*/
public void getKeyHash() {
PackageInfo info = null;
try {
info = mContext.getPackageManager().getPackageInfo(
mContext.getPackageName(), PackageManager.GET_SIGNATURES);
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
ErrorLog.SaveErrorLog(e1);
}
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
ErrorLog.SaveErrorLog(e1);
}
md.update(signature.toByteArray());
Log.d("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
}
/***
* Get the device unique id
*
* @return
*/
public String getDeviceID() {
String AndroidId = null;
try {
AndroidId = Settings.Secure.getString(mContext.getContentResolver(),
Settings.Secure.ANDROID_ID);
} catch (Exception e) {
e.printStackTrace();
ErrorLog.SaveErrorLog(e);
} finally {
return AndroidId;
}
}
/***
* Get Applicaiton version name
*
* @return
*/
public String getAppVersionName() {
String VersionName = "";
try {
PackageInfo pInfo = mContext.getPackageManager().
getPackageInfo(mContext.getPackageName(), 0);
VersionName = pInfo.versionName;
} catch (Exception e) {
e.printStackTrace();
ErrorLog.SaveErrorLog(e);
} finally {
return VersionName;
}
}
/***
* Get Applicaiton version Code
*
* @return
*/
public int getAppVersionCode() {
int VersionID = 1;
try {
PackageInfo pInfo = mContext.getPackageManager().
getPackageInfo(mContext.getPackageName(), 0);
VersionID = pInfo.versionCode;
} catch (Exception e) {
e.printStackTrace();
ErrorLog.SaveErrorLog(e);
} finally {
return VersionID;
}
}
/***
* Convert the local time to UTC
*
* @return
*/
public String getUTCTime() {
String lv_dateFormateInUTC = ""; //Will hold the final converted date
try {
SimpleDateFormat lv_formatter = new SimpleDateFormat("dd/MM/yy hh:mm a");
lv_formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
lv_dateFormateInUTC = lv_formatter.format(new Date());
Log.v("", "UTC TIme == " + lv_dateFormateInUTC);
} catch (Exception e) {
e.printStackTrace();
ErrorLog.SaveErrorLog(e);
}
return lv_dateFormateInUTC;
}
/***
* Convert the UTC time to local
*
* @return
*/
/*public String convertUTCToLocalTime(SimpleDateFormat simpleDateFormat, String strDate) {
String LocalDate = null;
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(strDate);
LocalDate = myDate.toString();
} catch (Exception e) {
e.printStackTrace();
ErrorLog.SaveErrorLog(e);
}
return LocalDate;
}*/
/***
* Convert UTC time to local time
* @param Date
* @return
*/
public String convertUTCToLocalTime(SimpleDateFormat format, String Date){
String strDate = Date;
try{
//SimpleDateFormat format = new SimpleDateFormat("MM-dd-yy hh:mm:ss");
java.util.Date newDate = format.parse(Date);
strDate = format.format(newDate);
//Convert UTC to Local
format.setTimeZone(TimeZone.getTimeZone("UTC"));
java.util.Date myDate = format.parse(strDate);
strDate = myDate.toString();
SimpleDateFormat formatDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
newDate = formatDate.parse(strDate);
format = new SimpleDateFormat("MM-dd-yy HH:mm:ss");
strDate = format.format(newDate);
}
catch(Exception e){
e.printStackTrace();
}
return strDate;
}
/***
* Check if video is downloaded on sdcard or not
*
* @param URL
* @return
*/
public boolean isVideoDownload(String URL) {
boolean status = false;
File dir = new File(Environment.getExternalStorageDirectory() + "/"
+ mContext.getResources().getString(R.string.app_name) + "/" + URL);
if (dir.exists()) {
status = true;
}
return status;
}
/***
* Check if video is avilable in extermal memory card
*
* @param URL
* @return
*/
public boolean isVideoAvialableInMemoryCard(String URL) {
boolean status = false;
File dir = new File(System.getenv("SECONDARY_STORAGE") + "/"
+ mContext.getResources().getString(R.string.app_name) + "/" + URL);
if (dir.exists()) {
status = true;
}
return status;
}
/***
* Encrpt the Text
*
* @param Text
* @return
* @throws GeneralSecurityException
*//*
public static String encrypt(String Text) throws GeneralSecurityException {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(ENCRPYT_KEY.getBytes(), ALGORITHM);
Cipher cipherAES = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipherAES.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] cipherText = cipherAES.doFinal(Text.getBytes());
return new String(Base64.encode(cipherText, Base64.DEFAULT)).trim();
} catch (Exception e) {
e.printStackTrace();
ErrorLog.SaveErrorLog(e);
}
return null;
}
*//***
* Decrypt the message
*
* @param encryptedText
* @return
* @throws GeneralSecurityException
*//*
public static String decrypt(byte[] encryptedText) throws GeneralSecurityException {
SecretKey secret_key = new SecretKeySpec(ENCRPYT_KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secret_key);
encryptedText = Base64.decode(encryptedText, Base64.DEFAULT);// = cipher.doFinal(encryptedText);
byte[] decrypted = cipher.doFinal(encryptedText);
return new String(decrypted).trim();
}
private static String convertBinary2Hexadecimal(byte[] bytes) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
*//***
* @param data
* @return
*//*
public static String bytesToHex(byte[] data) {
if (data == null)
return null;
String str = "";
for (int i = 0; i < data.length; i++) {
if ((data[i] & 0xFF) < 16)
str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
else
str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
}
return str;
}*/
/***
* Insert UTC date Time to when the app open from Navigation Screen
*/
public void lastOpenApp(Context mContext){
try{
SharedPrefrences mSharedPref = new SharedPrefrences(mContext);
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy hh:mm a");
Date UTCDateTime = format.parse(getUTCTime());
String strUTCDateTime = format.format(UTCDateTime);
mSharedPref.setPreferences(mSharedPref.LAST_APP_OPEN_DATE, strUTCDateTime);
}
catch (Exception e){
}
}
/**
* Check if the user login has a
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public boolean isOwnerUser(){
boolean isSecondaryUser = false;
if(android.os.Build.VERSION.SDK_INT >= 17) {
UserHandle uh = android.os.Process.myUserHandle();
UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
if(null != um)
{
long userSerialNumber = um.getSerialNumberForUser(uh);
Log.d("USer Serial Number", "userSerialNumber = " + userSerialNumber);
isSecondaryUser = true;
return 0 == userSerialNumber;
}
else
isSecondaryUser = false;
}
else {
// Do something regular
}
return isSecondaryUser;
}
/***
* Check if the application is downloaded from play store or not
* @param context
* @return
*/
public static boolean isDownloadedFromPlayStore(Context context) {
boolean result = false;
try {
String installer = context.getPackageManager()
.getInstallerPackageName(context.getPackageName());
result = !TextUtils.isEmpty(installer);
} catch (Throwable e) {
}
return result;
}
}
Let's Learn Java Programming..... Through Lots of Coding Examples For Each Topic. Now Go For It ..!
Core Java Program :-
Java
C text
C Language Program : -