Just code rearrangement

This commit is contained in:
Karim Abou Zeid 2015-01-27 14:42:12 +01:00
commit 60a3070dfe
58 changed files with 1468 additions and 1500 deletions

View file

@ -48,23 +48,10 @@ import android.widget.TextView;
* providing the layout ID of your custom layout.
*/
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {@link #setCustomTabColorizer(com.google.samples.apps.iosched.ui.widget.SlidingTabLayout.TabColorizer)}.
*/
public interface TabColorizer {
/**
* @return return the color of the indicator used when {@code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private final SlidingTabStrip mTabStrip;
private int mTitleOffset;
private int mTabViewLayoutId;
@ -75,8 +62,6 @@ public class SlidingTabLayout extends HorizontalScrollView {
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
@ -158,30 +143,6 @@ public class SlidingTabLayout extends HorizontalScrollView {
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {@link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final OnClickListener tabClickListener = new TabClickListener();
@ -225,6 +186,30 @@ public class SlidingTabLayout extends HorizontalScrollView {
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {@link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
@ -257,6 +242,19 @@ public class SlidingTabLayout extends HorizontalScrollView {
}
}
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {@link #setCustomTabColorizer(com.google.samples.apps.iosched.ui.widget.SlidingTabLayout.TabColorizer)}.
*/
public interface TabColorizer {
/**
* @return return the color of the indicator used when {@code position} is selected.
*/
int getIndicatorColor(int position);
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
@ -281,15 +279,6 @@ public class SlidingTabLayout extends HorizontalScrollView {
}
}
@Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
@ -304,6 +293,15 @@ public class SlidingTabLayout extends HorizontalScrollView {
}
}
@Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
}
private class TabClickListener implements OnClickListener {

View file

@ -40,12 +40,10 @@ class SlidingTabStrip extends LinearLayout {
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
private final SimpleTabColorizer mDefaultTabColorizer;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
@ -75,6 +73,13 @@ class SlidingTabStrip extends LinearLayout {
mSelectedIndicatorPaint = new Paint();
}
/**
* Set the alpha value of the {@code color} to be the given {@code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
@ -132,13 +137,6 @@ class SlidingTabStrip extends LinearLayout {
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {@code color} to be the given {@code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {@code color1} and {@code color2} using the given ratio.
*

View file

@ -43,13 +43,6 @@ public class App extends Application {
return playerRemote;
}
public SharedPreferences getDefaultSharedPreferences() {
if (defaultSharedPreferences == null) {
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
return defaultSharedPreferences;
}
public int getAppTheme() {
if (appTheme == 0) {
appTheme = getDefaultSharedPreferences().getInt(AppKeys.SP_THEME, R.style.Theme_MaterialMusic);
@ -57,6 +50,13 @@ public class App extends Application {
return appTheme;
}
public SharedPreferences getDefaultSharedPreferences() {
if (defaultSharedPreferences == null) {
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
return defaultSharedPreferences;
}
public void setAppTheme(int appTheme) {
this.appTheme = appTheme;
defaultSharedPreferences.edit().putInt(AppKeys.SP_THEME, appTheme);
@ -70,15 +70,15 @@ public class App extends Application {
return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
public void addToRequestQueue(Request request) {
request.setTag(TAG);
getRequestQueue().add(request);
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(this);
}
return requestQueue;
}
public void addToRequestQueue(Request request) {
request.setTag(TAG);
getRequestQueue().add(request);
}
}

View file

@ -36,23 +36,6 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
private MusicService musicService;
private Intent musicServiceIntent;
private boolean musicBound = false;
public MusicPlayerRemote(Context context) {
app = (App) context.getApplicationContext();
playingQueue = new ArrayList<>();
restoredOriginalQueue = new ArrayList<>();
onMusicRemoteEventListeners = new ArrayList<>();
startAndBindService();
}
private void startAndBindService() {
if (musicServiceIntent == null) {
musicServiceIntent = new Intent(app, MusicService.class);
app.bindService(musicServiceIntent, musicConnection, Context.BIND_AUTO_CREATE);
app.startService(musicServiceIntent);
}
}
private ServiceConnection musicConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
@ -71,6 +54,22 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
}
};
public MusicPlayerRemote(Context context) {
app = (App) context.getApplicationContext();
playingQueue = new ArrayList<>();
restoredOriginalQueue = new ArrayList<>();
onMusicRemoteEventListeners = new ArrayList<>();
startAndBindService();
}
private void startAndBindService() {
if (musicServiceIntent == null) {
musicServiceIntent = new Intent(app, MusicService.class);
app.bindService(musicServiceIntent, musicConnection, Context.BIND_AUTO_CREATE);
app.startService(musicServiceIntent);
}
}
public boolean playSongAt(final int position) {
if (musicBound) {
musicService.playSongAt(position);
@ -126,6 +125,21 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
}
}
public void openQueue(final List<Song> playingQueue, final int startPosition, final boolean startPlaying) {
this.playingQueue = playingQueue;
if (musicBound) {
musicService.openQueue(this.playingQueue, startPosition, startPlaying);
}
}
public Song getCurrentSong() {
final int position = getPosition();
if (position != -1) {
return getPlayingQueue().get(position);
}
return new Song();
}
public int getPosition() {
if (musicBound) {
position = musicService.getPosition();
@ -140,13 +154,6 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
}
}
public void openQueue(final List<Song> playingQueue, final int startPosition, final boolean startPlaying) {
this.playingQueue = playingQueue;
if (musicBound) {
musicService.openQueue(this.playingQueue, startPosition, startPlaying);
}
}
public List<Song> getPlayingQueue() {
if (musicBound) {
playingQueue = musicService.getPlayingQueue();
@ -154,14 +161,6 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
return playingQueue;
}
public Song getCurrentSong() {
final int position = getPosition();
if (position != -1) {
return getPlayingQueue().get(position);
}
return new Song();
}
public int getSongProgressMillis() {
if (isPlayerPrepared()) {
return musicService.getSongProgressMillis();
@ -169,6 +168,13 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
return -1;
}
public boolean isPlayerPrepared() {
if (musicBound) {
return musicService.isPlayerPrepared();
}
return false;
}
public int getSongDurationMillis() {
if (isPlayerPrepared()) {
return musicService.getSongDurationMillis();
@ -186,13 +192,6 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
}
}
public boolean isPlayerPrepared() {
if (musicBound) {
return musicService.isPlayerPrepared();
}
return false;
}
public int getRepeatMode() {
if (musicBound) {
return musicService.getRepeatMode();
@ -223,15 +222,15 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
return false;
}
public void moveSong(int from, int to){
public void moveSong(int from, int to) {
final int currentPosition = getPosition();
Song songToMove = getPlayingQueue().remove(from);
getPlayingQueue().add(to, songToMove);
if(from > currentPosition && to <= currentPosition){
if (from > currentPosition && to <= currentPosition) {
setPosition(getPosition() + 1);
} else if(from < currentPosition && to >= currentPosition){
} else if (from < currentPosition && to >= currentPosition) {
setPosition(getPosition() - 1);
} else if(from == currentPosition){
} else if (from == currentPosition) {
setPosition(to);
}
}
@ -241,6 +240,13 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
notifyOnMusicRemoteEventListeners(event.getAction());
}
private void notifyOnMusicRemoteEventListeners(int event) {
MusicRemoteEvent musicRemoteEvent = new MusicRemoteEvent(event);
for (OnMusicRemoteEventListener listener : onMusicRemoteEventListeners) {
listener.onMusicRemoteEvent(musicRemoteEvent);
}
}
public void addOnMusicRemoteEventListener(OnMusicRemoteEventListener onMusicRemoteEventListener) {
onMusicRemoteEventListeners.add(onMusicRemoteEventListener);
}
@ -253,13 +259,6 @@ public class MusicPlayerRemote implements OnMusicRemoteEventListener {
onMusicRemoteEventListeners.clear();
}
private void notifyOnMusicRemoteEventListeners(int event) {
MusicRemoteEvent musicRemoteEvent = new MusicRemoteEvent(event);
for (OnMusicRemoteEventListener listener : onMusicRemoteEventListeners) {
listener.onMusicRemoteEvent(musicRemoteEvent);
}
}
@SuppressWarnings("unchecked")
public void restorePreviousState() {
try {

View file

@ -64,26 +64,6 @@ public class NotificationHelper {
service.startForeground(NOTIFICATION_ID, notification);
}
public void killNotification() {
service.stopForeground(true);
notification = null;
}
public void updatePlayState(final boolean isPlaying) {
if (notification == null || notificationManager == null) {
return;
}
if (notificationLayout != null) {
notificationLayout.setImageViewResource(R.id.button_toggle_play_pause,
isPlaying ? R.drawable.ic_pause_white_48dp : R.drawable.ic_play_arrow_white_48dp);
}
if (notificationLayoutExpanded != null) {
notificationLayoutExpanded.setImageViewResource(R.id.button_toggle_play_pause,
isPlaying ? R.drawable.ic_pause_white_48dp : R.drawable.ic_play_arrow_white_48dp);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
private PendingIntent getOpenMusicControllerPendingIntent() {
Intent result = new Intent(service, MusicControllerActivity.class);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(service);
@ -160,13 +140,6 @@ public class NotificationHelper {
notificationLayout.setTextViewText(R.id.song_artist, song.title);
}
private void setUpExpandedLayout(Song song) {
loadAlbumArt(notificationLayoutExpanded, MusicUtil.getAlbumArtUri(song.albumId).toString());
notificationLayoutExpanded.setTextViewText(R.id.song_title, song.title);
notificationLayoutExpanded.setTextViewText(R.id.song_artist, song.artistName);
notificationLayoutExpanded.setTextViewText(R.id.album_title, song.albumName);
}
private static void loadAlbumArt(RemoteViews notificationView, String albumArtUri) {
Bitmap albumArtBitmap = ImageLoader.getInstance().loadImageSync(albumArtUri);
if (albumArtBitmap == null) {
@ -175,4 +148,31 @@ public class NotificationHelper {
notificationView.setImageViewBitmap(R.id.album_art, albumArtBitmap);
}
}
private void setUpExpandedLayout(Song song) {
loadAlbumArt(notificationLayoutExpanded, MusicUtil.getAlbumArtUri(song.albumId).toString());
notificationLayoutExpanded.setTextViewText(R.id.song_title, song.title);
notificationLayoutExpanded.setTextViewText(R.id.song_artist, song.artistName);
notificationLayoutExpanded.setTextViewText(R.id.album_title, song.albumName);
}
public void killNotification() {
service.stopForeground(true);
notification = null;
}
public void updatePlayState(final boolean isPlaying) {
if (notification == null || notificationManager == null) {
return;
}
if (notificationLayout != null) {
notificationLayout.setImageViewResource(R.id.button_toggle_play_pause,
isPlaying ? R.drawable.ic_pause_white_48dp : R.drawable.ic_play_arrow_white_48dp);
}
if (notificationLayoutExpanded != null) {
notificationLayoutExpanded.setImageViewResource(R.id.button_toggle_play_pause,
isPlaying ? R.drawable.ic_pause_white_48dp : R.drawable.ic_play_arrow_white_48dp);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
}

View file

@ -6,7 +6,6 @@ import com.afollestad.materialdialogs.MaterialDialog;
import com.kabouzeid.materialmusic.App;
import com.kabouzeid.materialmusic.R;
import com.kabouzeid.materialmusic.adapter.PlayingQueueAdapter;
import com.kabouzeid.materialmusic.model.Song;
import com.mobeta.android.dslv.DragSortListView;
/**

View file

@ -61,6 +61,15 @@ public class LastFMAlbumInfoUtil {
}
}
public static JSONArray getAlbumImageArrayFromJSON(JSONObject rootJSON) {
try {
return rootJSON.getJSONObject("album").getJSONArray("image");
} catch (JSONException e) {
//Log.e(TAG, "Error while getting album image array from JSON parameter!", e);
return null;
}
}
public static String getAlbumImageUrlFromJSON(JSONObject rootJSON) {
try {
JSONArray images = getAlbumImageArrayFromJSON(rootJSON);
@ -71,15 +80,6 @@ public class LastFMAlbumInfoUtil {
}
}
public static JSONArray getAlbumImageArrayFromJSON(JSONObject rootJSON) {
try {
return rootJSON.getJSONObject("album").getJSONArray("image");
} catch (JSONException e) {
//Log.e(TAG, "Error while getting album image array from JSON parameter!", e);
return null;
}
}
public static void saveAlbumJSONDataToCacheAndDisk(Context context, String album, String artist, JSONObject jsonObject) {
Log.i(TAG, "Saving new JSON album data for " + album + "...");
AlbumJSONStore.getInstance(context).addAlbumJSON(album + artist, jsonObject.toString());

View file

@ -60,6 +60,15 @@ public class LastFMArtistInfoUtil {
}
}
public static JSONArray getArtistImageArrayFromJSON(JSONObject rootJSON) {
try {
return rootJSON.getJSONObject("artist").getJSONArray("image");
} catch (JSONException e) {
//Log.e(TAG, "Error while getting artist image array from JSON parameter!", e);
return null;
}
}
public static String getArtistImageUrlFromJSON(JSONObject rootJSON) {
try {
JSONArray images = getArtistImageArrayFromJSON(rootJSON);
@ -70,15 +79,6 @@ public class LastFMArtistInfoUtil {
}
}
public static JSONArray getArtistImageArrayFromJSON(JSONObject rootJSON) {
try {
return rootJSON.getJSONObject("artist").getJSONArray("image");
} catch (JSONException e) {
//Log.e(TAG, "Error while getting artist image array from JSON parameter!", e);
return null;
}
}
public static String getArtistBiographyFromJSON(JSONObject rootJSON) {
try {
return rootJSON.getJSONObject("artist").getJSONObject("bio").getString("content");

View file

@ -38,6 +38,24 @@ public class AlbumLoader {
return albums;
}
private static Cursor makeAlbumCursor(final Context context) {
return context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AlbumColumns.ALBUM,
/* 2 */
MediaStore.Audio.AlbumColumns.ARTIST,
/* 3 */
MediaStore.Audio.Media.ARTIST_ID,
/* 4 */
MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,
/* 5 */
MediaStore.Audio.AlbumColumns.FIRST_YEAR
}, null, null, null);
}
public static Album getAlbum(Context context, int albumId) {
Cursor cursor = makeAlbumCursor(context);
Album album = new Album();
@ -85,22 +103,4 @@ public class AlbumLoader {
}
return albums;
}
private static Cursor makeAlbumCursor(final Context context) {
return context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AlbumColumns.ALBUM,
/* 2 */
MediaStore.Audio.AlbumColumns.ARTIST,
/* 3 */
MediaStore.Audio.Media.ARTIST_ID,
/* 4 */
MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,
/* 5 */
MediaStore.Audio.AlbumColumns.FIRST_YEAR
}, null, null, null);
}
}

