Guest User

Untitled

a guest
Dec 18th, 2017
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.40 KB | None | 0 0
  1. package com.example.tilak.imusicplay;
  2.  
  3. import android.app.Notification;
  4. import android.app.PendingIntent;
  5. import android.app.Service;
  6. import android.content.BroadcastReceiver;
  7. import android.content.ContentUris;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.media.AudioAttributes;
  11. import android.media.AudioFocusRequest;
  12. import android.media.AudioManager;
  13. import android.media.MediaPlayer;
  14. import android.net.Uri;
  15. import android.os.Binder;
  16. import android.os.Build;
  17. import android.os.Handler;
  18. import android.os.IBinder;
  19. import android.os.PowerManager;
  20. import android.provider.MediaStore;
  21. import android.support.annotation.Nullable;
  22. import android.support.v4.content.LocalBroadcastManager;
  23. import android.util.Log;
  24.  
  25. import java.io.IOException;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Random;
  29. import java.util.concurrent.TimeUnit;
  30.  
  31. import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT;
  32. import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
  33.  
  34.  
  35. public class MusicService extends Service  implements  MediaPlayer.OnPreparedListener,MediaPlayer.OnErrorListener,MediaPlayer.OnCompletionListener,AudioManager.OnAudioFocusChangeListener {
  36.     private MediaPlayer player;
  37.     private List<Song> songs;
  38.     private int songposn;
  39.     private final IBinder musicBinder=new MusicBinder();
  40.     private String songTitle="";
  41.     private String songArtist="";
  42.     private static final int NOTIFY_ID=1;
  43.     public static boolean shuffle=false;
  44.     private Random random;
  45.     private boolean repeat=false;
  46.     private List<Integer> shuffleList=new ArrayList<>();
  47.     private AudioManager mAudioManager;
  48.     private AudioAttributes mAudioAttributes;
  49.     private AudioFocusRequest mAudioFocusRequest;
  50.     boolean mPlaybackDelayed = false;
  51.     boolean mPlaybackNowAuthorized = false;
  52.     private final Object mFocusLock = new Object();
  53.     private boolean mResumeOnFocusGain=true;
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.     @Override
  61.     public void onCreate() {
  62.         super.onCreate();
  63.         random=new Random();
  64.         songposn=0;
  65.         player=new MediaPlayer();
  66.         initMusicPlayer();
  67.     }
  68.  
  69.     public void setShuffle() {
  70.         shuffle = !shuffle;
  71.     }
  72.  
  73.     public void initMusicPlayer(){
  74.         player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
  75.         mAudioManager=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
  76.         if(Build.VERSION.SDK_INT<21){
  77.             player.setAudioStreamType(AudioManager.STREAM_MUSIC);
  78.         }else  {
  79.             mAudioAttributes= new AudioAttributes.Builder()
  80.                     .setUsage(AudioAttributes.USAGE_MEDIA)
  81.                     .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
  82.                     .build();
  83.             player.setAudioAttributes(mAudioAttributes);
  84.  
  85.         }
  86.  
  87.  
  88.         if(Build.VERSION.SDK_INT>=26){
  89.             mAudioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
  90.                     .setAudioAttributes(mAudioAttributes)
  91.                     .setAcceptsDelayedFocusGain(true)
  92.                     .setOnAudioFocusChangeListener(this)
  93.                     .build();
  94.             int res = mAudioManager.requestAudioFocus(mAudioFocusRequest);
  95.             synchronized(mFocusLock) {
  96.                 if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
  97.                     mPlaybackNowAuthorized = false;
  98.                 } else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
  99.                     mPlaybackNowAuthorized = true;
  100.                     playSong();
  101.                 } else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
  102.                     mPlaybackDelayed = true;
  103.                     mPlaybackNowAuthorized = false;
  104.                 }
  105.             }
  106.  
  107.         } else if(Build.VERSION.SDK_INT<26){
  108.             int result = 0;
  109.             if (mAudioManager != null) {
  110.                 result = mAudioManager.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
  111.             }
  112.  
  113.             if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
  114.                 mPlaybackNowAuthorized = true;
  115.                 playSong();
  116.             }
  117.         }
  118.  
  119.         player.setOnPreparedListener(this);
  120.         player.setOnErrorListener(this);
  121.         player.setOnCompletionListener(this);
  122.     }
  123.  
  124.  
  125.  
  126.     public void setSongs(List<Song> songs) {
  127.         this.songs = songs;
  128.     }
  129.  
  130.     @Override
  131.     public void onAudioFocusChange(int focusChange) {
  132.         if(Build.VERSION.SDK_INT<26){
  133.             if (focusChange == AudioManager.AUDIOFOCUS_LOSS || focusChange == AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
  134.                 pausePlayer();
  135.                 LocalBroadcastManager.getInstance(MusicService.this).sendBroadcast(new Intent("STOP_THREAD"));
  136.             } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
  137.                 playSong();
  138.             }
  139.         }else {
  140.             switch (focusChange) {
  141.                 case AudioManager.AUDIOFOCUS_GAIN:
  142.                     if (mPlaybackDelayed || mResumeOnFocusGain) {
  143.                         synchronized (mFocusLock) {
  144.                             mPlaybackDelayed = false;
  145.                             mResumeOnFocusGain = false;
  146.                         }
  147.                         playSong();
  148.                     }
  149.                     break;
  150.                 case AudioManager.AUDIOFOCUS_LOSS:
  151.                     synchronized (mFocusLock) {
  152.                         mResumeOnFocusGain = false;
  153.                         mPlaybackDelayed = false;
  154.                     }
  155.                     LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("STOP_THREAD"));
  156.                     pausePlayer();
  157.                     break;
  158.                 case AUDIOFOCUS_LOSS_TRANSIENT:
  159.                     synchronized (mFocusLock) {
  160.                         mResumeOnFocusGain = true;
  161.                         mPlaybackDelayed = false;
  162.                     }
  163.                     LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("STOP_THREAD"));
  164.                     pausePlayer();
  165.                     break;
  166.             }
  167.         }
  168.     }
  169.  
  170.     class MusicBinder extends Binder{
  171.         MusicService getService(){
  172.             return MusicService.this;
  173.         }
  174.     }
  175.  
  176.     @Nullable
  177.     @Override
  178.     public IBinder onBind(Intent intent) {
  179.         return musicBinder;
  180.     }
  181.  
  182.     @Override
  183.     public void onCompletion(MediaPlayer mediaPlayer) {
  184.         if(mediaPlayer.getCurrentPosition()>0) {
  185.             mediaPlayer.reset();
  186.             playNext();
  187.         }
  188.  
  189.     }
  190.  
  191.     @Override
  192.     public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
  193.         mediaPlayer.reset();
  194.         playSong();
  195.         return true;
  196.     }
  197.  
  198.     @Override
  199.     public void onPrepared(MediaPlayer mediaPlayer) {
  200.         mediaPlayer.start();
  201.         Intent onPreparedIntent=new Intent("MEDIA_PLAYER_PREPARED").putExtra("CURR_SONG",songposn);
  202.         LocalBroadcastManager.getInstance(this).sendBroadcast(onPreparedIntent);
  203.         Intent notintent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  204.         Notification.Builder builder=new Notification.Builder(this);
  205.         PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notintent,PendingIntent.FLAG_UPDATE_CURRENT);
  206.         PendingIntent prevPendingIntent=PendingIntent.getActivity
  207.                 (this,1,new Intent().setAction("PREVIOUS"),PendingIntent.FLAG_UPDATE_CURRENT);
  208.         PendingIntent pausePendingIntent=PendingIntent.getActivity
  209.                 (this,2,new Intent().setAction("PAUSE"),PendingIntent.FLAG_UPDATE_CURRENT);
  210.         PendingIntent nextPendingIntent=PendingIntent.getActivity
  211.                 (this,3,new Intent().setAction("NEXT"),PendingIntent.FLAG_UPDATE_CURRENT);;
  212.         builder.setContentIntent(pendingIntent).setSmallIcon(R.drawable.playicon)
  213.                 .addAction(R.drawable.back, "Previous", prevPendingIntent)
  214.                 .addAction(R.drawable.playsmall, "Pause", pausePendingIntent)
  215.                 .addAction(R.drawable.forw, "Next", nextPendingIntent)
  216.                 .setTicker(songArtist)
  217.                 .setOngoing(true).setContentTitle(songTitle).setContentText(songArtist);
  218.  
  219.         Notification not=builder.build();
  220.         startForeground(MusicService.NOTIFY_ID,not);
  221.     }
  222.  
  223.     public void setSong(int songIndex){
  224.         songposn=songIndex;
  225.     }
  226.  
  227.  
  228.  
  229.     @Override
  230.     public boolean onUnbind(Intent intent) {
  231.         return false;
  232.     }
  233.  
  234.  
  235.     public void playSong(){
  236.         player.reset();
  237.         Song songPlay=songs.get(songposn);
  238.         songTitle=songPlay.getTitle();
  239.         songArtist=songPlay.getArtist();
  240.  
  241.         long currSong=songPlay.getId();
  242.  
  243.         Uri currUri= ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currSong);
  244.         try {
  245.             player.setDataSource(getApplicationContext(),currUri);
  246.             player.prepare();
  247.         }catch (IOException e){
  248.             e.printStackTrace();
  249.         }catch (IllegalStateException e){
  250.             e.printStackTrace();
  251.         }
  252.     }
  253.  
  254.     public int getPosn(){
  255.         return player.getCurrentPosition();
  256.     }
  257.  
  258.     public int getDur(){
  259.         return player.getDuration();
  260.     }
  261.  
  262.     public boolean isPng(){
  263.         return player.isPlaying();
  264.     }
  265.  
  266.     public void pausePlayer(){
  267.         if(player.isPlaying())
  268.             player.pause();
  269.     }
  270.  
  271.     public void seek(int posn){
  272.         player.seekTo(posn);
  273.     }
  274.  
  275.     public void go(){
  276.         player.start();
  277.     }
  278.  
  279.     public void playPrev(){
  280.         songposn--;
  281.         if(songposn<=0)songposn=songs.size()-1;
  282.         playSong();
  283.     }
  284.  
  285.     public void playNext(){
  286.         if(shuffle){
  287.             do{
  288.  
  289.                 songposn=random.nextInt(this.songs.size());
  290.                 if(!shuffleList.contains(songposn)){
  291.                     shuffleList.add(songposn);
  292.                     repeat= false;
  293.                 }else {
  294.                     repeat=true;
  295.                 }
  296.             }while (repeat);
  297.         }else {
  298.             songposn++;
  299.             if(songposn>=songs.size())
  300.                 songposn=0;
  301.         }
  302.         playSong();
  303.     }
  304.  
  305.  
  306.     @Override
  307.     public void onDestroy() {
  308.         repeat=false;
  309.         clearShuffle();
  310.         if(Build.VERSION.SDK_INT>=26)
  311.             mAudioManager.abandonAudioFocusRequest(mAudioFocusRequest);
  312.         else mAudioManager.abandonAudioFocus(this);
  313.         stopForeground(true);
  314.     }
  315.  
  316.     public void clearShuffle(){
  317.         shuffleList.clear();
  318.     }
  319.  
  320.  
  321.  
  322.     public class NotificationReciever extends BroadcastReceiver{
  323.         @Override
  324.         public void onReceive(Context context, Intent intent) {
  325.             Log.e("here","here");
  326.            String action=intent.getAction();
  327.            if(action!=null){
  328.                switch (action){
  329.                    case "PREVIOUS":{
  330.                        playPrev();
  331.                        break;
  332.                    }
  333.                    case "PAUSE":{
  334.                        pausePlayer();
  335.                        LocalBroadcastManager.getInstance(MusicService.this).sendBroadcast(new Intent("STOP_THREAD"));
  336.                        break;
  337.                    }
  338.                    case "NEXT":{
  339.                        playNext();
  340.                        break;
  341.                    }
  342.                }
  343.            }
  344.         }
  345.     }
  346. }
Add Comment
Please, Sign In to add comment