Java tutorial
/* * Copyright (C) 2015 Naman Dwivedi * * Licensed under the GNU General Public License v3 * * This is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. */ package com.musiqueplayer.playlistequalizerandroidwear.activities; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.view.ContextThemeWrapper; import android.text.Html; import android.text.SpannableString; import android.text.util.Linkify; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.afollestad.appthemeengine.customizers.ATEActivityThemeCustomizer; import com.anjlab.android.iab.v3.BillingProcessor; import com.musiqueplayer.playlistequalizerandroidwear.MusicPlayer; import com.musiqueplayer.playlistequalizerandroidwear.R; import com.musiqueplayer.playlistequalizerandroidwear.TimeService; import com.musiqueplayer.playlistequalizerandroidwear.fragments.AlbumDetailFragment; import com.musiqueplayer.playlistequalizerandroidwear.fragments.ArtistDetailFragment; import com.musiqueplayer.playlistequalizerandroidwear.fragments.FoldersFragment; import com.musiqueplayer.playlistequalizerandroidwear.fragments.MainFragment; import com.musiqueplayer.playlistequalizerandroidwear.fragments.PlaylistFragment; import com.musiqueplayer.playlistequalizerandroidwear.fragments.QueueFragment; import com.musiqueplayer.playlistequalizerandroidwear.fragments.TimerFragment; import com.musiqueplayer.playlistequalizerandroidwear.permissions.Nammu; import com.musiqueplayer.playlistequalizerandroidwear.permissions.PermissionCallback; import com.musiqueplayer.playlistequalizerandroidwear.slidinguppanel.SlidingUpPanelLayout; import com.musiqueplayer.playlistequalizerandroidwear.utils.Constants; import com.musiqueplayer.playlistequalizerandroidwear.utils.NavigationUtils; import com.musiqueplayer.playlistequalizerandroidwear.utils.TimberUtils; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.HashMap; import java.util.Map; public class MainActivity extends BaseActivity implements ATEActivityThemeCustomizer { private static MainActivity sMainActivity; SlidingUpPanelLayout panelLayout; NavigationView navigationView; TextView songtitle, songartist; ImageView albumart; String action; Map<String, Runnable> navigationMap = new HashMap<String, Runnable>(); Handler navDrawerRunnable = new Handler(); Runnable runnable; Runnable navigateLibrary = new Runnable() { public void run() { navigationView.getMenu().findItem(R.id.nav_library).setChecked(true); Fragment fragment = new MainFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, fragment).commitAllowingStateLoss(); } }; Runnable navigateNowplaying = new Runnable() { public void run() { navigateLibrary.run(); startActivity(new Intent(MainActivity.this, NowPlayingActivity.class)); } }; final PermissionCallback permissionReadstorageCallback = new PermissionCallback() { @Override public void permissionGranted() { loadEverything(); } @Override public void permissionRefused() { finish(); } }; Runnable navigatePlaylist = new Runnable() { public void run() { navigationView.getMenu().findItem(R.id.nav_playlists).setChecked(true); Fragment fragment = new PlaylistFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.hide(getSupportFragmentManager().findFragmentById(R.id.fragment_container)); transaction.replace(R.id.fragment_container, fragment).commit(); } }; Runnable navigateFolder = new Runnable() { public void run() { navigationView.getMenu().findItem(R.id.nav_folders).setChecked(true); Fragment fragment = new FoldersFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.hide(getSupportFragmentManager().findFragmentById(R.id.fragment_container)); transaction.replace(R.id.fragment_container, fragment).commit(); } }; Runnable navigateQueue = new Runnable() { public void run() { navigationView.getMenu().findItem(R.id.nav_queue).setChecked(true); Fragment fragment = new QueueFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.hide(getSupportFragmentManager().findFragmentById(R.id.fragment_container)); transaction.replace(R.id.fragment_container, fragment).commit(); } }; Runnable navigateTimer = new Runnable() { public void run() { navigationView.getMenu().findItem(R.id.nav_timer).setChecked(true); Fragment fragment = new TimerFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.hide(getSupportFragmentManager().findFragmentById(R.id.fragment_container)); transaction.replace(R.id.fragment_container, fragment).commit(); } }; Runnable navigateAlbum = new Runnable() { public void run() { long albumID = getIntent().getExtras().getLong(Constants.ALBUM_ID); Fragment fragment = AlbumDetailFragment.newInstance(albumID, false, null); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit(); } }; Runnable navigateArtist = new Runnable() { public void run() { long artistID = getIntent().getExtras().getLong(Constants.ARTIST_ID); Fragment fragment = ArtistDetailFragment.newInstance(artistID, false, null); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit(); } }; private DrawerLayout mDrawerLayout; private boolean isDarkTheme; public static MainActivity getInstance() { return sMainActivity; } @Override public void onCreate(Bundle savedInstanceState) { sMainActivity = this; action = getIntent().getAction(); AppRater.app_launched(this); isDarkTheme = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("dark_theme", true); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); navigationMap.put(Constants.NAVIGATE_LIBRARY, navigateLibrary); navigationMap.put(Constants.NAVIGATE_PLAYLIST, navigatePlaylist); navigationMap.put(Constants.NAVIGATE_QUEUE, navigateQueue); navigationMap.put(Constants.NAVIGATE_NOWPLAYING, navigateNowplaying); navigationMap.put(Constants.NAVIGATE_TIMER, navigateTimer); navigationMap.put(Constants.NAVIGATE_ALBUM, navigateAlbum); navigationMap.put(Constants.NAVIGATE_ARTIST, navigateArtist); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); panelLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout); navigationView = (NavigationView) findViewById(R.id.nav_view); View header = navigationView.inflateHeaderView(R.layout.nav_header); albumart = (ImageView) header.findViewById(R.id.album_art); songtitle = (TextView) header.findViewById(R.id.song_title); songartist = (TextView) header.findViewById(R.id.song_artist); setPanelSlideListeners(panelLayout); navDrawerRunnable.postDelayed(new Runnable() { @Override public void run() { setupDrawerContent(navigationView); setupNavigationIcons(navigationView); } }, 700); if (TimberUtils.isMarshmallow()) { checkPermissionAndThenLoad(); } else { loadEverything(); } addBackstackListener(); if (Intent.ACTION_VIEW.equals(action)) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { MusicPlayer.clearQueue(); MusicPlayer.openFile(getIntent().getData().getPath()); stopService(new Intent(getApplicationContext(), TimeService.class)); if (!MusicPlayer.isPlaying()) { startService(new Intent(getApplicationContext(), TimeService.class)); } MusicPlayer.playOrPause(); navigateNowplaying.run(); } }, 350); } } private void loadEverything() { Runnable navigation = navigationMap.get(action); if (navigation != null) { navigation.run(); } else { navigateLibrary.run(); } new initQuickControls().execute(""); } private void checkPermissionAndThenLoad() { //check for permission if (Nammu.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) { loadEverything(); } else { if (Nammu.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { Snackbar.make(panelLayout, "Timber will need to read external storage to display songs on your device.", Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener() { @Override public void onClick(View view) { Nammu.askForPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE, permissionReadstorageCallback); } }).show(); } else { Nammu.askForPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE, permissionReadstorageCallback); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { if (isNavigatingMain()) { mDrawerLayout.openDrawer(GravityCompat.START); } else super.onBackPressed(); return true; } } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (panelLayout.isPanelExpanded()) { panelLayout.collapsePanel(); } else if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(final MenuItem menuItem) { updatePosition(menuItem); return true; } }); } private void setupNavigationIcons(NavigationView navigationView) { //material-icon-lib currently doesn't work with navigationview of design support library 22.2.0+ //set icons manually for now //https://github.com/code-mc/material-icon-lib/issues/15 if (!isDarkTheme) { navigationView.getMenu().findItem(R.id.nav_library).setIcon(R.drawable.library_music); navigationView.getMenu().findItem(R.id.nav_playlists).setIcon(R.drawable.playlist_play); navigationView.getMenu().findItem(R.id.nav_queue).setIcon(R.drawable.music_note); navigationView.getMenu().findItem(R.id.nav_folders).setIcon(R.drawable.ic_folder_open_black_24dp); navigationView.getMenu().findItem(R.id.nav_nowplaying).setIcon(R.drawable.bookmark_music); navigationView.getMenu().findItem(R.id.nav_timer).setIcon(R.drawable.clock); navigationView.getMenu().findItem(R.id.nav_settings).setIcon(R.drawable.settings); navigationView.getMenu().findItem(R.id.nav_about).setIcon(R.drawable.information); } else { navigationView.getMenu().findItem(R.id.nav_library).setIcon(R.drawable.library_music_white); navigationView.getMenu().findItem(R.id.nav_playlists).setIcon(R.drawable.playlist_play_white); navigationView.getMenu().findItem(R.id.nav_queue).setIcon(R.drawable.music_note_white); navigationView.getMenu().findItem(R.id.nav_timer).setIcon(R.drawable.clock); navigationView.getMenu().findItem(R.id.nav_folders).setIcon(R.drawable.ic_folder_open_white_24dp); navigationView.getMenu().findItem(R.id.nav_nowplaying).setIcon(R.drawable.bookmark_music_white); navigationView.getMenu().findItem(R.id.nav_settings).setIcon(R.drawable.settings_white); navigationView.getMenu().findItem(R.id.nav_about).setIcon(R.drawable.information_white); } try { if (!BillingProcessor.isIabServiceAvailable(this)) { } } catch (Exception e) { e.printStackTrace(); } } private void updatePosition(final MenuItem menuItem) { runnable = null; switch (menuItem.getItemId()) { case R.id.nav_library: runnable = navigateLibrary; break; case R.id.nav_playlists: runnable = navigatePlaylist; break; case R.id.nav_folders: runnable = navigateFolder; break; case R.id.nav_nowplaying: NavigationUtils.navigateToNowplaying(MainActivity.this, false); break; case R.id.nav_queue: runnable = navigateQueue; break; case R.id.nav_timer: runnable = navigateTimer; break; case R.id.nav_settings: NavigationUtils.navigateToSettings(MainActivity.this); break; case R.id.nav_about: mDrawerLayout.closeDrawers(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { final String APP_PNAME = "com.musiqueplayer.playlistequalizerandroidwear"; final Context mContext = getApplicationContext(); final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( new ContextThemeWrapper(MainActivity.this, R.style.myDialog)); final SpannableString s = new SpannableString( Html.fromHtml("Thanks for downloading Music Player.<br>" + "Thanks for being an awesome user! If you enjoy using <b>Music Player</b> app, please take a moment to rate it with <b>5 stars</b>. " + "")); Linkify.addLinks(s, Linkify.ALL); alertDialogBuilder.setTitle("About"); alertDialogBuilder.setMessage(s); alertDialogBuilder.setPositiveButton("Rate Now", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { mContext.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME))); } }); alertDialogBuilder.setNegativeButton("Remind Later", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0); SharedPreferences.Editor editor = prefs.edit(); editor.putLong("launch_count", 0); editor.commit(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }, 350); break; } if (runnable != null) { menuItem.setChecked(true); mDrawerLayout.closeDrawers(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { runnable.run(); } }, 350); } } public void setDetailsToHeader() { String name = MusicPlayer.getTrackName(); String artist = MusicPlayer.getArtistName(); if (name != null && artist != null) { songtitle.setText(name); songartist.setText(artist); } /*ImageLoader.getInstance().displayImage(TimberUtils.getAlbumArtUri(MusicPlayer.getCurrentAlbumId()).toString(), albumart, new DisplayImageOptions.Builder().cacheInMemory(true) .showImageOnFail(R.drawable.icons) .resetViewBeforeLoading(true) .build());*/ } @Override public void onMetaChanged() { super.onMetaChanged(); setDetailsToHeader(); } @Override public void onResume() { super.onResume(); sMainActivity = this; } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Nammu.onRequestPermissionsResult(requestCode, permissions, grantResults); } private boolean isNavigatingMain() { Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); return (currentFragment instanceof MainFragment || currentFragment instanceof QueueFragment || currentFragment instanceof TimerFragment || currentFragment instanceof PlaylistFragment || currentFragment instanceof FoldersFragment); } private void addBackstackListener() { getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { getSupportFragmentManager().findFragmentById(R.id.fragment_container).onResume(); } }); } @Override public int getActivityTheme() { return isDarkTheme ? R.style.AppThemeNormalDark : R.style.AppThemeNormalLight; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); getSupportFragmentManager().findFragmentById(R.id.fragment_container).onActivityResult(requestCode, resultCode, data); } }