View file

@ -36,6 +36,20 @@ public class ArtistLoader {
return artists;
}
public static final Cursor makeArtistCursor(final Context context) {
return context.getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.ArtistColumns.ARTIST,
/* 2 */
MediaStore.Audio.ArtistColumns.NUMBER_OF_ALBUMS,
/* 3 */
MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS
}, null, null, null);
}
public static Artist getArtist(Context context, int artistId) {
Cursor cursor = makeArtistCursor(context);
Artist artist = new Artist();
@ -80,18 +94,4 @@ public class ArtistLoader {
}
return artists;
}
public static final Cursor makeArtistCursor(final Context context) {
return context.getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.ArtistColumns.ARTIST,
/* 2 */
MediaStore.Audio.ArtistColumns.NUMBER_OF_ALBUMS,
/* 3 */
MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS
}, null, null, null);
}
}

View file

@ -32,6 +32,16 @@ public class SongFileLoader {
return songFiles;
}
public static final Cursor makeSongFileCursor(final Context context) {
return context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AudioColumns.DATA,
}, null, null, null);
}
public static String getSongFile(Context context, int queryId) {
Cursor cursor = makeSongFileCursor(context);
String filePath = "";
@ -49,14 +59,4 @@ public class SongFileLoader {
}
return filePath;
}
public static final Cursor makeSongFileCursor(final Context context) {
return context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AudioColumns.DATA,
}, null, null, null);
}
}

View file

@ -39,6 +39,30 @@ public class SongLoader {
return songs;
}
public static final Cursor makeAlbumSongCursor(final Context context) {
final StringBuilder selection = new StringBuilder();
selection.append(MediaStore.Audio.AudioColumns.IS_MUSIC + "=1");
return context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AudioColumns.TITLE,
/* 2 */
MediaStore.Audio.AudioColumns.ARTIST,
/* 3 */
MediaStore.Audio.AudioColumns.ALBUM,
/* 4 */
MediaStore.Audio.AudioColumns.DURATION,
/* 5 */
MediaStore.Audio.AudioColumns.TRACK,
/* 6 */
MediaStore.Audio.AudioColumns.ARTIST_ID,
/* 7 */
MediaStore.Audio.AudioColumns.ALBUM_ID
}, selection.toString(), null, null);
}
public static List<Song> getSongs(Context context, String query) {
Cursor cursor = makeAlbumSongCursor(context);
List<Song> songs = new ArrayList<>();
@ -90,28 +114,4 @@ public class SongLoader {
}
return song;
}
public static final Cursor makeAlbumSongCursor(final Context context) {
final StringBuilder selection = new StringBuilder();
selection.append(MediaStore.Audio.AudioColumns.IS_MUSIC + "=1");
return context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AudioColumns.TITLE,
/* 2 */
MediaStore.Audio.AudioColumns.ARTIST,
/* 3 */
MediaStore.Audio.AudioColumns.ALBUM,
/* 4 */
MediaStore.Audio.AudioColumns.DURATION,
/* 5 */
MediaStore.Audio.AudioColumns.TRACK,
/* 6 */
MediaStore.Audio.AudioColumns.ARTIST_ID,
/* 7 */
MediaStore.Audio.AudioColumns.ALBUM_ID
}, selection.toString(), null, null);
}
}

View file

