Skip to content

Instantly share code, notes, and snippets.

@pookie13
Created June 5, 2015 05:58
Show Gist options
  • Save pookie13/856d2debbc6b7b499b46 to your computer and use it in GitHub Desktop.
Save pookie13/856d2debbc6b7b499b46 to your computer and use it in GitHub Desktop.
Common function used in project.
public class SharedHelper {
private static NotificationManager mNotificationManager;
private static Class<?> aClass;
private static ProgressDialog progressDialog;
private static Uri mBaseUri;
private static SharedPreferences.Editor editor;
private static SharedPreferences pref;
private static Class<?> mClass;
public static void showRecentChats(Context context) {
try {
mClass = Class.forName("com.hestabit.rqchat.RecentActivity");
Log.d("secondActivity", mClass.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Intent intent = new Intent(context, mClass);
context.startActivity(intent);
}
/**
* function used to show notification and handle click on notification
* provide full name (with package name) to second Activity.
*
* @param context
* @param title
* @param subTitle
* @param ticker
* @param secondActivity
*/
public static void showNotification(Context context, String title, String subTitle, String ticker, String secondActivity) {
String s = secondActivity + ".class";
Log.d("secondActivity", secondActivity);
try {
aClass = Class.forName(secondActivity);
Log.d("secondActivity", aClass.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(title);
mBuilder.setContentText(subTitle);
mBuilder.setTicker(ticker);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
//todo:make Statcking Notification.
// mBuilder.setStyle(new NotificationCompat.InboxStyle().addLine(dsghgshdgshdg));
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(9);
/* Creates an explicit intent for an Activity in your app */
if (aClass != null) {
Intent resultIntent = new Intent(context, aClass);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// stackBuilder.addParentStack(SecondActivity.class);
/* Adds the Intent that starts the Activity to the top of the stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
}
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
/* notificationID allows you to update the notification later on. */
mNotificationManager.notify(12, mBuilder.build());
}
/**
* function used to get UGT time.
*
* @return
*/
public static String getGMTTime() {
final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.d("UTC TIME PICKER", f.format(new Date()));
return f.format(new Date());
}
public static void setErrorNotify(View view, String error) {
}
/**
* function used to show toast/
*
* @param context
* @param message
*/
public static void showToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* function used to get is phone connected to internet.
*
* @param context
*/
public static void isInternetConnected(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
if (!activeNetworkInfo.isConnected()) {
showToast(context, "No InterNet Connection");
} else {
showToast(context, "connected");
}
}
}
public static boolean isNetConnected(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* function used to Save contact in phone contacts.
*
* @param name
* @param phoneNumber
*/
public static void saveTOContactBook(Context mContext, String name, String phoneNumber) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContentInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContentInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name).build());
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContentInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber) // Number of the person
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
try {
ContentProviderResult[] res = mContext.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException re) {
} catch (OperationApplicationException e) {
}
showToast(mContext, "contact Save.");
}
public static void openDialPad(Context context, String number) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
dial.setData(Uri.parse("tel:" + number));
context.startActivity(dial);
}
/**
* function used to get all phone contacts list
*
* @param mContext
* @return
*/
public static String getAllContactsFromPhone(Context mContext) {
String phoneNumbers = null;
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
String numberData = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumbers = phoneNumbers + "," + numberData;
}
pCur.close();
}
}
}
return phoneNumbers;
}
/**
* function used to get name of user in phone contact repository of number provided.
*
* @param mContext
* @param phoneNumber
* @return
*/
public static String getContactName(Context mContext, String phoneNumber) {
Uri uri;
String[] projection;
mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[]{Contacts.People.NAME};
try {
Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[]{"display_name"};
} catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
/**
* function to create Random number
*
* @return String(random number)
*/
public static String getUniqueID() {
String id = UUID.randomUUID().toString();
return id;
}
/**
* function used to Encode Bitmap into Base 64.
*
* @param image
* @return
*/
public static String encodeToBase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
/**
* function used to Decode String(Base64) in to Image Bitmap.
*
* @param input
* @return
*/
public static Bitmap decodeBase64Profile(String input) {
Bitmap bitmap = null;
if (input != null) {
byte[] decodedByte = Base64.decode(input, 0);
bitmap = BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
return bitmap;
}
/**
* function used to show progress dialog.
*/
public static void showProgressDialog(Context mContext) {
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
/**
* hide progress dialog.
*/
public static void hideProgressDialog() {
progressDialog.dismiss();
}
/**
* function used to get SubString From String.
*
* @param mainString
* @param lastString
* @param startString
* @return
*/
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
Log.d("message", "" + mainString.substring(startIndex, endIndex));
endString = mainString.substring(startIndex, endIndex);
return endString;
}
/**
* Saves the Bitmap as a PNG file at path 'fullPath'
*
* @param fullPath path of the image file
* @param bitmap the image as a Bitmap
* @return true if it successfully saved, false otherwise
* path in form of(Environment.getExternalStorageDirectory().toString() +"/" + "folderName";);
*/
private boolean saveBitmapInToFolder(String fullPath, Bitmap bitmap) {
if (fullPath == null || bitmap == null)
return false;
boolean fileCreated = false;
boolean bitmapCompressed = false;
boolean streamClosed = false;
File imageFile = new File(fullPath);
if (imageFile.exists())
if (!imageFile.delete())
return false;
try {
fileCreated = imageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(imageFile);
bitmapCompressed = bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
bitmapCompressed = false;
} finally {
if (out != null) {
try {
out.flush();
out.close();
streamClosed = true;
} catch (IOException e) {
e.printStackTrace();
streamClosed = false;
}
}
}
return (fileCreated && bitmapCompressed && streamClosed);
}
/**
* Decodes the Bitmap from 'path' and returns it
*
* @param path image path
* @return the Bitmap from 'path'
*/
public static Bitmap getImageFromPath(String path) {
Bitmap bitmapFromPath = null;
try {
bitmapFromPath = BitmapFactory.decodeFile(path);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return bitmapFromPath;
}
//tiny DB like
public static void insertIntoSharedPref(Context mContext, String key, String value) {
pref = mContext.getSharedPreferences(mContext.getString(R.string.shared_pref_name), mContext.MODE_PRIVATE);
editor = pref.edit();
editor.putString(key, value);
editor.commit();
}
public static String getSharedPrefData(Context mContext, String key) {
pref = mContext.getSharedPreferences(mContext.getString(R.string.shared_pref_name), mContext.MODE_PRIVATE);
return pref.getString(key, null);
}
/*public String getContactName(Context context,final String phoneNumber) {
Uri uri;
String[] projection;
mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[]{android.provider.Contacts.People.NAME};
try {
Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[]{"display_name"};
} catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}*/
public static String getNumberFromJID(String jid) {
if (jid.contains("@hestalabs")) {
Log.d("message", "" + jid);
int endIndex = jid.indexOf('@');
int startIndex = 0;
Log.d("message", "" + jid.substring(startIndex, endIndex));
jid = jid.substring(startIndex, endIndex);
}
return jid;
}
/**
* function used to get date and time by milli second.
*
* @param dateInMilliseconds
* @param dateFormat
* @return
*/
public static String convertDate(String dateInMilliseconds, String dateFormat) {
return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}
public static String convertDate(long dateInMilliseconds, String dateFormat) {
return DateFormat.format(dateFormat, dateInMilliseconds).toString();
}
/**
* function used to set Shortcut at home screen.
* PERMISSION:com.android.launcher.permission.INSTALL_SHORTCUT
*
* @param context
* @param userName
*/
public static void addShortcut(Context context, String userName, int position) {
Intent shortcutIntent = new Intent(context, ConversationActivity.class);
shortcutIntent.putExtra("position", position);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, userName);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(context, R.drawable.logo));
addIntent.putExtra("duplicate", false);
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
context.sendBroadcast(addIntent);
}
//@pookie make .txt file
public static void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), context.getString(R.string.app_name));
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Encodes bitmap to Base64 String
*
* @param path(ImageFilePath)
* @return Base64EncodedString
*/
public static String encodeBase64(String path) {
String byte64String = null;
if (path != null) {
Log.d("SharedHelper_ImagePath", path);
Bitmap bitmap = BitmapFactory.decodeFile(path);
if (bitmap != null) {
Log.d("SharedHelper_bitmap", bitmap.toString());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
byte64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.d("Base64EncodedSting", byte64String);
} else {
Log.d("Base64EncodedSting", " null");
}
}
return byte64String;
}
public static String encodeBase64(Bitmap bitmap) {
String byte64String = null;
if (bitmap != null) {
Log.d("SharedHelper_ImagePath", bitmap.toString());
if (bitmap != null) {
Log.d("SharedHelper_bitmap", bitmap.toString());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
byte64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.d("Base64EncodedSting", byte64String);
} else {
Log.d("Base64EncodedSting", " null");
}
}
return byte64String;
}
/**
* function used to make Animation while switch An Activity to Other.
* @param mContext
* @param startAnimation
* @param endAnimation
* 1-left_out
* 2-right_in
* 3-top_out
* 4-bottom_in
*/
public static void animationForSwitchActivity(Activity mContext,int startAnimation,int endAnimation){
int start = 0;
int end = 0;
switch (startAnimation){
case 1:
start = R.anim.left_out;
break;
case 2:
start = R.anim.right_in;
break;
case 3:
start = R.anim.top_out;
break;
case 4:
start = R.anim.bottom_in;
break;
}
switch (endAnimation){
case 1:
end = R.anim.left_out;
break;
case 2:
end = R.anim.right_in;
break;
case 3:
end = R.anim.top_out;
break;
case 4:
end = R.anim.bottom_in;
break;
}
mContext.overridePendingTransition(start,end);
}
public static void copyToClipboard(Context mContext,String textToCopy){
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard!=null) {
if (clipboard.hasText()){
clipboard.setText("");
}
clipboard.setText(textToCopy);
clipboard.getText();
showToast(mContext,"text copy to clipboard.");
}
}
/*String textSize = getTextSize();
if (textSize.equalsIgnoreCase("Small")) {
viewHolder.messageBody.setTextSize(10);
}else if (textSize.equalsIgnoreCase("Large")){
viewHolder.messageBody.setTextSize(50);
}else{
viewHolder.messageBody.setTextSize(16);
}
public String getTextSize(){
String string = activity.getPreferences().getString("fount_size", "Medium");
return string;
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment