Cleaned up the Util classes

This commit is contained in:
Karim Abou Zeid 2015-07-11 02:08:54 +02:00
commit 88d4dd8e80
37 changed files with 214 additions and 417 deletions

View file

@ -0,0 +1,51 @@
package com.kabouzeid.gramophone.util;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
/**
* @author Karim Abou Zeid (kabouzeid)
*/
public class ColorUtil {
public static int resolveColor(@NonNull Context context, @AttrRes int colorAttr) {
TypedArray a = context.obtainStyledAttributes(new int[]{colorAttr});
int resId = a.getColor(0, 0);
a.recycle();
return resId;
}
public static int getOpaqueColor(@ColorInt int color) {
return color | 0xFF000000;
}
public static int getColorWithAlpha(float alpha, int baseColor) {
int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24;
int rgb = 0x00ffffff & baseColor;
return a + rgb;
}
@SuppressWarnings("ResourceType")
public static int shiftColorDown(int color) {
int alpha = Color.alpha(color);
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.9f; // value component
return (alpha << 24) + (0x00ffffff & Color.HSVToColor(hsv));
}
@NonNull
public static ColorStateList getEmptyColorStateList(int color) {
return new ColorStateList(
new int[][]{
new int[]{}
},
new int[]{color}
);
}
}

View file