@ -8,33 +8,33 @@ import android.database.sqlite.SQLiteOpenHelper;
public class AlbumJSONStore extends SQLiteOpenHelper {
private static final int VERSION = 1;
public static final String DATABASE_NAME = "albumJSONLastFM.db";
private static final int VERSION = 1;
private static AlbumJSONStore sInstance = null;
public AlbumJSONStore(final Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(final SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + AlbumJSONColumns.NAME +
" (" + AlbumJSONColumns.ALBUMANDARTIST_NAME + " TEXT NOT NULL," +
AlbumJSONColumns.JSON + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + AlbumJSONColumns.NAME);
onCreate(db);
}
public static synchronized AlbumJSONStore getInstance(final Context context) {
if (sInstance == null) {
sInstance = new AlbumJSONStore(context.getApplicationContext());
}
return sInstance;
} @Override
public void onCreate(final SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + AlbumJSONColumns.NAME +
" (" + AlbumJSONColumns.ALBUMANDARTIST_NAME + " TEXT NOT NULL," +
AlbumJSONColumns.JSON + " TEXT NOT NULL);"
);
}
public static void deleteDatabase(final Context context) {
context.deleteDatabase(DATABASE_NAME);
} @Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + AlbumJSONColumns.NAME);
onCreate(db);
}
public void addAlbumJSON(final String albumAndArtistName, final String JSON) {
@ -82,10 +82,6 @@ public class AlbumJSONStore extends SQLiteOpenHelper {
return null;
}
public static void deleteDatabase(final Context context) {
context.deleteDatabase(DATABASE_NAME);
}
public void removeItem(final String albumAndArtistName) {
final SQLiteDatabase database = getReadableDatabase();
database.delete(AlbumJSONColumns.NAME, AlbumJSONColumns.ALBUMANDARTIST_NAME + " = ?", new String[]{
@ -100,4 +96,8 @@ public class AlbumJSONStore extends SQLiteOpenHelper {
public static final String JSON = "JSON";
}
}

View file

@ -8,33 +8,33 @@ import android.database.sqlite.SQLiteOpenHelper;
public class ArtistJSONStore extends SQLiteOpenHelper {
private static final int VERSION = 1;
public static final String DATABASE_NAME = "artistJSONLastFM.db";
private static final int VERSION = 1;
private static ArtistJSONStore sInstance = null;
public ArtistJSONStore(final Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(final SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + ArtistJSONColumns.NAME +
" (" + ArtistJSONColumns.ARTIST_NAME + " TEXT NOT NULL," +
ArtistJSONColumns.JSON + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ArtistJSONColumns.NAME);
onCreate(db);
}
public static synchronized ArtistJSONStore getInstance(final Context context) {
if (sInstance == null) {
sInstance = new ArtistJSONStore(context.getApplicationContext());
}
return sInstance;
} @Override
public void onCreate(final SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + ArtistJSONColumns.NAME +
" (" + ArtistJSONColumns.ARTIST_NAME + " TEXT NOT NULL," +
ArtistJSONColumns.JSON + " TEXT NOT NULL);"
);
}
public static void deleteDatabase(final Context context) {
context.deleteDatabase(DATABASE_NAME);
} @Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ArtistJSONColumns.NAME);
onCreate(db);
}
public void addArtistJSON(final String artistName, final String JSON) {
@ -82,10 +82,6 @@ public class ArtistJSONStore extends SQLiteOpenHelper {
return null;
}
public static void deleteDatabase(final Context context) {
context.deleteDatabase(DATABASE_NAME);
}
public void removeItem(final String artistName) {
final SQLiteDatabase database = getReadableDatabase();
database.delete(ArtistJSONColumns.NAME, ArtistJSONColumns.ARTIST_NAME + " = ?", new String[]{
@ -100,4 +96,8 @@ public class ArtistJSONStore extends SQLiteOpenHelper {
public static final String JSON = "JSON";
}
}

View file

@ -37,8 +37,6 @@ import java.util.ArrayList;
import java.util.List;
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener, AudioManager.OnAudioFocusChangeListener {
private static final String TAG = MusicService.class.getSimpleName();
public static final String ACTION_TOGGLE_PLAYBACK = "com.kabouzeid.materialmusic.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.kabouzeid.materialmusic.action.PLAY";
public static final String ACTION_PAUSE = "com.kabouzeid.materialmusic.action.PAUSE";
@ -46,32 +44,13 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
public static final String ACTION_SKIP = "com.kabouzeid.materialmusic.action.SKIP";
public static final String ACTION_REWIND = "com.kabouzeid.materialmusic.action.REWIND";
public static final String ACTION_QUIT = "com.kabouzeid.materialmusic.action.QUIT";
public static final int SHUFFLE_MODE_NONE = 0;
public static final int SHUFFLE_MODE_SHUFFLE = 1;
public static final int REPEAT_MODE_NONE = 0;
public static final int REPEAT_MODE_ALL = 1;
public static final int REPEAT_MODE_THIS = 2;
private MediaPlayer player;
private List<Song> playingQueue;
private List<Song> originalPlayingQueue;
private List<OnMusicRemoteEventListener> onMusicRemoteEventListeners;
private int currentSongId = -1;
private int position = -1;
private int shuffleMode;
private int repeatMode;
private static final String TAG = MusicService.class.getSimpleName();
private final IBinder musicBind = new MusicBinder();
private boolean isPlayerPrepared;
private boolean wasPlayingBeforeFocusLoss;
private boolean thingsRegistered;
private boolean saveQueuesAgain;
private boolean isSavingQueues;
private NotificationHelper notificationHelper;
private AudioManager audioManager;
private RemoteControlClient remoteControlClient;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@ -80,13 +59,22 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
};
private AudioManager getAudioManager() {
if (audioManager == null) {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
return audioManager;
}
private MediaPlayer player;
private List<Song> playingQueue;
private List<Song> originalPlayingQueue;
private List<OnMusicRemoteEventListener> onMusicRemoteEventListeners;
private int currentSongId = -1;
private int position = -1;
private int shuffleMode;
private int repeatMode;
private boolean isPlayerPrepared;
private boolean wasPlayingBeforeFocusLoss;
private boolean thingsRegistered;
private boolean saveQueuesAgain;
private boolean isSavingQueues;
private NotificationHelper notificationHelper;
private AudioManager audioManager;
private RemoteControlClient remoteControlClient;
public MusicService() {
}
@ -106,11 +94,22 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
registerEverything();
}
private boolean requestFocus() {
int result = getAudioManager().requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
private void registerEverything() {
if (!thingsRegistered) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(receiver, intentFilter);
getAudioManager().registerMediaButtonEventReceiver(new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class));
initRemoteControlClient();
thingsRegistered = true;
}
}
return (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
private AudioManager getAudioManager() {
if (audioManager == null) {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
return audioManager;
}
private void initRemoteControlClient() {
@ -126,39 +125,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
getAudioManager().registerRemoteControlClient(remoteControlClient);
}
private void registerEverything() {
if (!thingsRegistered) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(receiver, intentFilter);
getAudioManager().registerMediaButtonEventReceiver(new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class));
initRemoteControlClient();
thingsRegistered = true;
}
}
private void unregisterEverything() {
if (thingsRegistered) {
unregisterReceiver(receiver);
getAudioManager().unregisterRemoteControlClient(remoteControlClient);
getAudioManager().unregisterMediaButtonEventReceiver(new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class));
getAudioManager().abandonAudioFocus(this);
thingsRegistered = false;
}
}
private void updateRemoteControlClient() {
Song song = getPlayingQueue().get(getPosition());
Bitmap loadedImage = ImageLoader.getInstance().loadImageSync(MusicUtil.getAlbumArtUri(song.albumId).toString());
remoteControlClient
.editMetadata(false)
.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, song.artistName)
.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, song.title)
.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, song.duration)
.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, loadedImage)
.apply();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
setUpMediaPlayerIfNeeded();
@ -196,6 +162,12 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
unregisterEverything();
killEverythingAndReleaseResources();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
@ -209,6 +181,77 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
return false;
}
private void unregisterEverything() {
if (thingsRegistered) {
unregisterReceiver(receiver);
getAudioManager().unregisterRemoteControlClient(remoteControlClient);
getAudioManager().unregisterMediaButtonEventReceiver(new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class));
getAudioManager().abandonAudioFocus(this);
thingsRegistered = false;
}
}
private void killEverythingAndReleaseResources() {
stopPlaying();
notificationHelper.killNotification();
savePosition();
saveQueues();
stopSelf();
}
public void stopPlaying() {
isPlayerPrepared = false;
player.stop();
notificationHelper.updatePlayState(isPlaying());
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
player.release();
player = null;
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.STOP);
}
public boolean isPlaying() {
return player != null && player.isPlaying();
}
private void notifyOnMusicRemoteEventListeners(int event) {
MusicRemoteEvent musicRemoteEvent = new MusicRemoteEvent(event);
for (OnMusicRemoteEventListener listener : onMusicRemoteEventListeners) {
listener.onMusicRemoteEvent(musicRemoteEvent);
}
}
public void saveQueues() {
try {
InternalStorageUtil.writeObject(MusicService.this, AppKeys.IS_PLAYING_QUEUE, playingQueue);
InternalStorageUtil.writeObject(MusicService.this, AppKeys.IS_ORIGINAL_PLAYING_QUEUE, originalPlayingQueue);
Log.i(TAG, "saved current queue state");
} catch (IOException e) {
Log.e(TAG, "error while saving music service queue state", e);
}
}
public void savePosition() {
new Thread(new Runnable() {
@Override
public void run() {
try {
InternalStorageUtil.writeObject(MusicService.this, AppKeys.IS_POSITION_IN_QUEUE, getPosition());
Log.i(TAG, "saved current position state");
} catch (IOException e) {
Log.e(TAG, "error while saving music service position state", e);
}
}
}).start();
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
@Override
public void onCompletion(MediaPlayer mp) {
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.SONG_COMPLETED);
@ -222,6 +265,112 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public void playNextSong() {
if (position != -1) {
if (isPlayerPrepared) {
setPosition(getNextPosition());
playSong();
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.NEXT);
}
}
}
public void playSong() {
if (requestFocus()) {
setUpMediaPlayerIfNeeded();
registerEverything();
isPlayerPrepared = false;
player.reset();
Uri trackUri = getCurrentPositionTrackUri();
try {
player.setDataSource(getApplicationContext(), trackUri);
currentSongId = getPlayingQueue().get(getPosition()).id;
updateNotification();
updateRemoteControlClient();
player.prepareAsync();
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
player.reset();
Toast.makeText(getApplicationContext(), getResources().getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show();
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.STOP);
notificationHelper.updatePlayState(false);
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
}
} else {
Toast.makeText(this, getResources().getString(R.string.audio_focus_denied), Toast.LENGTH_SHORT).show();
}
}
private boolean requestFocus() {
int result = getAudioManager().requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
return (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
}
private void updateRemoteControlClient() {
Song song = getPlayingQueue().get(getPosition());
Bitmap loadedImage = ImageLoader.getInstance().loadImageSync(MusicUtil.getAlbumArtUri(song.albumId).toString());
remoteControlClient
.editMetadata(false)
.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, song.artistName)
.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, song.title)
.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, song.duration)
.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, loadedImage)
.apply();
}
private void setUpMediaPlayerIfNeeded() {
if (player == null) {
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}
}
private void updateNotification() {
notificationHelper.buildNotification(playingQueue.get(position), isPlaying());
}
private Uri getCurrentPositionTrackUri() {
return ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, playingQueue.get(position).id);
}
public int getNextPosition() {
int position = 0;
switch (repeatMode) {
case REPEAT_MODE_NONE:
position = getPosition() + 1;
if (isLastTrack()) {
position -= 1;
}
break;
case REPEAT_MODE_ALL:
position = getPosition() + 1;
if (isLastTrack()) {
position = 0;
}
break;
case REPEAT_MODE_THIS:
position = getPosition();
break;
}
return position;
}
private boolean isLastTrack() {
return getPosition() == getPlayingQueue().size() - 1;
}
public List<Song> getPlayingQueue() {
return playingQueue;
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
isPlayerPrepared = false;
@ -240,37 +389,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
savePosition();
}
@Override
public void onDestroy() {
unregisterEverything();
killEverythingAndReleaseResources();
}
private void killEverythingAndReleaseResources() {
stopPlaying();
notificationHelper.killNotification();
savePosition();
saveQueues();
stopSelf();
}
private void setUpMediaPlayerIfNeeded() {
if (player == null) {
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}
}
private void updateNotification() {
notificationHelper.buildNotification(playingQueue.get(position), isPlaying());
}
public void openQueue(final List<Song> playingQueue, final int startPosition, final boolean startPlaying) {
if (playingQueue != null && !playingQueue.isEmpty() && startPosition >= 0 && startPosition < playingQueue.size()) {
originalPlayingQueue = playingQueue;
@ -287,6 +405,29 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public void saveState() {
saveQueuesAsync();
savePosition();
}
public void saveQueuesAsync() {
if (isSavingQueues) {
saveQueuesAgain = true;
} else {
new Thread(new Runnable() {
@Override
public void run() {
isSavingQueues = true;
do {
saveQueuesAgain = false;
saveQueues();
} while (saveQueuesAgain);
isSavingQueues = false;
}
}).start();
}
}
public void restorePreviousState(final List<Song> originalPlayingQueue, final List<Song> playingQueue, int position) {
this.originalPlayingQueue = originalPlayingQueue;
this.playingQueue = playingQueue;
@ -294,18 +435,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
saveState();
}
public List<Song> getPlayingQueue() {
return playingQueue;
}
public void setPosition(int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public long getCurrentSongId() {
return currentSongId;
}
@ -353,12 +482,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
public void playSongAt(final int position) {
if (position < getPlayingQueue().size() && position >= 0) {
setPosition(position);
@ -368,32 +491,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public void playSong() {
if (requestFocus()) {
setUpMediaPlayerIfNeeded();
registerEverything();
isPlayerPrepared = false;
player.reset();
Uri trackUri = getCurrentPositionTrackUri();
try {
player.setDataSource(getApplicationContext(), trackUri);
currentSongId = getPlayingQueue().get(getPosition()).id;
updateNotification();
updateRemoteControlClient();
player.prepareAsync();
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
player.reset();
Toast.makeText(getApplicationContext(), getResources().getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show();
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.STOP);
notificationHelper.updatePlayState(false);
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
}
} else {
Toast.makeText(this, getResources().getString(R.string.audio_focus_denied), Toast.LENGTH_SHORT).show();
}
}
public void pausePlaying() {
if (isPlaying()) {
player.pause();
@ -418,26 +515,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public void stopPlaying() {
isPlayerPrepared = false;
player.stop();
notificationHelper.updatePlayState(isPlaying());
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
player.release();
player = null;
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.STOP);
}
public void playNextSong() {
if (position != -1) {
if (isPlayerPrepared) {
setPosition(getNextPosition());
playSong();
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.NEXT);
}
}
}
public void playPreviousSong() {
if (position != -1) {
setPosition(getPreviousPosition());
@ -456,28 +533,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public int getNextPosition() {
int position = 0;
switch (repeatMode) {
case REPEAT_MODE_NONE:
position = getPosition() + 1;
if (isLastTrack()) {
position -= 1;
}
break;
case REPEAT_MODE_ALL:
position = getPosition() + 1;
if (isLastTrack()) {
position = 0;
}
break;
case REPEAT_MODE_THIS:
position = getPosition();
break;
}
return position;
}
public int getPreviousPosition() {
int position = 0;
switch (repeatMode) {
@ -500,14 +555,6 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
return position;
}
public boolean isPlaying() {
return player != null && player.isPlaying();
}
private Uri getCurrentPositionTrackUri() {
return ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, playingQueue.get(position).id);
}
public int getSongProgressMillis() {
return player.getCurrentPosition();
}
@ -524,66 +571,52 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
return player != null && isPlayerPrepared;
}
private boolean isLastTrack() {
return getPosition() == getPlayingQueue().size() - 1;
}
private void notifyOnMusicRemoteEventListeners(int event) {
MusicRemoteEvent musicRemoteEvent = new MusicRemoteEvent(event);
for (OnMusicRemoteEventListener listener : onMusicRemoteEventListeners) {
listener.onMusicRemoteEvent(musicRemoteEvent);
}
}
public void addOnMusicRemoteEventListener(OnMusicRemoteEventListener onMusicRemoteEventListener) {
onMusicRemoteEventListeners.add(onMusicRemoteEventListener);
}
public void saveState() {
saveQueuesAsync();
savePosition();
public void cycleRepeatMode() {
switch (getRepeatMode()) {
case REPEAT_MODE_NONE:
setRepeatMode(REPEAT_MODE_ALL);
break;
case REPEAT_MODE_ALL:
setRepeatMode(REPEAT_MODE_THIS);
break;
default:
setRepeatMode(REPEAT_MODE_NONE);
break;
}
}
public void saveQueuesAsync() {
if (isSavingQueues) {
saveQueuesAgain = true;
public int getRepeatMode() {
return repeatMode;
}
public void setRepeatMode(final int repeatMode) {
switch (repeatMode) {
case REPEAT_MODE_NONE:
case REPEAT_MODE_ALL:
case REPEAT_MODE_THIS:
this.repeatMode = repeatMode;
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putInt(AppKeys.SP_REPEAT_MODE, repeatMode)
.apply();
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.REPEAT_MODE_CHANGED);
break;
}
}
public void toggleShuffle() {
if (getShuffleMode() == SHUFFLE_MODE_NONE) {
setShuffleMode(SHUFFLE_MODE_SHUFFLE);
} else {
new Thread(new Runnable() {
@Override
public void run() {
isSavingQueues = true;
do {
saveQueuesAgain = false;
saveQueues();
} while (saveQueuesAgain);
isSavingQueues = false;
}
}).start();
setShuffleMode(SHUFFLE_MODE_NONE);
}
}
public void saveQueues() {
try {
InternalStorageUtil.writeObject(MusicService.this, AppKeys.IS_PLAYING_QUEUE, playingQueue);
InternalStorageUtil.writeObject(MusicService.this, AppKeys.IS_ORIGINAL_PLAYING_QUEUE, originalPlayingQueue);
Log.i(TAG, "saved current queue state");
} catch (IOException e) {
Log.e(TAG, "error while saving music service queue state", e);
}
}
public void savePosition() {
new Thread(new Runnable() {
@Override
public void run() {
try {
InternalStorageUtil.writeObject(MusicService.this, AppKeys.IS_POSITION_IN_QUEUE, getPosition());
Log.i(TAG, "saved current position state");
} catch (IOException e) {
Log.e(TAG, "error while saving music service position state", e);
}
}
}).start();
public int getShuffleMode() {
return shuffleMode;
}
public void setShuffleMode(final int shuffleMode) {
@ -615,47 +648,9 @@ public class MusicService extends Service implements MediaPlayer.OnPreparedListe
}
}
public void setRepeatMode(final int repeatMode) {
switch (repeatMode) {
case REPEAT_MODE_NONE:
case REPEAT_MODE_ALL:
case REPEAT_MODE_THIS:
this.repeatMode = repeatMode;
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putInt(AppKeys.SP_REPEAT_MODE, repeatMode)
.apply();
notifyOnMusicRemoteEventListeners(MusicRemoteEvent.REPEAT_MODE_CHANGED);
break;
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
public void cycleRepeatMode() {
switch (getRepeatMode()) {
case REPEAT_MODE_NONE:
setRepeatMode(REPEAT_MODE_ALL);
break;
case REPEAT_MODE_ALL:
setRepeatMode(REPEAT_MODE_THIS);
break;
default:
setRepeatMode(REPEAT_MODE_NONE);
break;
}
}
public void toggleShuffle() {
if (getShuffleMode() == SHUFFLE_MODE_NONE) {
setShuffleMode(SHUFFLE_MODE_SHUFFLE);
} else {
setShuffleMode(SHUFFLE_MODE_NONE);
}
}
public int getRepeatMode() {
return repeatMode;
}
public int getShuffleMode() {
return shuffleMode;
}
}

View file

@ -84,10 +84,56 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
private int titleViewHeight;
private int albumArtViewHeight;
private int toolbarColor;
private SmallObservableScrollViewCallbacks observableScrollViewCallbacks = new SmallObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean b, boolean b2) {
super.onScrollChanged(scrollY, b, b2);
// Translate overlay and image
float flexibleRange = albumArtViewHeight - headerOffset;
int minOverlayTransitionY = headerOffset - albumArtOverlayView.getHeight();
ViewHelper.setTranslationY(albumArtOverlayView, Math.max(minOverlayTransitionY, Math.min(0, -scrollY)));
ViewHelper.setTranslationY(albumArtImageView, Math.max(minOverlayTransitionY, Math.min(0, -scrollY / 2)));
// Translate list background
ViewHelper.setTranslationY(songsBackgroundView, Math.max(0, -scrollY + albumArtViewHeight));
// Change alpha of overlay
ViewHelper.setAlpha(albumArtOverlayView, Math.max(0, Math.min(1, (float) scrollY / flexibleRange)));
// Translate name text
int maxTitleTranslationY = albumArtViewHeight;
int titleTranslationY = maxTitleTranslationY - scrollY;
if (TOOLBAR_IS_STICKY) {
titleTranslationY = Math.max(headerOffset, titleTranslationY);
}
ViewHelper.setTranslationY(albumTitleView, titleTranslationY);
// Translate FAB
int fabTranslationY = titleTranslationY + titleViewHeight - (fab.getHeight() / 2);
ViewHelper.setTranslationY(fab, fabTranslationY);
if (TOOLBAR_IS_STICKY) {
// Change alpha of toolbar background
if (-scrollY + albumArtViewHeight <= headerOffset) {
ViewUtil.setBackgroundAlpha(toolbar, 1, toolbarColor);
ViewUtil.setBackgroundAlpha(statusBar, 1, toolbarColor);
} else {
ViewUtil.setBackgroundAlpha(toolbar, 0, toolbarColor);
ViewUtil.setBackgroundAlpha(statusBar, 0, toolbarColor);
}
} else {
// Translate Toolbar
if (scrollY < albumArtViewHeight) {
ViewHelper.setTranslationY(toolbar, 0);
} else {
ViewHelper.setTranslationY(toolbar, -scrollY);
}
}
}
};
private Bitmap albumCover;
@Override
protected void onCreate(Bundle savedInstanceState) {
app = (App) getApplicationContext();
@ -115,49 +161,6 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
animateEnterActivity();
}
@Override
public void onResume() {
super.onResume();
enableViews();
updateFabIcon();
app.getMusicPlayerRemote().addOnMusicRemoteEventListener(this);
}
@Override
protected void onStop() {
super.onStop();
app.getMusicPlayerRemote().removeOnMusicRemoteEventListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_album_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
case R.id.action_settings:
return true;
case R.id.action_current_playing:
return openCurrentPlayingIfPossible(null);
case R.id.action_tag_editor:
Intent intent = new Intent(this, AlbumTagEditorActivity.class);
intent.putExtra(AppKeys.E_ID, album.id);
startActivity(intent);
return true;
case R.id.action_go_to_artist:
goToArtistDetailsActivity(album.artistId, null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void initViews() {
albumArtImageView = (ImageView) findViewById(R.id.album_art);
toolbar = (Toolbar) findViewById(R.id.toolbar);
@ -217,26 +220,16 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
});
}
private void setUpSongsAdapter() {
final List<Song> songs = AlbumSongLoader.getAlbumSongList(this, album.id);
Collections.sort(songs, new SongTrackNumberComparator());
final SongAdapter songAdapter = new SongAdapter(this, this, songs);
// SwingBottomInAnimationAdapter songsAdapter = new SwingBottomInAnimationAdapter(songAdapter);
// SwingRightInAnimationAdapter songsAdapter = new SwingRightInAnimationAdapter(songAdapter);
// SwingLeftInAnimationAdapter songsAdapter = new SwingLeftInAnimationAdapter(songAdapter);
ScaleInAnimationAdapter songsAdapter = new ScaleInAnimationAdapter(songAdapter);
// AlphaInAnimationAdapter songsAdapter = new AlphaInAnimationAdapter(songAdapter);
animatedSongsAdapter = songsAdapter;
animatedSongsAdapter.setAbsListView(absSongListView);
absSongListView.setAdapter(animatedSongsAdapter);
absSongListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
private void applyPalette(Bitmap bitmap) {
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position > 0) {
app.getMusicPlayerRemote().openQueue(songs, position - 1, true);
public void onGenerated(Palette palette) {
Palette.Swatch swatch = palette.getVibrantSwatch();
if (swatch != null) {
toolbarColor = swatch.getRgb();
albumArtOverlayView.setBackgroundColor(swatch.getRgb());
albumTitleView.setBackgroundColor(swatch.getRgb());
albumTitleView.setTextColor(swatch.getTitleTextColor());
}
}
});
@ -289,107 +282,6 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
}
}
private void applyPalette(Bitmap bitmap) {
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
Palette.Swatch swatch = palette.getVibrantSwatch();
if (swatch != null) {
toolbarColor = swatch.getRgb();
albumArtOverlayView.setBackgroundColor(swatch.getRgb());
albumTitleView.setBackgroundColor(swatch.getRgb());
albumTitleView.setTextColor(swatch.getTitleTextColor());
}
}
});
}
private SmallObservableScrollViewCallbacks observableScrollViewCallbacks = new SmallObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean b, boolean b2) {
super.onScrollChanged(scrollY, b, b2);
// Translate overlay and image
float flexibleRange = albumArtViewHeight - headerOffset;
int minOverlayTransitionY = headerOffset - albumArtOverlayView.getHeight();
ViewHelper.setTranslationY(albumArtOverlayView, Math.max(minOverlayTransitionY, Math.min(0, -scrollY)));
ViewHelper.setTranslationY(albumArtImageView, Math.max(minOverlayTransitionY, Math.min(0, -scrollY / 2)));
// Translate list background
ViewHelper.setTranslationY(songsBackgroundView, Math.max(0, -scrollY + albumArtViewHeight));
// Change alpha of overlay
ViewHelper.setAlpha(albumArtOverlayView, Math.max(0, Math.min(1, (float) scrollY / flexibleRange)));
// Translate name text
int maxTitleTranslationY = albumArtViewHeight;
int titleTranslationY = maxTitleTranslationY - scrollY;
if (TOOLBAR_IS_STICKY) {
titleTranslationY = Math.max(headerOffset, titleTranslationY);
}
ViewHelper.setTranslationY(albumTitleView, titleTranslationY);
// Translate FAB
int fabTranslationY = titleTranslationY + titleViewHeight - (fab.getHeight() / 2);
ViewHelper.setTranslationY(fab, fabTranslationY);
if (TOOLBAR_IS_STICKY) {
// Change alpha of toolbar background
if (-scrollY + albumArtViewHeight <= headerOffset) {
ViewUtil.setBackgroundAlpha(toolbar, 1, toolbarColor);
ViewUtil.setBackgroundAlpha(statusBar, 1, toolbarColor);
} else {
ViewUtil.setBackgroundAlpha(toolbar, 0, toolbarColor);
ViewUtil.setBackgroundAlpha(statusBar, 0, toolbarColor);
}
} else {
// Translate Toolbar
if (scrollY < albumArtViewHeight) {
ViewHelper.setTranslationY(toolbar, 0);
} else {
ViewHelper.setTranslationY(toolbar, -scrollY);
}
}
}
};
@Override
public void onMusicRemoteEvent(MusicRemoteEvent event) {
switch (event.getAction()) {
case MusicRemoteEvent.PLAY:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause_white_48dp));
break;
case MusicRemoteEvent.PAUSE:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_arrow_white_48dp));
break;
case MusicRemoteEvent.RESUME:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause_white_48dp));
break;
case MusicRemoteEvent.STOP:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_arrow_white_48dp));
break;
case MusicRemoteEvent.QUEUE_COMPLETED:
fab.setImageResource(R.drawable.ic_play_arrow_white_48dp);
break;
}
}
@Override
public void enableViews() {
super.enableViews();
absSongListView.setEnabled(true);
fab.setEnabled(true);
toolbar.setEnabled(true);
}
@Override
public void disableViews() {
super.disableViews();
absSongListView.setEnabled(false);
fab.setEnabled(false);
toolbar.setEnabled(false);
}
private void setUpTranslucence() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Util.setStatusBarTranslucent(getWindow(), true);
@ -399,14 +291,50 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
}
}
private void updateFabIcon() {
if (app.getMusicPlayerRemote().isPlaying()) {
fab.setImageResource(R.drawable.ic_pause_white_48dp);
private void animateEnterActivity() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
animateHeader(0);
setUpSongsAdapter();
}
}, DEFAULT_DELAY);
} else {
fab.setImageResource(R.drawable.ic_play_arrow_white_48dp);
setUpSongsAdapter();
fab.setScaleX(0);
fab.setScaleY(0);
animateHeader(DEFAULT_DELAY_NO_TRANSITION);
animateFab(DEFAULT_DELAY_NO_TRANSITION);
}
}
private void setUpSongsAdapter() {
final List<Song> songs = AlbumSongLoader.getAlbumSongList(this, album.id);
Collections.sort(songs, new SongTrackNumberComparator());
final SongAdapter songAdapter = new SongAdapter(this, this, songs);
// SwingBottomInAnimationAdapter songsAdapter = new SwingBottomInAnimationAdapter(songAdapter);
// SwingRightInAnimationAdapter songsAdapter = new SwingRightInAnimationAdapter(songAdapter);
// SwingLeftInAnimationAdapter songsAdapter = new SwingLeftInAnimationAdapter(songAdapter);
ScaleInAnimationAdapter songsAdapter = new ScaleInAnimationAdapter(songAdapter);
// AlphaInAnimationAdapter songsAdapter = new AlphaInAnimationAdapter(songAdapter);
animatedSongsAdapter = songsAdapter;
animatedSongsAdapter.setAbsListView(absSongListView);
absSongListView.setAdapter(animatedSongsAdapter);
absSongListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position > 0) {
app.getMusicPlayerRemote().openQueue(songs, position - 1, true);
}
}
});
}
private void animateHeader(int startDelay) {
ViewPropertyAnimator.animate(albumTitleView)
.scaleX(1)
@ -427,25 +355,6 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
.start();
}
private void animateEnterActivity() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
animateHeader(0);
setUpSongsAdapter();
}
}, DEFAULT_DELAY);
} else {
setUpSongsAdapter();
fab.setScaleX(0);
fab.setScaleY(0);
animateHeader(DEFAULT_DELAY_NO_TRANSITION);
animateFab(DEFAULT_DELAY_NO_TRANSITION);
}
}
@Override
public void goToAlbum(int albumId) {
if (album.id != albumId) {
@ -487,4 +396,92 @@ public class AlbumDetailActivity extends AbsFabActivity implements OnMusicRemote
});
}
}
@Override
public void onResume() {
super.onResume();
enableViews();
updateFabIcon();
app.getMusicPlayerRemote().addOnMusicRemoteEventListener(this);
}
@Override
public void enableViews() {
super.enableViews();
absSongListView.setEnabled(true);
fab.setEnabled(true);
toolbar.setEnabled(true);
}
@Override
public void disableViews() {
super.disableViews();
absSongListView.setEnabled(false);
fab.setEnabled(false);
toolbar.setEnabled(false);
}
@Override
protected void onStop() {
super.onStop();
app.getMusicPlayerRemote().removeOnMusicRemoteEventListener(this);
}
@Override
public void onMusicRemoteEvent(MusicRemoteEvent event) {
switch (event.getAction()) {
case MusicRemoteEvent.PLAY:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause_white_48dp));
break;
case MusicRemoteEvent.PAUSE:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_arrow_white_48dp));
break;
case MusicRemoteEvent.RESUME:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause_white_48dp));
break;
case MusicRemoteEvent.STOP:
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_arrow_white_48dp));
break;
case MusicRemoteEvent.QUEUE_COMPLETED:
fab.setImageResource(R.drawable.ic_play_arrow_white_48dp);
break;
}
}
private void updateFabIcon() {
if (app.getMusicPlayerRemote().isPlaying()) {
fab.setImageResource(R.drawable.ic_pause_white_48dp);
} else {
fab.setImageResource(R.drawable.ic_play_arrow_white_48dp);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_album_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
case R.id.action_settings:
return true;
case R.id.action_current_playing:
return openCurrentPlayingIfPossible(null);
case R.id.action_tag_editor:
Intent intent = new Intent(this, AlbumTagEditorActivity.class);
intent.putExtra(AppKeys.E_ID, album.id);
startActivity(intent);
return true;
case R.id.action_go_to_artist:
goToArtistDetailsActivity(album.artistId, null);
return true;
}
return super.onOptionsItemSelected(item);
}
}

