Java tutorial
/* * </summary> * Source File : HomeActivity.java * Project : Sarigama * Owner : Kasun * </summary> * * <license> * Copyright 2016 Kasun Gunathilaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </license> */ package com.kasungunathilaka.sarigama.ui; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.animation.TranslateAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RemoteViews; import android.widget.TextView; import com.kasungunathilaka.sarigama.R; import com.kasungunathilaka.sarigama.domain.Song; import com.kasungunathilaka.sarigama.fragment.ArtistDetailFragment; import com.kasungunathilaka.sarigama.fragment.ConnectionFailFragment; import com.kasungunathilaka.sarigama.fragment.ContentFragment; import com.kasungunathilaka.sarigama.fragment.IFragmentCommunicator; import com.kasungunathilaka.sarigama.fragment.MainFragment; import com.kasungunathilaka.sarigama.fragment.PlayerFragment; import com.kasungunathilaka.sarigama.fragment.SearchFragment; import com.kasungunathilaka.sarigama.service.PlayerService; import com.kasungunathilaka.sarigama.util.PlayerQueue; import java.io.IOException; import java.io.InputStream; import java.net.URL; import de.hdodenhof.circleimageview.CircleImageView; public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IFragmentCommunicator { public static final String FRAGMENT_NAME = "fragment_name"; public static final String ROOT_FRAGMENT_SONG = "ROOT_FRAGMENT_SONG"; public static final String ROOT_FRAGMENT_ARTIST = "ROOT_FRAGMENT_ARTIST"; public static final String ROOT_FRAGMENT_SEARCH = "ROOT_FRAGMENT_SEARCH"; public static final String TYPE_SONG = "TYPE_SONG"; public static final String TYPE_ARTIST = "TYPE_ARTIST"; public final static String ON_PLAY = "com.kasungunathilaka.sarigama.ON_PLAY"; public final static String ON_PAUSE = "com.kasungunathilaka.sarigama.ON_PAUSE"; public final static String ON_PREPARED = "com.kasungunathilaka.sarigama.ON_PREPARED"; public final static String ON_PREPARING = "com.kasungunathilaka.sarigama.ON_PREPARING"; public final static String ON_COMPLETED = "com.kasungunathilaka.sarigama.ON_COMPLETED"; public final static String ON_PLAYER_EXIT = "com.kasungunathilaka.sarigama.ON_PLAYER_EXIT"; public final static String ON_PLAYER_ENTER = "com.kasungunathilaka.sarigama.ON_PLAYER_ENTER"; public final static String ON_PREPARE_ERROR = "com.kasungunathilaka.sarigama.ON_PREPARE_ERROR"; public final static String ON_ADDED_TO_QUEUE = "com.kasungunathilaka.sarigama.ON_ADDED_TO_QUEUE"; public final static String ON_QUEUE_COMPLETED = "com.kasungunathilaka.sarigama.ON_QUEUE_COMPLETED"; public final static String ON_SAME_ADDED_TO_QUEUE = "com.kasungunathilaka.sarigama.ON_SAME_ADDED_TO_QUEUE"; public final static String ON_CURRENT_POSITION_CHANGED = "com.kasungunathilaka.sarigama.ON_CURRENT_POSITION_CHANGED"; public final static String PLAYER_FRAGMENT_LAUNCH_MODE = "com.kasungunathilaka.sarigama.PLAYER_FRAGMENT_LAUNCH_MODE"; public final static String PLAYER_FRAGMENT_LAUNCH_MODE_NEW_QUEUE = "com.kasungunathilaka.sarigama.PLAYER_FRAGMENT_LAUNCH_MODE_NEW_QUEUE"; public final static String PLAYER_FRAGMENT_LAUNCH_MODE_MINI_PLAYER = "com.kasungunathilaka.sarigama.PLAYER_FRAGMENT_LAUNCH_MODE_MINI_PLAYER"; public static final String ACTION_PLAY = "com.kasungunathilaka.sarigama.play"; public static final String ACTION_PREV = "com.kasungunathilaka.sarigama.prev"; public static final String ACTION_NEXT = "com.kasungunathilaka.sarigama.next"; public static final String ACTION_BRING_FRONT = "com.kasungunathilaka.sarigama.ACTION_BRING_FRONT"; public static final String NOTIFICATION_TYPE_PLAY = "com.kasungunathilaka.sarigama.NOTIFICATION_TYPE_PLAY"; public static final String NOTIFICATION_TYPE_PAUSE = "com.kasungunathilaka.sarigama.NOTIFICATION_TYPE_PAUSE"; public static final String NOTIFICATION_TYPE_DISMISS = "com.kasungunathilaka.sarigama.NOTIFICATION_TYPE_DISMISS"; boolean isBound = false; PlayerService playerService; BroadcastReceiver broadcastReceiver; FrameLayout flMiniPlayer; FrameLayout flPlay, flMiniPb; TextView tvSongTitle, tvSongArtist; CircleImageView ibPlay; ImageButton ivNext; CardView cvMiniPlayer; PlayerQueue playerQueue; private MusicIntentReceiver myReceiver; public boolean isCanceled; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); myReceiver = new MusicIntentReceiver(); flMiniPlayer = (FrameLayout) findViewById(R.id.flMiniPlayer); flPlay = (FrameLayout) findViewById(R.id.flPlay); flMiniPb = (FrameLayout) findViewById(R.id.flMiniPb); cvMiniPlayer = (CardView) findViewById(R.id.cvMiniPlayer); tvSongTitle = (TextView) findViewById(R.id.tvSongTitle); tvSongArtist = (TextView) findViewById(R.id.tvSongArtist); ibPlay = (CircleImageView) findViewById(R.id.ibPlay); ivNext = (ImageButton) findViewById(R.id.ivNext); playerQueue = PlayerQueue.getInstance(HomeActivity.this); setFragment(new MainFragment()); if (playerService != null && playerService.isPlaying()) { int position = playerQueue.getCurrentPosition(); Song currentSong = playerQueue.getSongByPosition(position); setupMiniPlayer(currentSong.getSongTitle(), currentSong.getSongArtist()); showMiniPlayer(true); } broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case ON_PLAYER_EXIT: if (playerService.isPlaying()) { ibPlay.setImageResource(R.drawable.ic_pause_white); showMiniPlayer(true); } else { ibPlay.setImageResource(R.drawable.ic_play_white); if (!isCanceled) { showMiniPlayer(true); } else { isCanceled = false; } } break; case ON_PLAYER_ENTER: showMiniPlayer(false); break; case ON_PREPARING: flMiniPb.setVisibility(flMiniPlayer.getVisibility() == View.VISIBLE ? View.VISIBLE : View.GONE); break; case ON_PREPARED: flMiniPb.setVisibility(View.GONE); int position = playerQueue.getCurrentPosition(); Song currentSong = playerQueue.getSongByPosition(position); setupMiniPlayer(currentSong.getSongTitle(), currentSong.getSongArtist()); ibPlay.setImageResource(R.drawable.ic_pause_white); break; case ON_COMPLETED: ibPlay.setImageResource(R.drawable.ic_play_white); break; } } }; cvMiniPlayer.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Bundle bundle = new Bundle(); bundle.putString(HomeActivity.PLAYER_FRAGMENT_LAUNCH_MODE, HomeActivity.PLAYER_FRAGMENT_LAUNCH_MODE_MINI_PLAYER); PlayerFragment playerFragment = new PlayerFragment(); playerFragment.setData(bundle); setFragment(playerFragment); } return true; } }); ivNext.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { playerService.next(); } return true; } }); flPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (playerService.isPlaying()) { ibPlay.setImageResource(R.drawable.ic_play_white); playerService.setPlayPause(); } else { ibPlay.setImageResource(R.drawable.ic_pause_white); playerService.setPlayPause(); } } }); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { super.onBackPressed(); } else { moveTaskToBack(true); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_home, menu); MenuItem item = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) item.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow( (null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); ContentFragment contentFragment = new ContentFragment(); contentFragment.setContentType(ROOT_FRAGMENT_SEARCH, query); setFragment(contentFragment); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; case R.id.action_search: setFragment(new SearchFragment()); break; case R.id.action_about_developer: AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(HomeActivity.this); View dialogView = getLayoutInflater().inflate(R.layout.dialog_view_about_developer, null); alertDialogBuilder.setView(dialogView); ImageView ivClose = (ImageView) dialogView.findViewById(R.id.ivClose); TextView tvEmail = (TextView) dialogView.findViewById(R.id.tvEmail); final AlertDialog alertDialog = alertDialogBuilder.create(); tvEmail.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "developer.kasun.gunathilaka@gmail.com" }); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sarigama"); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, ""); startActivity(emailIntent); alertDialog.dismiss(); } return false; } }); ivClose.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { alertDialog.dismiss(); } return false; } }); alertDialog.show(); break; case R.id.action_exit: finish(); NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notificationManager.cancel(9999); System.exit(0); break; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { ContentFragment contentFragment; int id = item.getItemId(); if (id == R.id.nav_music) { contentFragment = new ContentFragment(); contentFragment.setContentType(ROOT_FRAGMENT_SONG, null); setFragment(contentFragment); } else if (id == R.id.nav_artist) { contentFragment = new ContentFragment(); contentFragment.setContentType(ROOT_FRAGMENT_ARTIST, null); setFragment(contentFragment); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } protected void setFragment(Fragment fragment) { String backStateName = fragment.getClass().getName(); String fragmentTag = backStateName; android.support.v4.app.FragmentManager manager = getSupportFragmentManager(); boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0); if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) { //fragment not in back stack, create it. android.support.v4.app.FragmentTransaction ft = manager.beginTransaction(); if (backStateName.contentEquals(PlayerFragment.class.getName())) { ft.setCustomAnimations(R.anim.slide_in_below, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_below); } else if (backStateName.contentEquals(MainFragment.class.getName())) { ft.setCustomAnimations(android.R.anim.fade_in, R.anim.slide_out_right); } else if (backStateName.contentEquals(ConnectionFailFragment.class.getName())) { ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); } else { ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right); } ft.replace(R.id.fragment_layout, fragment, fragmentTag); if (!backStateName.contentEquals(MainFragment.class.getName())) { ft.addToBackStack(backStateName); } ft.commit(); } } @Override public void fragmentData(Bundle bundle) { switch (bundle.getString(FRAGMENT_NAME)) { case "ArtistDetailFragment": ArtistDetailFragment artistDetailFragment = new ArtistDetailFragment(); artistDetailFragment.setData(bundle); setFragment(artistDetailFragment); break; case "PlayerFragment": PlayerFragment playerFragment = new PlayerFragment(); playerFragment.setData(bundle); setFragment(playerFragment); break; case "ConnectionFailFragment": ConnectionFailFragment connectionFailFragment = new ConnectionFailFragment(); setFragment(connectionFailFragment); break; } } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, PlayerService.class); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PLAY)); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PAUSE)); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PREPARED)); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_COMPLETED)); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PREPARING)); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PLAYER_ENTER)); LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PLAYER_EXIT)); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } @Override protected void onResume() { IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); registerReceiver(myReceiver, filter); registerReceiver(myReceiver, new IntentFilter(ACTION_PLAY)); registerReceiver(myReceiver, new IntentFilter(ACTION_BRING_FRONT)); registerReceiver(myReceiver, new IntentFilter(ACTION_NEXT)); registerReceiver(myReceiver, new IntentFilter(ACTION_PREV)); super.onResume(); } @Override public void onActivityReenter(int resultCode, Intent data) { super.onActivityReenter(resultCode, data); } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { PlayerService.PlayerBinder binder = (PlayerService.PlayerBinder) service; playerService = binder.getService(); isBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { isBound = false; } }; public PlayerService getPlayerService() { return playerService; } @Override protected void onDestroy() { super.onDestroy(); if (isBound) { unbindService(serviceConnection); isBound = false; } } private void showMiniPlayer(boolean show) { if (show) { TranslateAnimation animate = new TranslateAnimation(0, 0, flMiniPlayer.getHeight(), 0); animate.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime)); flMiniPlayer.startAnimation(animate); flMiniPlayer.setVisibility(View.VISIBLE); } else { TranslateAnimation animate = new TranslateAnimation(0, 0, 0, flMiniPlayer.getHeight()); animate.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime)); flMiniPlayer.startAnimation(animate); flMiniPlayer.setVisibility(View.GONE); } flMiniPlayer.setVisibility(show ? View.VISIBLE : View.GONE); } public void setupMiniPlayer(String songTitle, String songArtist) { tvSongTitle.setText(songTitle); tvSongArtist.setText(songArtist); } private class MusicIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case Intent.ACTION_HEADSET_PLUG: int state = intent.getIntExtra("state", -1); switch (state) { case 0: ibPlay.setImageResource(R.drawable.ic_play_white); if (playerService != null && playerService.isPlaying()) { playerService.setPlayPause(); } break; } break; } } } }