forked from mrizky-kur/Redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainActivity.java
636 lines (531 loc) · 23.7 KB
/
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package com.iven.musicplayergo;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v4.graphics.ColorUtils;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.iven.musicplayergo.adapters.AlbumsAdapter;
import com.iven.musicplayergo.adapters.ArtistsAdapter;
import com.iven.musicplayergo.adapters.ColorsAdapter;
import com.iven.musicplayergo.adapters.SongsAdapter;
import com.iven.musicplayergo.loaders.ArtistProvider;
import com.iven.musicplayergo.models.Album;
import com.iven.musicplayergo.models.Artist;
import com.iven.musicplayergo.models.Song;
import com.iven.musicplayergo.playback.EqualizerUtils;
import com.iven.musicplayergo.playback.MusicNotificationManager;
import com.iven.musicplayergo.playback.MusicService;
import com.iven.musicplayergo.playback.PlaybackInfoListener;
import com.iven.musicplayergo.playback.PlayerAdapter;
import com.iven.musicplayergo.slidinguppanel.SlidingUpPanelLayout;
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView;
import java.util.List;
public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<List<Artist>>, SongsAdapter.SongSelectedListener, ColorsAdapter.AccentChangedListener, AlbumsAdapter.AlbumSelectedListener, ArtistsAdapter.ArtistSelectedListener {
private LinearLayoutManager mArtistsLayoutManager;
private int mAccent;
private boolean sThemeInverted;
private FastScrollRecyclerView mArtistsRecyclerView;
private RecyclerView mAlbumsRecyclerView, mSongsRecyclerView;
private AlbumsAdapter mAlbumsAdapter;
private SongsAdapter mSongsAdapter;
private TextView mPlayingAlbum, mPlayingSong, mDuration, mSongPosition, mArtistAlbumCount, mSelectedAlbum;
private SeekBar mSeekBarAudio;
private LinearLayout mControlsContainer;
private View mSettingsView, mPlayerInfoView;
private SlidingUpPanelLayout mSlidingUpPanel;
private ImageButton mPlayPauseButton, mResetButton, mEqButton;
private PlayerAdapter mPlayerAdapter;
private boolean mUserIsSeeking = false;
private List<Artist> mArtists;
private String mSelectedArtist;
private boolean sExpandPanel = false;
private boolean sPlayerInfoLongPressed = false;
private MusicService mMusicService;
private PlaybackListener mPlaybackListener;
private MusicNotificationManager mMusicNotificationManager;
private final ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mMusicService = ((MusicService.LocalBinder) iBinder).getInstance();
mPlayerAdapter = mMusicService.getMediaPlayerHolder();
mMusicNotificationManager = mMusicService.getMusicNotificationManager();
mMusicNotificationManager.setAccentColor(mAccent);
if (mPlaybackListener == null) {
mPlaybackListener = new PlaybackListener();
mPlayerAdapter.setPlaybackInfoListener(mPlaybackListener);
}
checkReadStoragePermissions();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mMusicService = null;
}
};
private boolean mIsBound;
private Parcelable savedRecyclerLayoutState;
@Override
public void onPause() {
super.onPause();
if (mArtistsLayoutManager != null) {
savedRecyclerLayoutState = mArtistsLayoutManager.onSaveInstanceState();
}
if (mPlayerAdapter != null && mPlayerAdapter.isMediaPlayer()) {
mPlayerAdapter.onPauseActivity();
}
if (mSettingsView.getVisibility() == View.VISIBLE) {
showSettings(false);
}
}
@Override
public void onAccentChanged(int color) {
mMusicNotificationManager.setAccentColor(color);
if (mPlayerAdapter.isMediaPlayer()) {
mMusicNotificationManager.getNotificationManager().notify(MusicNotificationManager.NOTIFICATION_ID, mMusicNotificationManager.createNotification());
}
Utils.setThemeAccent(this, color);
}
@Override
public void onBackPressed() {
//if the sliding up panel is expanded collapse it
if (mSlidingUpPanel.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED) {
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else if (mSettingsView.getVisibility() == View.VISIBLE) {
closeSettings(mSettingsView);
} else {
super.onBackPressed();
}
}
private void checkReadStoragePermissions() {
if (Utils.isMarshmallow()) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
showPermissionRationale();
} else {
onPermissionGranted();
}
} else {
onPermissionGranted();
}
}
@TargetApi(23)
private void showPermissionRationale() {
AlertDialog builder = new AlertDialog.Builder(this).create();
builder.setIcon(R.drawable.ic_folder);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.perm_rationale));
builder.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final int READ_FILES_CODE = 2588;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}
, READ_FILES_CODE);
}
});
builder.setCanceledOnTouchOutside(false);
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
showPermissionRationale();
} else {
onPermissionGranted();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sThemeInverted = Utils.isThemeInverted(this);
mAccent = Utils.getAccent(this);
Utils.setTheme(this, sThemeInverted, mAccent);
setContentView(R.layout.main_activity);
getViews();
initializeSettings();
setupSlidingUpPanel();
initializeSeekBar();
doBindService();
}
private void getViews() {
mSlidingUpPanel = findViewById(R.id.sliding_panel);
mControlsContainer = findViewById(R.id.controls_container);
mControlsContainer.setBackgroundColor(ColorUtils.setAlphaComponent(ContextCompat.getColor(this, mAccent), 10));
mPlayerInfoView = findViewById(R.id.player_info);
setupPlayerInfoView();
mPlayPauseButton = findViewById(R.id.play_pause);
mResetButton = findViewById(R.id.replay);
mSeekBarAudio = findViewById(R.id.seekTo);
mPlayingSong = findViewById(R.id.playing_song);
mPlayingAlbum = findViewById(R.id.playing_album);
mDuration = findViewById(R.id.duration);
mSongPosition = findViewById(R.id.song_position);
mArtistAlbumCount = findViewById(R.id.artist_album_count);
mSelectedAlbum = findViewById(R.id.selected_disc);
mArtistsRecyclerView = findViewById(R.id.artists_rv);
mArtistsRecyclerView.setTrackColor(ColorUtils.setAlphaComponent(ContextCompat.getColor(this, mAccent), sThemeInverted ? 15 : 30));
mAlbumsRecyclerView = findViewById(R.id.albums_rv);
mSongsRecyclerView = findViewById(R.id.songs_rv);
mSettingsView = findViewById(R.id.settings_view);
mEqButton = findViewById(R.id.eq);
}
private void setupPlayerInfoView() {
mPlayerInfoView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (!sPlayerInfoLongPressed) {
mPlayingSong.setSelected(true);
mPlayingAlbum.setSelected(true);
sPlayerInfoLongPressed = true;
}
return true;
}
});
mPlayerInfoView.setOnTouchListener(new View.OnTouchListener() {
@Override
@SuppressLint("ClickableViewAccessibility")
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (sPlayerInfoLongPressed) {
mPlayingSong.setSelected(false);
mPlayingAlbum.setSelected(false);
sPlayerInfoLongPressed = false;
}
}
return false;
}
});
}
private void setupSlidingUpPanel() {
final ViewTreeObserver observer = mControlsContainer.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mSlidingUpPanel.setupSlidingUpPanel(mSongsRecyclerView, Gravity.BOTTOM, mControlsContainer.getHeight());
mSettingsView.setMinimumHeight(mControlsContainer.getHeight());
mControlsContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
private void initializeSettings() {
if (!EqualizerUtils.hasEqualizer(this)) {
mEqButton.getDrawable().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN);
}
mSettingsView.setBackgroundColor(ColorUtils.setAlphaComponent(ContextCompat.getColor(this, mAccent), 20));
initializeColorsSettings();
}
public void showSettings(View v) {
showSettings(true);
}
public void closeSettings(View v) {
showSettings(false);
}
private void setArtistsRecyclerView(List<Artist> data) {
mArtistsLayoutManager = new LinearLayoutManager(this);
mArtistsRecyclerView.setLayoutManager(mArtistsLayoutManager);
ArtistsAdapter artistsAdapter = new ArtistsAdapter(this, data);
mArtistsRecyclerView.setAdapter(artistsAdapter);
if (savedRecyclerLayoutState != null) {
mArtistsLayoutManager.onRestoreInstanceState(savedRecyclerLayoutState);
}
}
private void initializeSeekBar() {
mSeekBarAudio.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
final int currentPositionColor = mSongPosition.getCurrentTextColor();
int userSelectedPosition = 0;
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
mUserIsSeeking = true;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
userSelectedPosition = progress;
mSongPosition.setTextColor(ContextCompat.getColor(MainActivity.this, mAccent));
}
mSongPosition.setText(Song.formatDuration(progress));
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mUserIsSeeking) {
mSongPosition.setTextColor(currentPositionColor);
}
mUserIsSeeking = false;
mPlayerAdapter.seekTo(userSelectedPosition);
}
});
}
public void reset(View v) {
if (checkIsPlayer()) {
mPlayerAdapter.reset();
updateResetStatus(false);
}
}
public void skipPrev(View v) {
if (checkIsPlayer()) {
mPlayerAdapter.instantReset();
}
}
public void resumeOrPause(View v) {
if (checkIsPlayer()) {
mPlayerAdapter.resumeOrPause();
}
}
public void skipNext(View v) {
if (checkIsPlayer()) {
mPlayerAdapter.skip(true);
}
}
public void openEqualizer(View v) {
if (EqualizerUtils.hasEqualizer(this)) {
if (checkIsPlayer()) {
mPlayerAdapter.openEqualizer(MainActivity.this);
}
} else {
Toast.makeText(this, getString(R.string.no_eq), Toast.LENGTH_SHORT).show();
}
}
public void openGitPage(View v) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://deepcrazyworld.com")));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, getString(R.string.no_browser), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private boolean checkIsPlayer() {
boolean isPlayer = mPlayerAdapter.isMediaPlayer();
if (!isPlayer) {
EqualizerUtils.notifyNoSessionId(this);
}
return isPlayer;
}
public void switchTheme(View v) {
//avoid service killing when the player is in paused state
if (mPlayerAdapter != null && mPlayerAdapter.getState() == PlaybackInfoListener.State.PAUSED) {
mMusicService.startForeground(MusicNotificationManager.NOTIFICATION_ID, mMusicService.getMusicNotificationManager().createNotification());
mMusicService.setRestoredFromPause(true);
}
Utils.invertTheme(this);
}
private void showSettings(boolean show) {
int settingsVisibility = show ? View.VISIBLE : View.GONE;
int controlsVisibility = show ? View.GONE : View.VISIBLE;
mControlsContainer.setVisibility(controlsVisibility);
mSettingsView.setVisibility(settingsVisibility);
}
private void initializeColorsSettings() {
RecyclerView colorsRecyclerView = mSettingsView.findViewById(R.id.colors_rv);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
colorsRecyclerView.setLayoutManager(linearLayoutManager);
colorsRecyclerView.setAdapter(new ColorsAdapter(this, mAccent));
}
private void onPermissionGranted() {
getSupportLoaderManager().initLoader(ArtistProvider.ARTISTS_LOADER, null, this);
}
private void updateResetStatus(boolean onPlaybackCompletion) {
int themeColor = sThemeInverted ? Color.WHITE : Color.BLACK;
int color = onPlaybackCompletion ? themeColor : mPlayerAdapter.isReset() ? ContextCompat.getColor(this, mAccent) : themeColor;
mResetButton.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
private void updatePlayingStatus() {
int drawable = mPlayerAdapter.getState() != PlaybackInfoListener.State.PAUSED ? R.drawable.ic_pause : R.drawable.ic_play;
mPlayPauseButton.setImageResource(drawable);
}
private void updatePlayingInfo(boolean restore, boolean startPlay) {
if (startPlay) {
mPlayerAdapter.getMediaPlayer().start();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mMusicService.startForeground(MusicNotificationManager.NOTIFICATION_ID, mMusicNotificationManager.createNotification());
}
}, 250);
}
final Song selectedSong = mPlayerAdapter.getCurrentSong();
mSelectedArtist = selectedSong.artistName;
final int duration = selectedSong.duration;
mSeekBarAudio.setMax(duration);
mDuration.setText(Song.formatDuration(duration));
Spanned spanned = Utils.buildSpanned(getString(R.string.playing_song, mSelectedArtist, selectedSong.title));
mPlayingSong.setText(spanned);
mPlayingAlbum.setText(selectedSong.albumName);
if (restore) {
mSeekBarAudio.setProgress(mPlayerAdapter.getPlayerPosition());
updatePlayingStatus();
updateResetStatus(false);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//stop foreground if coming from pause state
if (mMusicService.isRestoredFromPause()) {
mMusicService.stopForeground(false);
mMusicService.getMusicNotificationManager().getNotificationManager().notify(MusicNotificationManager.NOTIFICATION_ID, mMusicService.getMusicNotificationManager().getNotificationBuilder().build());
mMusicService.setRestoredFromPause(false);
}
}
}, 250);
}
}
private void restorePlayerStatus() {
mSeekBarAudio.setEnabled(mPlayerAdapter.isMediaPlayer());
//if we are playing and the activity was restarted
//update the controls panel
if (mPlayerAdapter != null && mPlayerAdapter.isMediaPlayer()) {
mPlayerAdapter.onResumeActivity();
updatePlayingInfo(true, false);
}
}
private void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(this,
MusicService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
Intent startNotStickyIntent = new Intent(this, MusicService.class);
startService(startNotStickyIntent);
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
@Override
@NonNull
public Loader<List<Artist>> onCreateLoader(int id, Bundle args) {
return new ArtistProvider.AsyncArtistLoader(this);
}
@Override
public void onLoadFinished(@NonNull Loader<List<Artist>> loader, List<Artist> artists) {
if (artists.isEmpty()) {
Toast.makeText(this, getString(R.string.error_no_music), Toast.LENGTH_SHORT)
.show();
finish();
} else {
mArtists = artists;
setArtistsRecyclerView(mArtists);
mSelectedArtist = mPlayerAdapter.getSelectedAlbum() != null ? mPlayerAdapter.getSelectedAlbum().getArtistName() : mArtists.get(0).getName();
setArtistDetails(ArtistProvider.getArtist(mArtists, mSelectedArtist).albums);
}
}
private void setArtistDetails(List<Album> albums) {
if (mAlbumsAdapter != null) {
//only notify recycler view of item changed if an adapter already exists
mAlbumsAdapter.swapArtist(albums);
} else {
LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mAlbumsRecyclerView.setLayoutManager(horizontalLayoutManager);
mAlbumsAdapter = new AlbumsAdapter(this, albums, mPlayerAdapter, ContextCompat.getColor(this, mAccent));
mAlbumsRecyclerView.setAdapter(mAlbumsAdapter);
}
int albumCount = albums.size();
mArtistAlbumCount.setText(getString(R.string.albums, mSelectedArtist, albumCount));
if (sExpandPanel) {
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
sExpandPanel = false;
} else {
restorePlayerStatus();
}
}
@Override
public void onLoaderReset(@NonNull Loader loader) {
}
@Override
protected void onDestroy() {
super.onDestroy();
mPlaybackListener = null;
doUnbindService();
}
@Override
public void onSongSelected(Song song, Album album) {
if (!mSeekBarAudio.isEnabled()) {
mSeekBarAudio.setEnabled(true);
}
mPlayerAdapter.setCurrentSong(song, album.songs);
mPlayerAdapter.initMediaPlayer();
}
@Override
public void onArtistSelected(String artist) {
if (!mSelectedArtist.equals(artist)) {
//make the panel expandable
sExpandPanel = true;
mPlayerAdapter.setSelectedAlbum(null);
//load artist albums only if not already loaded
mSelectedArtist = artist;
setArtistDetails(ArtistProvider.getArtist(mArtists, mSelectedArtist).albums);
} else {
//if already loaded expand the panel
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
}
}
@Override
public void onAlbumSelected(Album album) {
mSelectedAlbum.setText(album.getTitle());
mPlayerAdapter.setSelectedAlbum(album);
if (mSongsAdapter != null) {
mSongsAdapter.swapSongs(album);
} else {
LinearLayoutManager songsLayoutManager = new LinearLayoutManager(this);
mSongsRecyclerView.setLayoutManager(songsLayoutManager);
mSongsAdapter = new SongsAdapter(this, album);
mSongsRecyclerView.setAdapter(mSongsAdapter);
}
}
public class PlaybackListener extends PlaybackInfoListener {
@Override
public void onPositionChanged(int position) {
if (!mUserIsSeeking) {
mSeekBarAudio.setProgress(position);
}
}
@Override
public void onStateChanged(@State int state) {
updatePlayingStatus();
if (mPlayerAdapter.getState() != State.RESUMED && mPlayerAdapter.getState() != State.PAUSED) {
updatePlayingInfo(false, true);
}
}
@Override
public void onPlaybackCompleted() {
updateResetStatus(true);
}
}
}