View file

@ -97,28 +97,6 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
lollipopTransitionImageWrongSizeFix();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_artist_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
case R.id.action_settings:
return true;
case R.id.action_current_playing:
openCurrentPlayingIfPossible(null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void initViews() {
artistImageView = (ImageView) findViewById(R.id.artist_image);
toolbar = (Toolbar) findViewById(R.id.toolbar);
@ -181,80 +159,42 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
});
}
private void setUpArtistImageAndApplyPalette() {
if (artistImage == null) {
LastFMArtistImageLoader.loadArtistImage(this, artist.name, new LastFMArtistImageLoader.ArtistImageLoaderCallback() {
@Override
public void onArtistImageLoaded(Bitmap artistImage) {
if (artistImage != null) {
ArtistDetailActivity.this.artistImage = artistImage;
artistImageView.setImageBitmap(artistImage);
applyPalette(artistImage);
}
}
});
} else {
artistImageView.setImageBitmap(artistImage);
applyPalette(artistImage);
}
}
private void setUpViewPatch() {
final View contentView = getWindow().getDecorView().findViewById(android.R.id.content);
contentView.post(new Runnable() {
public void restoreY(final int scrollY) {
translateToolBar(scrollY);
int animationTime = 1000;
DecelerateInterpolator interpolator = new DecelerateInterpolator(4);
int titleTranslationY = getTitleTranslation(scrollY);
ViewPropertyAnimator.animate(artistArtOverlayView).y(getOverlayTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(artistImageView).y(getImageViewTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(absAlbumListBackgroundView).y(getListBackgroundTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(artistArtOverlayView).alpha(getOverlayAlpha(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(slidingTabs).y(titleTranslationY + titleViewHeight).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(artistTitleText).y(titleTranslationY).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(getFab()).y(getFabTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).setListener(new Animator.AnimatorListener() {
@Override
public void run() {
absAlbumListBackgroundView.getLayoutParams().height = contentView.getHeight();
public void onAnimationStart(Animator animation) {
isAnimating = true;
}
});
}
private void setUpToolBar() {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (!TOOLBAR_IS_STICKY) {
toolbar.setBackgroundColor(Color.TRANSPARENT);
}
}
private void applyPalette(Bitmap bitmap) {
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
Palette.Swatch swatch = palette.getVibrantSwatch();
if (swatch != null) {
toolbarColor = swatch.getRgb();
artistArtOverlayView.setBackgroundColor(swatch.getRgb());
artistTitleText.setBackgroundColor(swatch.getRgb());
slidingTabs.setBackgroundColor(swatch.getRgb());
artistTitleText.setTextColor(swatch.getTitleTextColor());
public void onAnimationEnd(Animator animation) {
translateToolBar(scrollY);
isAnimating = false;
if (currentFragment instanceof AbsViewPagerTabArtistListFragment) {
onScrollChanged((((AbsViewPagerTabArtistListFragment) currentFragment).getY()), false, false);
}
}
});
}
@Override
public void enableViews() {
super.enableViews();
viewPager.setEnabled(true);
toolbar.setEnabled(true);
}
@Override
public void onAnimationCancel(Animator animation) {
isAnimating = false;
}
@Override
public void disableViews() {
super.disableViews();
viewPager.setEnabled(false);
toolbar.setEnabled(false);
}
private void getIntentExtras() {
Bundle intentExtras = getIntent().getExtras();
final int artistId = intentExtras.getInt(AppKeys.E_ARTIST);
artist = ArtistLoader.getArtist(this, artistId);
if (artist == null) {
finish();
}
@Override
public void onAnimationRepeat(Animator animation) {
isAnimating = true;
}
}).start();
}
@Override
@ -272,6 +212,14 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
}
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
}
private int getImageViewTranslation(int scrollY) {
int minOverlayTransitionY = headerOffset - artistArtOverlayView.getHeight();
return Math.max(minOverlayTransitionY, Math.min(0, -scrollY / 2));
@ -325,50 +273,66 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
}
}
public void restoreY(final int scrollY) {
translateToolBar(scrollY);
int animationTime = 1000;
DecelerateInterpolator interpolator = new DecelerateInterpolator(4);
int titleTranslationY = getTitleTranslation(scrollY);
ViewPropertyAnimator.animate(artistArtOverlayView).y(getOverlayTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(artistImageView).y(getImageViewTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(absAlbumListBackgroundView).y(getListBackgroundTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(artistArtOverlayView).alpha(getOverlayAlpha(scrollY)).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(slidingTabs).y(titleTranslationY + titleViewHeight).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(artistTitleText).y(titleTranslationY).setDuration(animationTime).setInterpolator(interpolator).start();
ViewPropertyAnimator.animate(getFab()).y(getFabTranslation(scrollY)).setDuration(animationTime).setInterpolator(interpolator).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
isAnimating = true;
}
private void setUpArtistImageAndApplyPalette() {
if (artistImage == null) {
LastFMArtistImageLoader.loadArtistImage(this, artist.name, new LastFMArtistImageLoader.ArtistImageLoaderCallback() {
@Override
public void onArtistImageLoaded(Bitmap artistImage) {
if (artistImage != null) {
ArtistDetailActivity.this.artistImage = artistImage;
artistImageView.setImageBitmap(artistImage);
applyPalette(artistImage);
}
}
});
} else {
artistImageView.setImageBitmap(artistImage);
applyPalette(artistImage);
}
}
private void applyPalette(Bitmap bitmap) {
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
public void onAnimationEnd(Animator animation) {
translateToolBar(scrollY);
isAnimating = false;
if (currentFragment instanceof AbsViewPagerTabArtistListFragment) {
onScrollChanged((((AbsViewPagerTabArtistListFragment) currentFragment).getY()), false, false);
public void onGenerated(Palette palette) {
Palette.Swatch swatch = palette.getVibrantSwatch();
if (swatch != null) {
toolbarColor = swatch.getRgb();
artistArtOverlayView.setBackgroundColor(swatch.getRgb());
artistTitleText.setBackgroundColor(swatch.getRgb());
slidingTabs.setBackgroundColor(swatch.getRgb());
artistTitleText.setTextColor(swatch.getTitleTextColor());
}
}
@Override
public void onAnimationCancel(Animator animation) {
isAnimating = false;
}
@Override
public void onAnimationRepeat(Animator animation) {
isAnimating = true;
}
}).start();
});
}
@Override
public void onDownMotionEvent() {
private void setUpViewPatch() {
final View contentView = getWindow().getDecorView().findViewById(android.R.id.content);
contentView.post(new Runnable() {
@Override
public void run() {
absAlbumListBackgroundView.getLayoutParams().height = contentView.getHeight();
}
});
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
private void setUpToolBar() {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (!TOOLBAR_IS_STICKY) {
toolbar.setBackgroundColor(Color.TRANSPARENT);
}
}
private void getIntentExtras() {
Bundle intentExtras = getIntent().getExtras();
final int artistId = intentExtras.getInt(AppKeys.E_ARTIST);
artist = ArtistLoader.getArtist(this, artistId);
if (artist == null) {
finish();
}
}
@Override
@ -420,6 +384,42 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_artist_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
case R.id.action_settings:
return true;
case R.id.action_current_playing:
openCurrentPlayingIfPossible(null);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void enableViews() {
super.enableViews();
viewPager.setEnabled(true);
toolbar.setEnabled(true);
}
@Override
public void disableViews() {
super.disableViews();
viewPager.setEnabled(false);
toolbar.setEnabled(false);
}
private static class NavigationAdapter extends FragmentPagerAdapter {
private String[] titles;
@ -465,6 +465,14 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
return f;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (0 <= mPages.indexOfKey(position)) {
mPages.remove(position);
}
super.destroyItem(container, position, object);
}
public Fragment getItemAt(int position) {
return mPages.get(position, null);
}
@ -474,14 +482,6 @@ public class ArtistDetailActivity extends AbsFabActivity implements OnMusicRemot
return titles.length;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (0 <= mPages.indexOfKey(position)) {
mPages.remove(position);
}
super.destroyItem(container, position, object);
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];

View file

@ -68,6 +68,48 @@ public class MainActivity extends AbsFabActivity
}
}
private void initViews() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
updateNavigationDrawerHeader();
}
private void updateNavigationDrawerHeader() {
Song song = getApp().getMusicPlayerRemote().getCurrentSong();
if (navigationDrawerFragment != null && song.id != -1) {
ImageLoader.getInstance().displayImage(MusicUtil.getAlbumArtUri(song.albumId).toString(), navigationDrawerFragment.getAlbumArtImageView(), new ImageLoaderUtil.defaultAlbumArtOnFailed());
navigationDrawerFragment.getSongTitle().setText(song.title);
navigationDrawerFragment.getSongArtist().setText(song.artistName);
}
}
private void setUpToolBar() {
toolbarTitle = getTitle();
toolbar = (Toolbar) findViewById(R.id.toolbar);
statusBar = findViewById(R.id.statusBar);
setSupportActionBar(toolbar);
ViewUtil.setBackgroundAlpha(toolbar, 0.97f, Util.resolveColor(this, R.attr.colorPrimary));
ViewUtil.setBackgroundAlpha(statusBar, 0.97f, Util.resolveColor(this, R.attr.colorPrimary));
setUpDrawerToggle();
}
private void setUpDrawerToggle() {
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
);
drawerLayout.post(new Runnable() {
@Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
}
@Override
protected void onResume() {
super.onResume();
@ -75,9 +117,23 @@ public class MainActivity extends AbsFabActivity
}
@Override
protected void onDestroy() {
super.onDestroy();
getApp().getMusicPlayerRemote().removeAllOnMusicRemoteEventListeners();
public void enableViews() {
try {
super.enableViews();
toolbar.setEnabled(true);
} catch (NullPointerException e) {
Log.e(TAG, "wasn't able to enable the views", e.fillInStackTrace());
}
}
@Override
public void disableViews() {
try {
super.disableViews();
toolbar.setEnabled(false);
} catch (NullPointerException e) {
Log.e(TAG, "wasn't able to disable the views", e.fillInStackTrace());
}
}
@Override
@ -135,22 +191,6 @@ public class MainActivity extends AbsFabActivity
}
}
private void initViews() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
updateNavigationDrawerHeader();
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(toolbarTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.drawer, menu);
@ -193,6 +233,14 @@ public class MainActivity extends AbsFabActivity
return true;
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(toolbarTitle);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
@ -216,6 +264,12 @@ public class MainActivity extends AbsFabActivity
super.onConfigurationChanged(newConfig);
}
@Override
protected void onDestroy() {
super.onDestroy();
getApp().getMusicPlayerRemote().removeAllOnMusicRemoteEventListeners();
}
@Override
public void onBackPressed() {
if (navigationDrawerFragment.isDrawerOpen()) {
@ -225,41 +279,6 @@ public class MainActivity extends AbsFabActivity
super.onBackPressed();
}
private void setUpToolBar() {
toolbarTitle = getTitle();
toolbar = (Toolbar) findViewById(R.id.toolbar);
statusBar = findViewById(R.id.statusBar);
setSupportActionBar(toolbar);
ViewUtil.setBackgroundAlpha(toolbar, 0.97f, Util.resolveColor(this, R.attr.colorPrimary));
ViewUtil.setBackgroundAlpha(statusBar, 0.97f, Util.resolveColor(this, R.attr.colorPrimary));
setUpDrawerToggle();
}
private void setUpDrawerToggle() {
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
);
drawerLayout.post(new Runnable() {
@Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
}
private void updateNavigationDrawerHeader() {
Song song = getApp().getMusicPlayerRemote().getCurrentSong();
if (navigationDrawerFragment != null && song.id != -1) {
ImageLoader.getInstance().displayImage(MusicUtil.getAlbumArtUri(song.albumId).toString(), navigationDrawerFragment.getAlbumArtImageView(), new ImageLoaderUtil.defaultAlbumArtOnFailed());
navigationDrawerFragment.getSongTitle().setText(song.title);
navigationDrawerFragment.getSongArtist().setText(song.artistName);
}
}
private void disableFragmentViews() {
if (currentFragmentPosition >= 0 && currentFragmentPosition < getApp().MainActivityFragments.length) {
if (getApp().MainActivityFragments[currentFragmentPosition] instanceof KabViewsDisableAble) {
@ -285,26 +304,6 @@ public class MainActivity extends AbsFabActivity
return true;
}
@Override
public void enableViews() {
try {
super.enableViews();
toolbar.setEnabled(true);
} catch (NullPointerException e) {
Log.e(TAG, "wasn't able to enable the views", e.fillInStackTrace());
}
}
@Override
public void disableViews() {
try {
super.disableViews();
toolbar.setEnabled(false);
} catch (NullPointerException e) {
Log.e(TAG, "wasn't able to disable the views", e.fillInStackTrace());
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {

View file

@ -84,56 +84,6 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
setUpToolBar();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_title_playing, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
case R.id.action_playing_queue:
final MaterialDialog materialDialog = PlayingQueueDialogHelper.getDialog(this);
materialDialog.show();
return true;
case R.id.action_tag_editor:
Intent intent = new Intent(this, SongTagEditorActivity.class);
intent.putExtra(AppKeys.E_ID, song.id);
startActivity(intent);
return true;
case R.id.action_details:
String songFilePath = SongFileLoader.getSongFile(this, song.id);
File songFile = new File(songFilePath);
SongDetailDialogHelper.getDialog(this, songFile).show();
return true;
case R.id.action_go_to_album:
goToAlbumDetailsActivity(song.albumId, null);
return true;
case R.id.action_go_to_artist:
goToArtistDetailsActivity(song.artistId, null);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
startMusicControllerStateUpdateThread();
}
@Override
protected void onPause() {
super.onPause();
killThreads = true;
}
private void updateCurrentSong() {
getCurrentSongAndQueue();
setHeadersText();
@ -143,13 +93,6 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
currentSongProgress.setText(MusicUtil.getReadableDurationString(-1));
}
private void moveSeekBarIntoPlace() {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) progressSlider.getLayoutParams();
progressSlider.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
lp.setMargins(0, 0, 0, -(progressSlider.getMeasuredHeight() / 2));
progressSlider.setLayoutParams(lp);
}
private void setHeadersText() {
songTitle.setText(song.title);
songArtist.setText(song.artistName);
@ -181,41 +124,6 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
});
}
private void setUpArtistArt() {
if (artistArt != null) {
artistArt.setImageResource(R.drawable.default_artist_image);
LastFMArtistImageLoader.loadArtistImage(this, song.artistName, new LastFMArtistImageLoader.ArtistImageLoaderCallback() {
@Override
public void onArtistImageLoaded(Bitmap artistImage) {
artistArt.setImageBitmap(artistImage);
}
});
}
}
private void getCurrentSongAndQueue() {
if (getApp().getMusicPlayerRemote().getPosition() >= 0) {
song = getApp().getMusicPlayerRemote().getPlayingQueue().get(getApp().getMusicPlayerRemote().getPosition());
} else {
finish();
}
}
private void initViews() {
nextButton = (ImageButton) findViewById(R.id.next_button);
prevButton = (ImageButton) findViewById(R.id.prev_button);
repeatButton = (ImageButton) findViewById(R.id.repeat_button);
shuffleButton = (ImageButton) findViewById(R.id.shuffle_button);
albumArt = (ImageView) findViewById(R.id.album_art);
artistArt = (ImageView) findViewById(R.id.artist_image);
songTitle = (TextView) findViewById(R.id.song_title);
songArtist = (TextView) findViewById(R.id.song_artist);
currentSongProgress = (TextView) findViewById(R.id.song_current_progress);
totalSongDuration = (TextView) findViewById(R.id.song_total_time);
footer = findViewById(R.id.footer);
progressSlider = (SeekBar) findViewById(R.id.progress_slider);
}
private void applyPalette(Bitmap bitmap) {
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
@ -255,6 +163,48 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
lastFooterColor = newColor;
}
private void setUpArtistArt() {
if (artistArt != null) {
artistArt.setImageResource(R.drawable.default_artist_image);
LastFMArtistImageLoader.loadArtistImage(this, song.artistName, new LastFMArtistImageLoader.ArtistImageLoaderCallback() {
@Override
public void onArtistImageLoaded(Bitmap artistImage) {
artistArt.setImageBitmap(artistImage);
}
});
}
}
private void getCurrentSongAndQueue() {
if (getApp().getMusicPlayerRemote().getPosition() >= 0) {
song = getApp().getMusicPlayerRemote().getPlayingQueue().get(getApp().getMusicPlayerRemote().getPosition());
} else {
finish();
}
}
private void moveSeekBarIntoPlace() {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) progressSlider.getLayoutParams();
progressSlider.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
lp.setMargins(0, 0, 0, -(progressSlider.getMeasuredHeight() / 2));
progressSlider.setLayoutParams(lp);
}
private void initViews() {
nextButton = (ImageButton) findViewById(R.id.next_button);
prevButton = (ImageButton) findViewById(R.id.prev_button);
repeatButton = (ImageButton) findViewById(R.id.repeat_button);
shuffleButton = (ImageButton) findViewById(R.id.shuffle_button);
albumArt = (ImageView) findViewById(R.id.album_art);
artistArt = (ImageView) findViewById(R.id.artist_image);
songTitle = (TextView) findViewById(R.id.song_title);
songArtist = (TextView) findViewById(R.id.song_artist);
currentSongProgress = (TextView) findViewById(R.id.song_current_progress);
totalSongDuration = (TextView) findViewById(R.id.song_total_time);
footer = findViewById(R.id.footer);
progressSlider = (SeekBar) findViewById(R.id.progress_slider);
}
private void setUpMusicControllers() {
setUpPrevNext();
setUpRepeatButton();
@ -306,6 +256,17 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
});
}
private void updateShuffleState() {
switch (getApp().getMusicPlayerRemote().getShuffleMode()) {
case MusicService.SHUFFLE_MODE_SHUFFLE:
shuffleButton.setImageResource(R.drawable.ic_shuffle_white_48dp);
break;
default:
shuffleButton.setImageResource(R.drawable.ic_shuffle_grey600_48dp);
break;
}
}
private void setUpRepeatButton() {
updateRepeatState();
repeatButton.setOnClickListener(new View.OnClickListener() {
@ -330,22 +291,21 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
}
}
private void updateShuffleState() {
switch (getApp().getMusicPlayerRemote().getShuffleMode()) {
case MusicService.SHUFFLE_MODE_SHUFFLE:
shuffleButton.setImageResource(R.drawable.ic_shuffle_white_48dp);
break;
default:
shuffleButton.setImageResource(R.drawable.ic_shuffle_grey600_48dp);
break;
}
private void prepareViewsForOpenAnimation() {
footer.setPivotY(0);
footer.setScaleY(0);
}
private void setUpToolBar() {
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void updateControllerState() {
super.updateControllerState();
updateRepeatState();
updateShuffleState();
protected void onResume() {
super.onResume();
startMusicControllerStateUpdateThread();
}
private void startMusicControllerStateUpdateThread() {
@ -379,6 +339,19 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
}).start();
}
@Override
protected boolean openCurrentPlayingIfPossible(Pair[] sharedViews) {
onBackPressed();
return true;
}
@Override
protected void updateControllerState() {
super.updateControllerState();
updateRepeatState();
updateShuffleState();
}
@Override
public void onMusicRemoteEvent(MusicRemoteEvent event) {
super.onMusicRemoteEvent(event);
@ -398,9 +371,56 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
}
}
private void prepareViewsForOpenAnimation() {
footer.setPivotY(0);
footer.setScaleY(0);
@Override
protected void onPause() {
super.onPause();
killThreads = true;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
animateActivityOpened(DEFAULT_DELAY);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_title_playing, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
case R.id.action_playing_queue:
final MaterialDialog materialDialog = PlayingQueueDialogHelper.getDialog(this);
materialDialog.show();
return true;
case R.id.action_tag_editor:
Intent intent = new Intent(this, SongTagEditorActivity.class);
intent.putExtra(AppKeys.E_ID, song.id);
startActivity(intent);
return true;
case R.id.action_details:
String songFilePath = SongFileLoader.getSongFile(this, song.id);
File songFile = new File(songFilePath);
SongDetailDialogHelper.getDialog(this, songFile).show();
return true;
case R.id.action_go_to_album:
goToAlbumDetailsActivity(song.albumId, null);
return true;
case R.id.action_go_to_artist:
goToArtistDetailsActivity(song.artistId, null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void animateActivityOpened(int startDelay) {
@ -412,24 +432,4 @@ public class MusicControllerActivity extends AbsFabActivity implements OnMusicRe
.setStartDelay(startDelay)
.start();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
animateActivityOpened(DEFAULT_DELAY);
}
}
private void setUpToolBar() {
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected boolean openCurrentPlayingIfPossible(Pair[] sharedViews) {
onBackPressed();
return true;
}
}

View file

@ -32,12 +32,34 @@ public abstract class AbsBaseActivity extends ActionBarActivity implements KabVi
super.onCreate(savedInstanceState);
}
protected App getApp() {
if (app == null) {
app = (App) getApplicationContext();
}
return app;
}
@Override
protected void onResume() {
super.onResume();
enableViews();
}
@Override
public void enableViews() {
areViewsEnabled = true;
}
@Override
public void disableViews() {
areViewsEnabled = false;
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
protected void setUpTranslucence(boolean statusBarTranslucent, boolean navigationBarTranslucent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Util.setStatusBarTranslucent(getWindow(), statusBarTranslucent);
@ -78,19 +100,6 @@ public abstract class AbsBaseActivity extends ActionBarActivity implements KabVi
goToArtistDetailsActivity(artistId, null);
}
public void goToAlbumDetailsActivity(int albumId, Pair[] sharedViews) {
final Intent intent = new Intent(this, AlbumDetailActivity.class);
intent.putExtra(AppKeys.E_ALBUM, albumId);
if (sharedViews != null) {
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(this,
sharedViews
);
ActivityCompat.startActivity(this, intent, optionsCompat.toBundle());
} else {
startActivity(intent);
}
}
public void goToArtistDetailsActivity(int artistId, Pair[] sharedViews) {
final Intent intent = new Intent(this, ArtistDetailActivity.class);
intent.putExtra(AppKeys.E_ARTIST, artistId);
@ -104,25 +113,16 @@ public abstract class AbsBaseActivity extends ActionBarActivity implements KabVi
}
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
@Override
public void enableViews() {
areViewsEnabled = true;
}
@Override
public void disableViews() {
areViewsEnabled = false;
}
protected App getApp() {
if (app == null) {
app = (App) getApplicationContext();
public void goToAlbumDetailsActivity(int albumId, Pair[] sharedViews) {
final Intent intent = new Intent(this, AlbumDetailActivity.class);
intent.putExtra(AppKeys.E_ALBUM, albumId);
if (sharedViews != null) {
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(this,
sharedViews
);
ActivityCompat.startActivity(this, intent, optionsCompat.toBundle());
} else {
startActivity(intent);
}
return app;
}
}

View file

@ -19,73 +19,12 @@ import com.melnykov.fab.FloatingActionButton;
public abstract class AbsFabActivity extends AbsBaseActivity implements OnMusicRemoteEventListener {
private FloatingActionButton fab;
protected FloatingActionButton getFab() {
if (fab == null) {
fab = (FloatingActionButton) findViewById(R.id.fab);
}
return fab;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setUpFab();
}
@Override
protected void onResume() {
super.onResume();
updateControllerState();
getApp().getMusicPlayerRemote().addOnMusicRemoteEventListener(this);
}
@Override
protected void onStop() {
super.onStop();
getApp().getMusicPlayerRemote().removeOnMusicRemoteEventListener(this);
}
@Override
public void enableViews() {
super.enableViews();
fab.setEnabled(true);
}
@Override
public void disableViews() {
super.disableViews();
fab.setEnabled(false);
}
@Override
protected boolean openCurrentPlayingIfPossible(Pair[] sharedViews) {
return super.openCurrentPlayingIfPossible(getSharedViewsWithFab(sharedViews));
}
@Override
public void goToArtistDetailsActivity(int artistId, Pair[] sharedViews) {
super.goToArtistDetailsActivity(artistId, getSharedViewsWithFab(sharedViews));
}
@Override
public void goToAlbumDetailsActivity(int albumId, Pair[] sharedViews) {
super.goToAlbumDetailsActivity(albumId, getSharedViewsWithFab(sharedViews));
}
private Pair[] getSharedViewsWithFab(Pair[] sharedViews) {
Pair[] sharedViewsWithFab;
if (sharedViews != null) {
sharedViewsWithFab = new Pair[sharedViews.length + 1];
for (int i = 0; i < sharedViews.length; i++) {
sharedViewsWithFab[i] = sharedViews[i];
}
} else {
sharedViewsWithFab = new Pair[1];
}
sharedViewsWithFab[sharedViewsWithFab.length - 1] = Pair.create((View) getFab(), getString(R.string.transition_fab));
return sharedViewsWithFab;
}
private void setUpFab() {
updateFabState();
final GestureDetector gestureDetector = new GestureDetector(this, new SmallOnGestureListener() {
@ -128,10 +67,6 @@ public abstract class AbsFabActivity extends AbsBaseActivity implements OnMusicR
});
}
protected void updateControllerState() {
updateFabState();
}
private void updateFabState() {
if (getApp().getMusicPlayerRemote().isPlaying()) {
getFab().setImageResource(R.drawable.ic_pause_white_48dp);
@ -140,6 +75,71 @@ public abstract class AbsFabActivity extends AbsBaseActivity implements OnMusicR
}
}
protected FloatingActionButton getFab() {
if (fab == null) {
fab = (FloatingActionButton) findViewById(R.id.fab);
}
return fab;
}
@Override
protected void onResume() {
super.onResume();
updateControllerState();
getApp().getMusicPlayerRemote().addOnMusicRemoteEventListener(this);
}
@Override
public void enableViews() {
super.enableViews();
fab.setEnabled(true);
}
@Override
public void disableViews() {
super.disableViews();
fab.setEnabled(false);
}
@Override
protected boolean openCurrentPlayingIfPossible(Pair[] sharedViews) {
return super.openCurrentPlayingIfPossible(getSharedViewsWithFab(sharedViews));
}
@Override
public void goToArtistDetailsActivity(int artistId, Pair[] sharedViews) {
super.goToArtistDetailsActivity(artistId, getSharedViewsWithFab(sharedViews));
}
@Override
public void goToAlbumDetailsActivity(int albumId, Pair[] sharedViews) {
super.goToAlbumDetailsActivity(albumId, getSharedViewsWithFab(sharedViews));
}
private Pair[] getSharedViewsWithFab(Pair[] sharedViews) {
Pair[] sharedViewsWithFab;
if (sharedViews != null) {
sharedViewsWithFab = new Pair[sharedViews.length + 1];
for (int i = 0; i < sharedViews.length; i++) {
sharedViewsWithFab[i] = sharedViews[i];
}
} else {
sharedViewsWithFab = new Pair[1];
}
sharedViewsWithFab[sharedViewsWithFab.length - 1] = Pair.create((View) getFab(), getString(R.string.transition_fab));
return sharedViewsWithFab;
}
protected void updateControllerState() {
updateFabState();
}
@Override
protected void onStop() {
super.onStop();
getApp().getMusicPlayerRemote().removeOnMusicRemoteEventListener(this);
}
@Override
public void onMusicRemoteEvent(MusicRemoteEvent event) {
switch (event.getAction()) {

View file

@ -68,7 +68,21 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
private Toolbar toolBar;
private ImageView image;
private View header;
private SmallObservableScrollViewCallbacks observableScrollViewCallbacks = new SmallObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean b, boolean b2) {
float alpha;
if (!isInNoImageMode) {
alpha = 1 - (float) Math.max(0, headerVariableSpace - scrollY) / headerVariableSpace;
} else {
ViewHelper.setTranslationY(header, scrollY);
alpha = 1;
}
ViewUtil.setBackgroundAlpha(toolBar, alpha, paletteColorPrimary);
ViewUtil.setBackgroundAlpha(header, alpha, paletteColorPrimary);
ViewHelper.setTranslationY(image, scrollY / 2);
}
};
private List<String> songPaths;
@Override
@ -147,23 +161,44 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
});
}
protected void searchWebFor(List<String> strings) {
StringBuilder stringBuilder = new StringBuilder();
for (String string : strings) {
stringBuilder.append(string);
stringBuilder.append(" ");
}
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, stringBuilder.toString());
startActivity(intent);
}
private void startImagePicker() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_SELECT_IMAGE);
}
protected abstract void loadCurrentImage();
protected abstract void getImageFromLastFM();
protected abstract void searchImageOnWeb();
protected abstract void deleteImage();
protected void setUpFab() {
ViewHelper.setScaleX(fab, 0);
ViewHelper.setScaleY(fab, 0);
fab.setEnabled(false);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
}
});
}
protected abstract void save();
private void restoreStandardColors() {
final int vibrantColor = Util.resolveColor(this, R.attr.colorPrimary);
paletteColorPrimary = vibrantColor;
observableScrollViewCallbacks.onScrollChanged(scrollView.getCurrentScrollY(), false, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(vibrantColor);
getWindow().setNavigationBarColor(vibrantColor);
}
}
private void setUpTranslucence() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Util.setStatusBarTranslucent(getWindow(), false);
@ -184,6 +219,21 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
protected abstract int getContentViewResId();
protected abstract List<String> getSongPaths();
protected void searchWebFor(List<String> strings) {
StringBuilder stringBuilder = new StringBuilder();
for (String string : strings) {
stringBuilder.append(string);
stringBuilder.append(" ");
}
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, stringBuilder.toString());
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tag_editor, menu);
@ -203,16 +253,16 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
return super.onOptionsItemSelected(item);
}
protected void setUpFab() {
ViewHelper.setScaleX(fab, 0);
ViewHelper.setScaleY(fab, 0);
fab.setEnabled(false);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
}
});
protected void setNoImageMode() {
isInNoImageMode = true;
image.setVisibility(View.GONE);
image.setEnabled(false);
scrollView.setPadding(0, Util.getActionBarSize(this), 0, 0);
observableScrollViewCallbacks.onScrollChanged(scrollView.getCurrentScrollY(), false, false);
}
protected void dataChanged() {
showFab();
}
private void showFab() {
@ -225,21 +275,17 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
fab.setEnabled(true);
}
private SmallObservableScrollViewCallbacks observableScrollViewCallbacks = new SmallObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean b, boolean b2) {
float alpha;
if (!isInNoImageMode) {
alpha = 1 - (float) Math.max(0, headerVariableSpace - scrollY) / headerVariableSpace;
} else {
ViewHelper.setTranslationY(header, scrollY);
alpha = 1;
}
ViewUtil.setBackgroundAlpha(toolBar, alpha, paletteColorPrimary);
ViewUtil.setBackgroundAlpha(header, alpha, paletteColorPrimary);
ViewHelper.setTranslationY(image, scrollY / 2);
protected void setImageRes(int resId) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
setImageBitmap(bitmap);
}
protected void setImageBitmap(final Bitmap bitmap) {
if (bitmap != null) {
image.setImageBitmap(bitmap);
applyPalette(bitmap);
}
};
}
private void applyPalette(final Bitmap bitmap) {
if (bitmap != null) {
@ -260,71 +306,10 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
}
}
private void restoreStandardColors() {
final int vibrantColor = Util.resolveColor(this, R.attr.colorPrimary);
paletteColorPrimary = vibrantColor;
observableScrollViewCallbacks.onScrollChanged(scrollView.getCurrentScrollY(), false, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(vibrantColor);
getWindow().setNavigationBarColor(vibrantColor);
}
}
protected void setNoImageMode() {
isInNoImageMode = true;
image.setVisibility(View.GONE);
image.setEnabled(false);
scrollView.setPadding(0, Util.getActionBarSize(this), 0, 0);
observableScrollViewCallbacks.onScrollChanged(scrollView.getCurrentScrollY(), false, false);
}
protected void dataChanged() {
showFab();
}
protected void setImageBitmap(final Bitmap bitmap) {
if (bitmap != null) {
image.setImageBitmap(bitmap);
applyPalette(bitmap);
}
}
protected void setImageRes(int resId) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
setImageBitmap(bitmap);
}
private void rescanMedia() {
String[] toBeScanned = new String[songPaths.size()];
toBeScanned = songPaths.toArray(toBeScanned);
MediaScannerConnection.scanFile(this, toBeScanned, null, null);
}
private AudioFile getAudioFile(String path) {
try {
return AudioFileIO.read(new File(path));
} catch (CannotReadException | ReadOnlyFileException | InvalidAudioFrameException | TagException | IOException e) {
Log.e(TAG, "error while trying to create the AudioFile from File", e);
}
return null;
}
protected void writeValuesToFiles(final Map<FieldKey, String> fieldKeyValueMap) {
writeValuesToFiles(fieldKeyValueMap, null, false);
}
protected void writeValuesToFiles(final Map<FieldKey, String> fieldKeyValueMap, final Artwork artwork) {
if (artwork == null) {
writeValuesToFiles(fieldKeyValueMap, null, true);
} else {
writeValuesToFiles(fieldKeyValueMap, artwork, false);
}
}
protected void writeValuesToFiles(final Map<FieldKey, String> fieldKeyValueMap, boolean deleteArtwork) {
writeValuesToFiles(fieldKeyValueMap, null, deleteArtwork);
}
protected void writeValuesToFiles(final Map<FieldKey, String> fieldKeyValueMap, final Artwork artwork, final boolean deleteArtwork) {
final String writingFileStr = getResources().getString(R.string.writing_file_number);
final MaterialDialog progressDialog = new MaterialDialog.Builder(AbsTagEditorActivity.this)
@ -382,6 +367,12 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
}).start();
}
private void rescanMedia() {
String[] toBeScanned = new String[songPaths.size()];
toBeScanned = songPaths.toArray(toBeScanned);
MediaScannerConnection.scanFile(this, toBeScanned, null, null);
}
private void restartApp() {
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
@ -389,6 +380,22 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
startActivity(i);
}
protected int getId() {
return id;
}
protected void writeValuesToFiles(final Map<FieldKey, String> fieldKeyValueMap, final Artwork artwork) {
if (artwork == null) {
writeValuesToFiles(fieldKeyValueMap, null, true);
} else {
writeValuesToFiles(fieldKeyValueMap, artwork, false);
}
}
protected void writeValuesToFiles(final Map<FieldKey, String> fieldKeyValueMap, boolean deleteArtwork) {
writeValuesToFiles(fieldKeyValueMap, null, deleteArtwork);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
@ -401,30 +408,12 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
}
}
protected abstract void save();
protected abstract int getContentViewResId();
protected abstract void loadCurrentImage();
protected abstract void getImageFromLastFM();
protected abstract void searchImageOnWeb();
protected abstract void loadImageFromFile(Uri selectedFile);
protected abstract void deleteImage();
protected abstract List<String> getSongPaths();
protected App getApp() {
return app;
}
protected int getId() {
return id;
}
protected String getSongTitle() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.TITLE);
@ -433,6 +422,15 @@ public abstract class AbsTagEditorActivity extends ActionBarActivity {
}
}
private AudioFile getAudioFile(String path) {
try {
return AudioFileIO.read(new File(path));
} catch (CannotReadException | ReadOnlyFileException | InvalidAudioFrameException | TagException | IOException e) {
Log.e(TAG, "error while trying to create the AudioFile from File", e);
}
return null;
}
protected String getAlbumTitle() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.ALBUM);

