Skip to content

Instantly share code, notes, and snippets.

@aftabsikander
Created October 15, 2014 11:56
Show Gist options
  • Select an option

  • Save aftabsikander/61fb4af37c7a2514b18b to your computer and use it in GitHub Desktop.

Select an option

Save aftabsikander/61fb4af37c7a2514b18b to your computer and use it in GitHub Desktop.
A Utility/Helper class for common method used across the Project
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.os.StrictMode;
import android.util.Log;
import android.util.Patterns;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
public class ProjectUtils
{
public static final int MESSAGE_LENGTH_LONG = Toast.LENGTH_LONG;
public static final int MESSAGE_LENGTH_SHORT = Toast.LENGTH_SHORT;
public static final int _noAnimation = Intent.FLAG_ACTIVITY_NO_ANIMATION;
public static final Integer TWITTER_POST_COUNT = 140;
public static final int WAKELOCK_TIMEOUT = 60 * 1000;
public static final String FACEBOOK_APPLICATION_PACKAGE_NAME = "com.facebook.katana";
public static final String TWITTER_APPLICATION_PACKAGE_NAME = "com.twitter.android";
public static final String DOTNET_EMAIL_REGEX = "/^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i";
public static final String TWITDROID_APPLICATION_PACKAGE_NAME = "com.twidroid";
public static final String TWEETCASTER_APPLICATION_PACKAGE_NAME = "com.handmark.tweetcaster";
public static final String THEDECK_APPLICATION_PACKAGE_NAME = "com.thedeck.android";
//region Static Fields and Constant
public static long _splashDelay = 5000; // 5 seconds
public static String EMAIL_REGEX_PATTERN = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";
public static final Pattern CHECK_EMAIL_ADDRESS_PATTERN = Pattern.compile(EMAIL_REGEX_PATTERN);
//endregion
//region Helper Method for database existing
public static boolean doesDatabaseExist(ContextWrapper context, String dbName)
{
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}
// endregion
//region Helper Method for taking ScreenShot from the Google Map Object
public static void takeMapSnapShot(GoogleMap mMap, final Context mContext)
{
if (mMap == null)
{
return;
}
final GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback()
{
@Override
public void onSnapshotReady(Bitmap snapshot)
{
// Callback is called from the main thread, so we can modify the ImageView safely.
//snapshotHolder.setImageBitmap(snapshot);
File carSnapShotFile = ProjectUtils.createFileInsideTheFolder(ProjectUtils.getCarLocationImageFolderPath(), ProjectUtils.CAR_LOCATION_SNAPSHOT_FILE_NAME);
FileOutputStream out = null;
try
{
out = new FileOutputStream(carSnapShotFile);
snapshot.compress(Bitmap.CompressFormat.PNG, 70, out);
//ProjectUtils.showToast(mContext, "SnapShot Taken", ProjectUtils.MESSAGE_LENGTH_SHORT);
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
//endregion
// region Helper Methods for share Intents
public static Intent startShareIntent(Context mContext, String applicationName, String applicationLink)
{
// Standard message to send
String msg = "";
final String TAG = "IntentShare";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent targetedShareIntent = null;
List<ResolveInfo> resInfo = mContext.getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty())
{
for (ResolveInfo resolveInfo : resInfo)
{
String packageName = resolveInfo.activityInfo.packageName;
targetedShareIntent = new Intent(android.content.Intent.ACTION_SEND);
targetedShareIntent.setType("text/plain");
// Find twitter: com.twitter.android...
if (FACEBOOK_APPLICATION_PACKAGE_NAME.equals(packageName))
{
DebugLogUtils.showLogs(TAG, "Facebook Message: " + msg);
targetedShareIntent.putExtra(Intent.EXTRA_SUBJECT, applicationName);
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg);
} else if (TWITTER_APPLICATION_PACKAGE_NAME.equals(packageName))
{
targetedShareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, applicationName);
String twitterShortDesc = getShorterStringForTwitterPost(msg);
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, twitterShortDesc);
} else
{
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg);
}
targetedShareIntent.setPackage(packageName);
targetedShareIntents.add(targetedShareIntent);
}
}
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
return chooserIntent;
}
public static Intent startShareIntent(Context mContext, String para_title, String para_URL, String activityName)
{
// Standard message to send
String msg = para_title + para_URL;
final String TAG = "IntentShare";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent targetedShareIntent = null;
List<ResolveInfo> resInfo = mContext.getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty())
{
for (ResolveInfo resolveInfo : resInfo)
{
String packageName = resolveInfo.activityInfo.packageName;
targetedShareIntent = new Intent(android.content.Intent.ACTION_SEND);
targetedShareIntent.setType("text/plain");
// Find twitter: com.twitter.android...
if (FACEBOOK_APPLICATION_PACKAGE_NAME.equals(packageName))
{
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg);
} else if (TWITTER_APPLICATION_PACKAGE_NAME.equals(packageName))
{
targetedShareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, para_title);
if (activityName.contentEquals("NamazTime"))
{
String twitterShortDesc = getShorterStringForTwitterPost(para_title + para_URL);
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, twitterShortDesc);
} else
{
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, para_URL);
}
}
else
{
// Rest of Apps
// Log.d(TAG, "Rest of the app: " + msg);
targetedShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg);
}
targetedShareIntent.setPackage(packageName);
targetedShareIntents.add(targetedShareIntent);
}
}
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
return chooserIntent;
}
public static String getShorterStringForTwitterPost(String para_content)
{
int current_contentCharacterCount = para_content.length();
String generatedContentForTwitter = "";
char[] para_contentSplitIntoCharacter = para_content.toCharArray();
for (int i = 0; i < current_contentCharacterCount; i++)
{
if (i == TWITTER_POST_COUNT - 2)
{
generatedContentForTwitter += "..";
break;
} else
{
generatedContentForTwitter += para_contentSplitIntoCharacter[i];
}
}
return generatedContentForTwitter;
}
//endregion
//region Helper Methods for Checking Database into the mobile device
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public static boolean checkDataBase(Context mContext)
{
boolean checkdb = false;
try
{
String myPath = mContext.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator + mContext.getString(R.string.db_name);
File dbfile = new File(myPath);
checkdb = dbfile.exists();
} catch (SQLiteException e)
{
System.out.println("Database doesn't exist");
}
return checkdb;
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public static Boolean checkdbMethod(Context context)
{
File database = context.getDatabasePath(context.getString(R.string.db_name));
if (!database.exists())
{
// Database does not exist so copy it from assets here
DebugLogUtils.showLogs("Database", "Not Found");
return false;
} else
{
DebugLogUtils.showLogs("Database", "Found");
return true;
}
}
// endregion
// region General Helper Methods
public static void buildObjectForPicasso(Context mContext)
{
picasso = new Picasso.Builder(mContext).build();
}
/**
* This method is used to go across the application i.e opening new Activities
*/
public static void genericIntent(Context context, Class<?> className, Bundle datapassingBundle)
{
Intent intent = new Intent();
intent.setClass(context, className);
intent.setFlags(_noAnimation);
if (datapassingBundle != null) intent.putExtras(datapassingBundle);
context.startActivity(intent);
}
/**
* This Method is use to get the Home LauncherName from the device so that
*/
public static void GotoHomeScreen(Context context)
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
}
/**
* This method is used to display message on Screen
*
* @param context From where this function is being called.
* @param message The message we want to display.
* @param duration How long the message should stay on Screen.
*/
public static void showToast(Context context, String message, int duration)
{
Toast.makeText(context, message, duration).show();
}
/**
* This method is used to allow Network stream works on UI treads.
*/
@SuppressLint("NewApi")
public static void SetStrickPolicy()
{
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public static void buildAlertMessageNoGps(final Context mContext)
{
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id)
{
mContext.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id)
{
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
// #endregion
// region Validation Methods
/**
* This method is used to validate Email address input by the user
*
* @param email Entered Email address
*
* @return return true if email is in correct format else return false
*/
public static boolean isValidEmail(String email)
{
return ProjectUtils.CHECK_EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
// endregion
// region Helper Methods for the UserAccount
/**
* This method is used to get all the user account from device and return the set<String> containing all its
* account
*
* @param mContext
*
* @return return the account name from the device
*/
public static Set<String> getUserAccountFromDevice(Context mContext)
{
final Account[] accounts = AccountManager.get(mContext).getAccounts();
final Set<String> emailSet = new HashSet<String>();
for (Account account : accounts)
{
if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches())
{
emailSet.add(account.name);
}
}
return emailSet;
}
// endregion
// region Helper Methods for Home Screen Package Name
public static String getHomeLauncherPackageName(Context mContext)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String currentHomePackage = resolveInfo.activityInfo.packageName;
DebugLogUtils.showLogs("HomeScreenPackageName", currentHomePackage);
return currentHomePackage;
}
// endregion
//region Helper Method for Bugsense Setup
public static void SetupBugSenseForActivity(Class<?> activityClass, Context mContext)
{
DebugLogUtils.showLogs("ActivityBugSense", activityClass.toString());
BugSenseHandler.I_WANT_TO_DEBUG = true;
BugSenseHandler.initAndStartSession(mContext, BUG_SENSE_API_KEY);
// BugSenseHandler.addCrashExtraData("ActivityBugSense", activityClass.toString());
}
// endregion
// region Helper Method for setup the Google Analytics for Application
/**
* This method is used to setup Google Analytics for Each Activity, And also it is used for the sending the screen
* name to google Analytic
*
* @param activityName Pass the activity Object on which the tracking will be made
* @param screenName Pass the activity ScreenName
*/
public static void setupGoogleAnalyticsForActivity(Activity activityName, String screenName)
{
EasyTracker.getInstance().activityStart(activityName);
GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(activityName);
Tracker mGaTrackerObjet = mGaInstance.getTracker(GOOGLE_ANALYTIC_TRACKER_ID);
mGaTrackerObjet.sendView(screenName);
}
public static void stopGoogleAnalyticsForActivity(Activity activityName)
{
EasyTracker.getInstance().activityStop(activityName);
}
// #endregion
// region Helper methods for Folder Creation/Reading
public static void createFolderForApplication()
{
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File applicationfolder = new File(extStorageDirectory, APPLICATION_FOLDER_TAG);
applicationfolder.mkdir();
File carLocationImageFolder = new File(applicationfolder, CAR_LOCATION_FOLDER_TAG);
carLocationImageFolder.mkdir();
}
/**
* This method is used to get the video Folder path from SD card
*
* @return Return the File instance of the Video Directory
*/
public static File getCarLocationImageFolderPath()
{
/* File file = new File(Environment.getExternalStorageDirectory() + File.separator + APPLICATION_FOLDER_TAG + File.separator + CAR_LOCATION_FOLDER_TAG);
*return file;
*/
}
public static int getCarLocationImageFileCount()
{
File file[] = getCarLocationImageFolderPath().listFiles();
if (file != null)
{
int countOfFilesPresent = file.length;
Log.d("Files", "FileName:" + file[countOfFilesPresent].getName());
return splitFileName(file[countOfFilesPresent].getName());
} else
{
return 1000;
}
}
public static int splitFileName(String para_FileName)
{
String[] splitArr = para_FileName.split("-");
int startingIndexForSplit = splitArr[1].indexOf(".");
String finalImageNumberCount = splitArr[1].substring(startingIndexForSplit);
return Integer.valueOf(finalImageNumberCount);
}
/**
* This method is used to create file inside a particular directory
*
* @param directoryPath Path/File object of the directoryFolder
* @param filename File name
*
* @return It return the File instance of the current folder where new file is created
*/
public static File createFileInsideTheFolder(File directoryPath, String filename)
{
File file = new File(directoryPath, filename);
try
{
file.createNewFile();
return file;
} catch (IOException e1)
{
e1.printStackTrace();
return file;
}
}
/**
* This method is used to check for the file is present on the SD card if it exist it return true else return false
*
* @param directoryPath The path where the file is to be located
* @param filename File name with extension
*
* @return if File exist return true else return false
*/
public static boolean isFileAlreadyExistInTheFolder(String filePathToLook)
{
File file = new File(filePathToLook);
if (file.exists())
{
return true;
} else
{
return false;
}
}
// endregion
//region Helper Methods for Getting the Time span
public static long getElaspedTime(long timeInMilliSecond)
{
long lStartTime = new Date(timeInMilliSecond).getTime();
long lEndTime = new Date().getTime();
long difference = lEndTime - lStartTime;
return difference;
}
public static String getFormatedCurrentTime()
{
Calendar systemTime = Calendar.getInstance();
int Hour = systemTime.get(Calendar.HOUR_OF_DAY);
int Minute = systemTime.get(Calendar.MINUTE);
return String.format("%02d:%02d", Long.valueOf(Hour), Long.valueOf(Minute));
}
//endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment