2 * Copyright (C) 2014 The CyanogenMod Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com.cyanogenmod.eleven.ui.activities;
18 import android.animation.ArgbEvaluator;
19 import android.animation.ObjectAnimator;
20 import android.content.Intent;
21 import android.graphics.Bitmap;
22 import android.graphics.Color;
23 import android.net.Uri;
24 import android.os.AsyncTask;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.provider.MediaStore;
28 import android.support.v4.app.Fragment;
29 import android.support.v4.app.FragmentManager;
30 import android.support.v4.app.FragmentTransaction;
31 import android.text.TextUtils;
32 import android.util.Log;
33 import android.view.MenuItem;
34 import android.view.Window;
36 import com.cyanogenmod.eleven.Config;
37 import com.cyanogenmod.eleven.R;
38 import com.cyanogenmod.eleven.cache.ImageFetcher;
39 import com.cyanogenmod.eleven.ui.fragments.AlbumDetailFragment;
40 import com.cyanogenmod.eleven.ui.fragments.ArtistDetailFragment;
41 import com.cyanogenmod.eleven.ui.fragments.IChildFragment;
42 import com.cyanogenmod.eleven.ui.fragments.ISetupActionBar;
43 import com.cyanogenmod.eleven.ui.fragments.PlaylistDetailFragment;
44 import com.cyanogenmod.eleven.ui.fragments.RecentFragment;
45 import com.cyanogenmod.eleven.ui.fragments.phone.MusicBrowserPhoneFragment;
46 import com.cyanogenmod.eleven.ui.fragments.profile.LastAddedFragment;
47 import com.cyanogenmod.eleven.ui.fragments.profile.TopTracksFragment;
48 import com.cyanogenmod.eleven.utils.ApolloUtils;
49 import com.cyanogenmod.eleven.utils.BitmapWithColors;
50 import com.cyanogenmod.eleven.utils.MusicUtils;
51 import com.cyanogenmod.eleven.utils.NavUtils;
53 public class HomeActivity extends SlidingPanelActivity implements
54 FragmentManager.OnBackStackChangedListener {
55 private static final String TAG = "HomeActivity";
56 private static final String ACTION_PREFIX = HomeActivity.class.getName();
57 public static final String ACTION_VIEW_ARTIST_DETAILS = ACTION_PREFIX + ".view.ArtistDetails";
58 public static final String ACTION_VIEW_ALBUM_DETAILS = ACTION_PREFIX + ".view.AlbumDetails";
59 public static final String ACTION_VIEW_PLAYLIST_DETAILS = ACTION_PREFIX + ".view.PlaylistDetails";
60 public static final String ACTION_VIEW_SMART_PLAYLIST = ACTION_PREFIX + ".view.SmartPlaylist";
61 public static final String EXTRA_BROWSE_PAGE_IDX = "BrowsePageIndex";
63 private static final String STATE_KEY_BASE_FRAGMENT = "BaseFragment";
65 private static final int NEW_PHOTO = 1;
66 public static final int EQUALIZER = 2;
69 private boolean mLoadedBaseFragment = false;
70 private boolean mHasPendingPlaybackRequest = false;
71 private Handler mHandler = new Handler();
72 private boolean mBrowsePanelActive = true;
75 * Used by the up action to determine how to handle this
77 protected boolean mTopLevelActivity = false;
80 protected void onCreate(Bundle savedInstanceState) {
81 super.onCreate(savedInstanceState);
83 // if we've been launched by an intent, parse it
84 Intent launchIntent = getIntent();
85 boolean intentHandled = false;
86 if (launchIntent != null) {
87 intentHandled = parseIntentForFragment(launchIntent);
90 // if the intent didn't cause us to load a fragment, load the music browse one
91 if (savedInstanceState == null && !mLoadedBaseFragment) {
92 final MusicBrowserPhoneFragment fragment = new MusicBrowserPhoneFragment();
93 if (launchIntent != null) {
94 fragment.setDefaultPageIdx(launchIntent.getIntExtra(EXTRA_BROWSE_PAGE_IDX,
95 MusicBrowserPhoneFragment.INVALID_PAGE_INDEX));
97 getSupportFragmentManager().beginTransaction()
98 .replace(R.id.activity_base_content, fragment)
101 mLoadedBaseFragment = true;
102 mTopLevelActivity = true;
105 getSupportFragmentManager().addOnBackStackChangedListener(this);
107 // if we are resuming from a saved instance state
108 if (savedInstanceState != null) {
109 // track which fragments are loaded and if this is the top level activity
110 mTopLevelActivity = savedInstanceState.getBoolean(STATE_KEY_BASE_FRAGMENT);
111 mLoadedBaseFragment = mTopLevelActivity;
113 // update the action bar based on the top most fragment
114 onBackStackChanged();
116 // figure which panel we are on and update the status bar
117 mBrowsePanelActive = (getCurrentPanel() == Panel.Browse);
118 updateStatusBarColor();
121 // if intent wasn't UI related, process it as a audio playback request
122 if (!intentHandled) {
123 handlePlaybackIntent(launchIntent);
128 protected void onSaveInstanceState(Bundle outState) {
129 super.onSaveInstanceState(outState);
130 outState.putBoolean(STATE_KEY_BASE_FRAGMENT, mTopLevelActivity);
133 public Fragment getTopFragment() {
134 return getSupportFragmentManager().findFragmentById(R.id.activity_base_content);
137 public void postRemoveFragment(final Fragment frag) {
138 mHandler.post(new Runnable() {
141 // removing the fragment doesn't cause the backstack event to be triggered even if
142 // it is the top fragment, so if it is the top fragment, we will just manually
143 // call pop back stack
144 if (frag == getTopFragment()) {
145 getSupportFragmentManager().popBackStack();
147 getSupportFragmentManager().beginTransaction().remove(frag).commit();
154 protected void onNewIntent(Intent intent) {
155 super.onNewIntent(intent);
157 // parse intent to ascertain whether the intent is inter UI communication
158 boolean intentHandled = parseIntentForFragment(intent);
159 // since this activity is marked 'singleTop' (launch mode), an existing activity instance
160 // could be sent media play requests
161 if ( !intentHandled) {
162 handlePlaybackIntent(intent);
167 public void onMetaChanged() {
168 super.onMetaChanged();
169 updateStatusBarColor();
173 protected void onSlide(float slideOffset) {
174 super.onSlide(slideOffset);
176 boolean isInBrowser = getCurrentPanel() == Panel.Browse && slideOffset < 0.7f;
177 if (isInBrowser != mBrowsePanelActive) {
178 mBrowsePanelActive = isInBrowser;
179 updateStatusBarColor();
183 private void updateStatusBarColor() {
184 if (mBrowsePanelActive || MusicUtils.getCurrentAlbumId() < 0) {
185 updateStatusBarColor(getResources().getColor(R.color.primary_dark));
187 new AsyncTask<Void, Void, Integer>() {
189 protected Integer doInBackground(Void... params) {
190 ImageFetcher imageFetcher = ImageFetcher.getInstance(HomeActivity.this);
191 final BitmapWithColors bitmap = imageFetcher.getArtwork(
192 MusicUtils.getAlbumName(), MusicUtils.getCurrentAlbumId(),
193 MusicUtils.getArtistName(), true);
194 return bitmap != null ? bitmap.getVibrantDarkColor() : Color.TRANSPARENT;
197 protected void onPostExecute(Integer color) {
198 if (color == Color.TRANSPARENT) {
199 color = getResources().getColor(R.color.primary_dark);
201 updateStatusBarColor(color);
207 private void updateStatusBarColor(int color) {
208 final Window window = getWindow();
209 ObjectAnimator animator = ObjectAnimator.ofInt(window,
210 "statusBarColor", window.getStatusBarColor(), color);
211 animator.setEvaluator(new ArgbEvaluator());
212 animator.setDuration(300);
216 private boolean parseIntentForFragment(Intent intent) {
217 boolean handled = false;
218 if (intent.getAction() != null) {
219 final String action = intent.getAction();
220 Fragment targetFragment = null;
221 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
223 if (action.equals(ACTION_VIEW_SMART_PLAYLIST)) {
224 long playlistId = intent.getExtras().getLong(Config.SMART_PLAYLIST_TYPE);
225 switch (Config.SmartPlaylistType.getTypeById(playlistId)) {
227 targetFragment = new LastAddedFragment();
230 targetFragment = new RecentFragment();
233 targetFragment = new TopTracksFragment();
236 } else if (action.equals(ACTION_VIEW_PLAYLIST_DETAILS)) {
237 targetFragment = new PlaylistDetailFragment();
238 } else if (action.equals(ACTION_VIEW_ALBUM_DETAILS)) {
239 targetFragment = new AlbumDetailFragment();
240 } else if (action.equals(ACTION_VIEW_ARTIST_DETAILS)) {
241 targetFragment = new ArtistDetailFragment();
244 if (targetFragment != null) {
245 targetFragment.setArguments(intent.getExtras());
246 transaction.setCustomAnimations(0, 0, 0, R.anim.fade_out);
247 // If we ever come back to this because of memory concerns because
248 // none of the fragments are being removed from memory, we can fix this
249 // by using "replace" instead of "add". The caveat is that the performance of
250 // returning to previous fragments is a bit more sluggish because the fragment
251 // view needs to be recreated. If we do remove that, we can remove the back stack
252 // change listener code above
253 transaction.add(R.id.activity_base_content, targetFragment);
254 if (mLoadedBaseFragment) {
255 transaction.addToBackStack(null);
256 showPanel(Panel.Browse);
258 // else mark the fragment as loaded so we don't load the music browse fragment.
259 // this happens when they launch search which is its own activity and then
260 // browse through that back to home activity
261 mLoadedBaseFragment = true;
262 getActionBar().setDisplayHomeAsUpEnabled(true);
264 // the current top fragment is about to be hidden by what we are replacing
265 // it with -- so tell that fragment not to make its action bar menu items visible
266 Fragment oldTop = getTopFragment();
267 if (oldTop != null) {
268 oldTop.setMenuVisibility(false);
271 transaction.commit();
279 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
280 super.onActivityResult(requestCode, resultCode, data);
281 if (requestCode == NEW_PHOTO && !TextUtils.isEmpty(mKey)) {
282 if (resultCode == RESULT_OK) {
283 MusicUtils.removeFromCache(this, mKey);
284 final Uri selectedImage = data.getData();
286 new Thread(new Runnable() {
289 Bitmap bitmap = ImageFetcher.decodeSampledBitmapFromUri(getContentResolver(),
292 ImageFetcher imageFetcher = ApolloUtils.getImageFetcher(HomeActivity.this);
293 imageFetcher.addBitmapToCache(mKey, bitmap);
295 MusicUtils.refresh();
303 * Starts an activity for result that returns an image from the Gallery.
305 public void selectNewPhoto(String key) {
307 // Now open the gallery
308 final Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
309 intent.setType("image/*");
310 startActivityForResult(intent, NEW_PHOTO);
314 public boolean onOptionsItemSelected(final MenuItem item) {
315 switch (item.getItemId()) {
316 case android.R.id.home:
321 return super.onOptionsItemSelected(item);
325 * Navigates to the top Activity and places the view to the correct page
327 protected void navigateToTop() {
328 final Fragment topFragment = getTopFragment();
329 int targetFragmentIndex = MusicBrowserPhoneFragment.INVALID_PAGE_INDEX;
330 if (topFragment instanceof IChildFragment) {
331 targetFragmentIndex = ((IChildFragment)topFragment).getMusicFragmentParent().ordinal();
334 // If we are the top activity in the stack (as determined by the activity that has loaded
335 // the MusicBrowserPhoneFragment) then clear the back stack and move the browse fragment
336 // to the appropriate page as per Android up standards
337 if (mTopLevelActivity) {
339 MusicBrowserPhoneFragment musicFragment = (MusicBrowserPhoneFragment) getTopFragment();
340 musicFragment.setDefaultPageIdx(targetFragmentIndex);
341 showPanel(Panel.Browse);
343 // I've tried all other combinations with parent activities, support.NavUtils and
344 // there is no easy way to achieve what we want that I'm aware of, so clear everything
345 // and jump to the right page
346 NavUtils.goHome(this, targetFragmentIndex);
351 * Immediately clears the backstack
353 protected void clearBackStack() {
354 final FragmentManager fragmentManager = getSupportFragmentManager();
355 if (fragmentManager.getBackStackEntryCount() > 0) {
356 final int id = fragmentManager.getBackStackEntryAt(0).getId();
357 fragmentManager.popBackStackImmediate(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
362 public void handlePendingPlaybackRequests() {
363 if (mHasPendingPlaybackRequest) {
364 Intent unhandledIntent = getIntent();
365 handlePlaybackIntent(unhandledIntent);
370 * Checks whether the passed intent contains a playback request,
371 * and starts playback if that's the case
372 * @return true if the intent was consumed
374 private boolean handlePlaybackIntent(Intent intent) {
376 if (intent == null) {
378 } else if ( !MusicUtils.isPlaybackServiceConnected() ) {
379 mHasPendingPlaybackRequest = true;
383 String mimeType = intent.getType();
384 boolean handled = false;
386 if (MediaStore.Audio.Playlists.CONTENT_TYPE.equals(mimeType)) {
387 long id = parseIdFromIntent(intent, "playlistId", "playlist", -1);
389 MusicUtils.playPlaylist(this, id, false);
392 } else if (MediaStore.Audio.Albums.CONTENT_TYPE.equals(mimeType)) {
393 long id = parseIdFromIntent(intent, "albumId", "album", -1);
395 int position = intent.getIntExtra("position", 0);
396 MusicUtils.playAlbum(this, id, position, false);
399 } else if (MediaStore.Audio.Artists.CONTENT_TYPE.equals(mimeType)) {
400 long id = parseIdFromIntent(intent, "artistId", "artist", -1);
402 int position = intent.getIntExtra("position", 0);
403 MusicUtils.playArtist(this, id, position, false);
408 // reset intent as it was handled as a playback request
410 setIntent(new Intent());
417 private long parseIdFromIntent(Intent intent, String longKey,
418 String stringKey, long defaultId) {
419 long id = intent.getLongExtra(longKey, -1);
421 String idString = intent.getStringExtra(stringKey);
422 if (idString != null) {
424 id = Long.parseLong(idString);
425 } catch (NumberFormatException e) {
426 Log.e(TAG, e.getMessage());
434 public void onBackStackChanged() {
435 Fragment topFragment = getTopFragment();
436 if (topFragment != null) {
437 // the fragment that has come back to the top should now have its menu items
438 // added to the action bar -- so tell it to make it menu items visible
439 topFragment.setMenuVisibility(true);
440 ISetupActionBar setupActionBar = (ISetupActionBar) topFragment;
441 setupActionBar.setupActionBar();
443 getActionBar().setDisplayHomeAsUpEnabled(
444 !(topFragment instanceof MusicBrowserPhoneFragment));