View file

@ -27,7 +27,6 @@ import org.jaudiotagger.tag.images.ArtworkFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;

View file

@ -25,19 +25,14 @@ import com.nhaarman.listviewanimations.appearance.simple.AlphaInAnimationAdapter
import java.util.ArrayList;
public class NavigationDrawerFragment extends Fragment {
private static final String TAG = NavigationDrawerFragment.class.getSimpleName();
public static final int NAVIGATION_DRAWER_HEADER = -1;
private static final String TAG = NavigationDrawerFragment.class.getSimpleName();
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private App app;
private NavigationDrawerCallbacks mCallbacks;
private NavigationDrawerItemAdapter drawerAdapter;
private DrawerLayout drawerLayout;
public View fragmentRootView;
private App app;
private NavigationDrawerCallbacks mCallbacks;
private NavigationDrawerItemAdapter drawerAdapter;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private View fragmentContainerView;
@ -53,6 +48,45 @@ public class NavigationDrawerFragment extends Fragment {
public NavigationDrawerFragment() {
}
public boolean isDrawerOpen() {
return drawerLayout != null && drawerLayout.isDrawerOpen(fragmentContainerView);
}
public void setUp(int fragmentId, final DrawerLayout drawerLayout) {
fragmentContainerView = getActivity().findViewById(fragmentId);
this.drawerLayout = drawerLayout;
this.drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
if (!userLearnedDrawer && !fromSavedInstanceState) {
this.drawerLayout.openDrawer(fragmentContainerView);
userLearnedDrawer = true;
app.getDefaultSharedPreferences().edit().putBoolean(AppKeys.SP_USER_LEARNED_DRAWER, true).apply();
}
}
public TextView getSongArtist() {
return songArtist;
}
public ImageView getAlbumArtImageView() {
return albumArt;
}
public TextView getSongTitle() {
return songTitle;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
app = (App) getActivity().getApplicationContext();
@ -126,23 +160,6 @@ public class NavigationDrawerFragment extends Fragment {
});
}
public boolean isDrawerOpen() {
return drawerLayout != null && drawerLayout.isDrawerOpen(fragmentContainerView);
}
public void setUp(int fragmentId, final DrawerLayout drawerLayout) {
fragmentContainerView = getActivity().findViewById(fragmentId);
this.drawerLayout = drawerLayout;
this.drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
if (!userLearnedDrawer && !fromSavedInstanceState) {
this.drawerLayout.openDrawer(fragmentContainerView);
userLearnedDrawer = true;
app.getDefaultSharedPreferences().edit().putBoolean(AppKeys.SP_USER_LEARNED_DRAWER, true).apply();
}
}
private void selectItem(int position) {
if (position != NAVIGATION_DRAWER_HEADER) {
currentSelectedPosition = position;
@ -165,26 +182,10 @@ public class NavigationDrawerFragment extends Fragment {
}
}
public TextView getSongArtist() {
return songArtist;
}
public ImageView getAlbumArtImageView() {
return albumArt;
}
public TextView getSongTitle() {
return songTitle;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}
@Override
@ -193,12 +194,6 @@ public class NavigationDrawerFragment extends Fragment {
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}

View file

@ -68,6 +68,44 @@ public abstract class AbsViewPagerTabArtistListFragment extends Fragment impleme
}
}
/*
*
* IMPORTANT:
*
* You CAN return null here and use setAdapter(ListAdapter adapter) inside getAdapter() to manually set the adapter.
*
* (i.e. if you must set the adapter async).
*
* */
protected abstract ListAdapter getAdapter();
protected void setAdapter(ListAdapter adapter) {
observableGridView.setAdapter(adapter);
}
@Override
public void onResume() {
super.onResume();
enableViews();
}
@Override
public void enableViews() {
areViewsEnabled = true;
observableGridView.setEnabled(true);
}
@Override
public void disableViews() {
areViewsEnabled = false;
observableGridView.setEnabled(false);
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
public int getY() {
return observableGridView.getCurrentScrollY() + paddingViewHeight;
}
@ -84,10 +122,6 @@ public abstract class AbsViewPagerTabArtistListFragment extends Fragment impleme
return parentActivity;
}
protected void setAdapter(ListAdapter adapter) {
observableGridView.setAdapter(adapter);
}
protected void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
observableGridView.setOnItemClickListener(onItemClickListener);
}
@ -96,17 +130,6 @@ public abstract class AbsViewPagerTabArtistListFragment extends Fragment impleme
observableGridView.setNumColumns(columns);
}
/*
*
* IMPORTANT:
*
* You CAN return null here and use setAdapter(ListAdapter adapter) inside getAdapter() to manually set the adapter.
*
* (i.e. if you must set the adapter async).
*
* */
protected abstract ListAdapter getAdapter();
@Override
public void onScrollChanged(int scrollY, boolean b, boolean b2) {
if (parentActivity instanceof ObservableScrollViewCallbacks) {
@ -125,27 +148,4 @@ public abstract class AbsViewPagerTabArtistListFragment extends Fragment impleme
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
}
@Override
public void disableViews() {
areViewsEnabled = false;
observableGridView.setEnabled(false);
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
@Override
public void enableViews() {
areViewsEnabled = true;
observableGridView.setEnabled(true);
}
@Override
public void onResume() {
super.onResume();
enableViews();
}
}

View file

@ -46,12 +46,6 @@ public class ViewPagerTabArtistAlbumFragment extends AbsViewPagerTabArtistListFr
return adapter;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fab = (FloatingActionButton) getParentActivity().findViewById(R.id.fab);
}
@SuppressWarnings("unchecked")
private void openAlbumDetailsActivityIfPossible(Album album, View albumArtForTransition) {
if (areParentActivitiesViewsEnabled()) {
@ -83,4 +77,10 @@ public class ViewPagerTabArtistAlbumFragment extends AbsViewPagerTabArtistListFr
private boolean areParentActivitiesViewsEnabled() {
return !(getParentActivity() instanceof KabViewsDisableAble) || ((KabViewsDisableAble) getParentActivity()).areViewsEnabled();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fab = (FloatingActionButton) getParentActivity().findViewById(R.id.fab);
}
}

View file

@ -68,6 +68,23 @@ public class AlbumViewFragment extends Fragment implements KabViewsDisableAble,
enableViews();
}
@Override
public void enableViews() {
areViewsEnabled = true;
absListView.setEnabled(true);
}
@Override
public void disableViews() {
areViewsEnabled = false;
absListView.setEnabled(false);
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
private void initViews() {
absListView = (AbsListView) fragmentRootView.findViewById(R.id.absList);
fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
@ -82,11 +99,6 @@ public class AlbumViewFragment extends Fragment implements KabViewsDisableAble,
fillAbsListView(albums);
}
private void setUpAbsListView(String query) {
List<Album> albums = AlbumLoader.getAlbums(getActivity(), query);
fillAbsListView(albums);
}
private void fillAbsListView(List<Album> albums) {
Collections.sort(albums, new AlbumAlphabeticComparator());
AlbumViewGridAdapter albumTileAdapter = new AlbumViewGridAdapter(getActivity(), albums);
@ -144,28 +156,16 @@ public class AlbumViewFragment extends Fragment implements KabViewsDisableAble,
return !(getActivity() instanceof KabViewsDisableAble) || ((KabViewsDisableAble) getActivity()).areViewsEnabled();
}
@Override
public void disableViews() {
areViewsEnabled = false;
absListView.setEnabled(false);
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
@Override
public void enableViews() {
areViewsEnabled = true;
absListView.setEnabled(true);
}
@Override
public void search(String query) {
setUpAbsListView(query);
}
private void setUpAbsListView(String query) {
List<Album> albums = AlbumLoader.getAlbums(getActivity(), query);
fillAbsListView(albums);
}
@Override
public void returnToNonSearch() {
setUpAbsListView();

View file

@ -65,6 +65,23 @@ public class ArtistViewFragment extends Fragment implements KabSearchAbleFragmen
enableViews();
}
@Override
public void enableViews() {
areViewsEnabled = true;
absListView.setEnabled(true);
}
@Override
public void disableViews() {
areViewsEnabled = false;
absListView.setEnabled(false);
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
private void initViews() {
absListView = (AbsListView) fragmentRootView.findViewById(R.id.absList);
}
@ -78,11 +95,6 @@ public class ArtistViewFragment extends Fragment implements KabSearchAbleFragmen
fillAbsListView(artists);
}
private void setUpAbsListView(String query) {
List<Artist> artists = ArtistLoader.getArtists(getActivity(), query);
fillAbsListView(artists);
}
private void fillAbsListView(List<Artist> artists) {
Collections.sort(artists, new ArtistAlphabeticComparator());
ArtistViewListAdapter artistAdapter = new ArtistViewListAdapter(getActivity(), artists);
@ -121,6 +133,11 @@ public class ArtistViewFragment extends Fragment implements KabSearchAbleFragmen
setUpAbsListView(query);
}
private void setUpAbsListView(String query) {
List<Artist> artists = ArtistLoader.getArtists(getActivity(), query);
fillAbsListView(artists);
}
@Override
public void returnToNonSearch() {
setUpAbsListView();
@ -135,21 +152,4 @@ public class ArtistViewFragment extends Fragment implements KabSearchAbleFragmen
private boolean areParentActivityViewsEnabled() {
return !(getActivity() instanceof KabViewsDisableAble) || ((KabViewsDisableAble) getActivity()).areViewsEnabled();
}
@Override
public void enableViews() {
areViewsEnabled = true;
absListView.setEnabled(true);
}
@Override
public void disableViews() {
areViewsEnabled = false;
absListView.setEnabled(false);
}
@Override
public boolean areViewsEnabled() {
return areViewsEnabled;
}
}

View file

@ -66,11 +66,6 @@ public class SongViewFragment extends Fragment implements KabSearchAbleFragment
fillAbsListView(songs);
}
private void setUpAbsListView(String query) {
List<Song> songs = SongLoader.getSongs(getActivity(), query);
fillAbsListView(songs);
}
private void fillAbsListView(final List<Song> songs) {
Collections.sort(songs, new SongAlphabeticComparator());
AbsBaseActivity absBaseActivity = null;
@ -102,6 +97,11 @@ public class SongViewFragment extends Fragment implements KabSearchAbleFragment
setUpAbsListView(query);
}
private void setUpAbsListView(String query) {
List<Song> songs = SongLoader.getSongs(getActivity(), query);
fillAbsListView(songs);
}
@Override
public void returnToNonSearch() {
setUpAbsListView();

View file

@ -56,6 +56,11 @@ public class MusicUtil {
contentResolver.delete(ContentUris.withAppendedId(localUri, albumId), null, null);
}
public static File getAlbumArtFile(Context context, String name)
throws IOException {
return new File(createAlbumArtDir(context), name + System.currentTimeMillis());
}
public static File createAlbumArtDir(Context paramContext) {
File albumArtDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/.albumart/");
if (!albumArtDir.exists()) {
@ -68,9 +73,4 @@ public class MusicUtil {
}
return albumArtDir;
}
public static File getAlbumArtFile(Context context, String name)
throws IOException {
return new File(createAlbumArtDir(context), name + System.currentTimeMillis());
}
}

View file

@ -21,6 +21,8 @@ import com.kabouzeid.materialmusic.misc.AppKeys;
* Created by karim on 12.12.14.
*/
public class Util {
private static int albumArtSize = 600;
public static int resolveDrawable(Context context, int drawable) {
TypedArray a = context.obtainStyledAttributes(new int[]{drawable});
int resId = a.getResourceId(0, 0);
@ -160,8 +162,6 @@ public class Util {
return path;
}
private static int albumArtSize = 600;
public static Bitmap getAlbumArtScaledBitmap(final Bitmap bitmap, boolean keepAspectRatio) {
if (keepAspectRatio) {
double aspectRatio = (double) bitmap.getHeight() / (double) bitmap.getWidth();