@ -3,6 +3,7 @@ package com.kabouzeid.gramophone.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@ -24,6 +25,20 @@ import java.io.IOException;
*/
public class ImageUtil {
public static Bitmap getResizedBitmap(@NonNull Bitmap bm, int newHeight, int newWidth, boolean recycleOld) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
if (recycleOld && resizedBitmap != bm) {
bm.recycle();
}
return resizedBitmap;
}
@Nullable
public static Bitmap getEmbeddedSongArt(File songFile, @NonNull Context context) {
try {

View file

@ -1,67 +0,0 @@
package com.kabouzeid.gramophone.util;
import android.content.Context;
import android.support.annotation.NonNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author Karim Abou Zeid (kabouzeid)
* <p/>
* A simple helper class for Android to read and write
* any serializeable object to the internal storage
*/
public final class InternalStorageUtil {
/**
* @param context a valid {@link Context}
* @param key the filename
* @param object any {@link java.io.Serializable} object which will be written to the internal storage
*/
public static synchronized void writeObject(@NonNull final Context context, @NonNull final String key, final Object object) throws IOException {
// First write the object to a file with ".tmp" postfix,
// so when an error occurs, we do not overwrite the original
// file (if exists) with a corrupted file.
String tempFileName = key + ".tmp";
FileOutputStream fos;
fos = context.openFileOutput(tempFileName, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
// after writing was successful we overwrite the original
// file (if exists) with the new file
renameAppFile(context, tempFileName, key);
}
/**
* @param context a valid {@link Context}
* @param originalFileName the original filename
* @param newFileName the new filename
*/
public static synchronized void renameAppFile(@NonNull final Context context, String originalFileName, @NonNull String newFileName) {
File originalFile = context.getFileStreamPath(originalFileName);
File newFile = new File(originalFile.getParent(), newFileName);
if (newFile.exists()) {
context.deleteFile(newFileName);
}
//noinspection ResultOfMethodCallIgnored
originalFile.renameTo(newFile);
}
/**
* @param context a valid {@link Context}
* @param key the filename
*/
public static synchronized Object readObject(@NonNull final Context context, String key) throws IOException,
ClassNotFoundException {
FileInputStream fis = context.openFileInput(key);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}
}

View file

@ -59,19 +59,6 @@ public class PlaylistsUtil {
return id;
}
// public static void clearPlaylist(final Context context, final int playlistId) {
// final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
// context.getContentResolver().delete(uri, null, null);
// }
// public static void deletePlaylists(final Context context, final long playlistId) {
// final Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
// String where = MediaStore.Audio.Playlists._ID + "=?";
// String[] whereVal = {String.valueOf(playlistId)};
// context.getContentResolver().delete(uri, where, whereVal);
// App.bus.post(new DataBaseChangedEvent(DataBaseChangedEvent.PLAYLISTS_CHANGED));
// }
public static void deletePlaylists(@NonNull final Context context, @NonNull final ArrayList<Playlist> playlists) {
final Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
final StringBuilder selection = new StringBuilder();
@ -183,21 +170,6 @@ public class PlaylistsUtil {
return false;
}
// public static int getSongCountForPlaylist(final Context context, final long playlistId) {
// Cursor c = context.getContentResolver().query(
// MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId),
// new String[]{BaseColumns._ID}, MUSIC_ONLY_SELECTION, null, null);
// if (c != null) {
// int count = 0;
// if (c.moveToFirst()) {
// count = c.getCount();
// }
// c.close();
// return count;
// }
// return 0;
// }
public static boolean moveItem(@NonNull final Context context, int playlistId, int from, int to) {
return MediaStore.Audio.Playlists.Members.moveItem(context.getContentResolver(),
playlistId, from, to);

View file

@ -8,11 +8,12 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.kabouzeid.gramophone.R;
import com.kabouzeid.gramophone.helper.SortOrder;
import java.util.HashSet;
import java.util.Set;
public final class PreferenceUtils {
public final class PreferenceUtil {
public static final int DEFAULT_PAGE = 1;
public static final String GENERAL_THEME = "general_theme";
@ -49,20 +50,20 @@ public final class PreferenceUtils {
public static final String NEXT_SLEEP_TIMER_ELAPSED_REALTIME = "next_sleep_timer_elapsed_real_time";
public static final String IGNORE_MEDIA_STORE_ARTWORK = "ignore_media_store_artwork";
private static PreferenceUtils sInstance;
private static PreferenceUtil sInstance;
@NonNull
private final Context mContext;
private final SharedPreferences mPreferences;
public PreferenceUtils(@NonNull final Context context) {
public PreferenceUtil(@NonNull final Context context) {
mContext = context;
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public static PreferenceUtils getInstance(@NonNull final Context context) {
public static PreferenceUtil getInstance(@NonNull final Context context) {
if (sInstance == null) {
sInstance = new PreferenceUtils(context.getApplicationContext());
sInstance = new PreferenceUtil(context.getApplicationContext());
}
return sInstance;
}
@ -83,7 +84,7 @@ public final class PreferenceUtils {
}
public int getThemeColorPrimaryDarker() {
return Util.shiftColorDown(getThemeColorPrimary());
return ColorUtil.shiftColorDown(getThemeColorPrimary());
}
@SuppressLint("CommitPrefEdits")

View file

@ -1,160 +0,0 @@
/*
* Copyright (C) 2012 Andrew Neal 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.
*/
package com.kabouzeid.gramophone.util;
import android.provider.MediaStore;
/**
* Holds all of the sort orders for each list type.
*
* @author Andrew Neal (andrewdneal@gmail.com)
*/
public final class SortOrder {
/**
* This class is never instantiated
*/
public SortOrder() {
}
/**
* Artist sort order entries.
*/
public interface ArtistSortOrder {
/* Artist sort order A-Z */
String ARTIST_A_Z = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER;
/* Artist sort order Z-A */
String ARTIST_Z_A = ARTIST_A_Z + " DESC";
/* Artist sort order number of songs */
String ARTIST_NUMBER_OF_SONGS = MediaStore.Audio.Artists.NUMBER_OF_TRACKS
+ " DESC";
/* Artist sort order number of albums */
String ARTIST_NUMBER_OF_ALBUMS = MediaStore.Audio.Artists.NUMBER_OF_ALBUMS
+ " DESC";
}
/**
* Album sort order entries.
*/
public interface AlbumSortOrder {
/* Album sort order A-Z */
String ALBUM_A_Z = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER;
/* Album sort order Z-A */
String ALBUM_Z_A = ALBUM_A_Z + " DESC";
/* Album sort order songs */
String ALBUM_NUMBER_OF_SONGS = MediaStore.Audio.Albums.NUMBER_OF_SONGS
+ " DESC";
/* Album sort order artist */
String ALBUM_ARTIST = MediaStore.Audio.Albums.ARTIST;
/* Album sort order year */
String ALBUM_YEAR = MediaStore.Audio.Albums.FIRST_YEAR + " DESC";
}
/**
* Song sort order entries.
*/
public interface SongSortOrder {
/* Song sort order A-Z */
String SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
/* Song sort order Z-A */
String SONG_Z_A = SONG_A_Z + " DESC";
/* Song sort order artist */
String SONG_ARTIST = MediaStore.Audio.Media.ARTIST;
/* Song sort order album */
String SONG_ALBUM = MediaStore.Audio.Media.ALBUM;
/* Song sort order year */
String SONG_YEAR = MediaStore.Audio.Media.YEAR + " DESC";
/* Song sort order duration */
String SONG_DURATION = MediaStore.Audio.Media.DURATION + " DESC";
/* Song sort order date */
String SONG_DATE = MediaStore.Audio.Media.DATE_ADDED + " DESC";
}
/**
* Album song sort order entries.
*/
public interface AlbumSongSortOrder {
/* Album song sort order A-Z */
String SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
/* Album song sort order Z-A */
String SONG_Z_A = SONG_A_Z + " DESC";
/* Album song sort order track list */
String SONG_TRACK_LIST = MediaStore.Audio.Media.TRACK + ", "
+ MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
/* Album song sort order duration */
String SONG_DURATION = SongSortOrder.SONG_DURATION;
}
/**
* Artist song sort order entries.
*/
public interface ArtistSongSortOrder {
/* Artist song sort order A-Z */
String SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
/* Artist song sort order Z-A */
String SONG_Z_A = SONG_A_Z + " DESC";
/* Artist song sort order album */
String SONG_ALBUM = MediaStore.Audio.Media.ALBUM;
/* Artist song sort order year */
String SONG_YEAR = MediaStore.Audio.Media.YEAR + " DESC";
/* Artist song sort order duration */
String SONG_DURATION = MediaStore.Audio.Media.DURATION + " DESC";
/* Artist song sort order date */
String SONG_DATE = MediaStore.Audio.Media.DATE_ADDED + " DESC";
}
/**
* Artist album sort order entries.
*/
public interface ArtistAlbumSortOrder {
/* Artist album sort order A-Z */
String ALBUM_A_Z = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER;
/* Artist album sort order Z-A */
String ALBUM_Z_A = ALBUM_A_Z + " DESC";
/* Artist album sort order songs */
String ALBUM_NUMBER_OF_SONGS = MediaStore.Audio.Artists.Albums.NUMBER_OF_SONGS
+ " DESC";
/* Artist album sort order year */
String ALBUM_YEAR = MediaStore.Audio.Artists.Albums.FIRST_YEAR
+ " DESC";
/* Artist album sort order year */
String ALBUM_YEAR_ASC = MediaStore.Audio.Artists.Albums.FIRST_YEAR
+ " ASC";
}
}

View file

@ -3,22 +3,18 @@ package com.kabouzeid.gramophone.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
@ -31,27 +27,6 @@ import com.kabouzeid.gramophone.R;
*/
public class Util {
// public static int resolveDrawable(Context context, int drawable) {
// TypedArray a = context.obtainStyledAttributes(new int[]{drawable});
// int resId = a.getResourceId(0, 0);
// a.recycle();
// return resId;
// }
public static int resolveColor(@NonNull Context context, @AttrRes int colorAttr) {
TypedArray a = context.obtainStyledAttributes(new int[]{colorAttr});
int resId = a.getColor(0, 0);
a.recycle();
return resId;
}
// public static boolean isWindowTranslucent(Context context) {
// TypedArray a = context.obtainStyledAttributes(new int[]{android.R.attr.windowTranslucentStatus});
// boolean result = a.getBoolean(0, false);
// a.recycle();
// return result;
// }
public static int getActionBarSize(@NonNull Context context) {
TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[]{R.attr.actionBarSize};
@ -62,41 +37,13 @@ public class Util {
return actionBarSize;
}
public static int getStatusBarHeight(@NonNull Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
public static Point getScreenSize(@NonNull Context c) {
Display display = ((WindowManager) c.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
public static int getNavigationBarHeight(@NonNull Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
// @TargetApi(19)
// public static void setNavBarTranslucent(Window window, boolean translucent) {
// if (translucent) {
// window.setFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// return;
// }
//
// final WindowManager.LayoutParams attrs = window
// .getAttributes();
// attrs.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// window.setAttributes(attrs);
// window.clearFlags(
// WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// }
@TargetApi(19)
public static void setStatusBarTranslucent(@NonNull Window window, boolean translucent) {
if (translucent) {
@ -120,31 +67,6 @@ public class Util {
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
@NonNull
public static String getFileSizeString(long sizeInBytes) {
long fileSizeInKB = sizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
return fileSizeInMB + " MB";
}
// public static String getFilePathFromContentProviderUri(Context context, Uri uri) {
// String path = "";
// String[] projection = {MediaStore.MediaColumns.DATA};
// Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
// if (cursor == null) return null;
// int column_index = cursor.getColumnIndexOrThrow(projection[0]);
// if (cursor.moveToFirst()) {
// path = cursor.getString(column_index);
// }
// cursor.close();
// return path;
// }
//
// private static Bitmap getScaledBitmap(final Bitmap bitmap) {
// int albumArtSize = 600;
// return Bitmap.createScaledBitmap(bitmap, albumArtSize, albumArtSize, false);
// }
public static void hideSoftKeyboard(@Nullable Activity activity) {
if (activity != null) {
View currentFocus = activity.getCurrentFocus();
@ -155,14 +77,6 @@ public class Util {
}
}
public static boolean isAtLeastLollipop() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
public static boolean isAtLeastKitKat() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
}
public static boolean isTablet(@NonNull final Context context) {
return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
}
@ -179,35 +93,6 @@ public class Util {
return drawable;
}
public static int getOpaqueColor(@ColorInt int color) {
return color | 0xFF000000;
}
public static int getColorWithAlpha(float alpha, int baseColor) {
int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24;
int rgb = 0x00ffffff & baseColor;
return a + rgb;
}
@SuppressWarnings("ResourceType")
public static int shiftColorDown(int color) {
int alpha = Color.alpha(color);
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.9f; // value component
return (alpha << 24) + (0x00ffffff & Color.HSVToColor(hsv));
}
@NonNull
public static ColorStateList getEmptyColorStateList(int color) {
return new ColorStateList(
new int[][]{
new int[]{}
},
new int[]{color}
);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static boolean isRTL(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
@ -215,18 +100,4 @@ public class Util {
return config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
} else return false;
}
public static Bitmap getResizedBitmap(@NonNull Bitmap bm, int newHeight, int newWidth, boolean recycleOld) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
if (recycleOld && resizedBitmap != bm) {
bm.recycle();
}
return resizedBitmap;
}
}

View file

@ -8,11 +8,9 @@ import android.support.annotation.Nullable;
import android.support.v7.internal.view.menu.ListMenuItemView;
import android.support.v7.internal.view.menu.MenuPopupHelper;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.PathInterpolator;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
@ -28,50 +26,6 @@ import java.lang.reflect.Field;
public class ViewUtil {
public final static int DEFAULT_COLOR_ANIMATION_DURATION = 500;
public static void disableViews(@NonNull ViewGroup layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
if (child instanceof ViewGroup) {
disableViews((ViewGroup) child);
} else {
child.setEnabled(false);
}
}
}
public static void enableViews(@NonNull ViewGroup layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
if (child instanceof ViewGroup) {
enableViews((ViewGroup) child);
} else {
child.setEnabled(true);
}
}
}
public static void setListViewHeightBasedOnChildren(@NonNull ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
public static void animateViewColor(final View v, final int startColor, final int endColor) {
animateViewColor(v, startColor, endColor, DEFAULT_COLOR_ANIMATION_DURATION);
}
@ -124,18 +78,6 @@ public class ViewUtil {
});
}
// public static void animateTextViewMaxLines(TextView text, int maxLines) {
// try {
// ObjectAnimator animation = ObjectAnimator.ofInt(text, "maxLines", maxLines);
// animation.setInterpolator(new AccelerateInterpolator());
// animation.setDuration(200);
// animation.start();
// } catch (Exception e) {
// // Some devices crash at runtime when using the ObjectAnimator
// text.setMaxLines(maxLines);
// }
// }
public static void setCheckBoxTintForMenu(@Nullable MenuPopupHelper menuPopupHelper) {
if (menuPopupHelper != null) {
final ListView listView = menuPopupHelper.getPopup().getListView();