Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.tilak.imusicplay;
- import android.app.Notification;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.BroadcastReceiver;
- import android.content.ContentUris;
- import android.content.Context;
- import android.content.Intent;
- import android.media.AudioAttributes;
- import android.media.AudioFocusRequest;
- import android.media.AudioManager;
- import android.media.MediaPlayer;
- import android.net.Uri;
- import android.os.Binder;
- import android.os.Build;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.PowerManager;
- import android.provider.MediaStore;
- import android.support.annotation.Nullable;
- import android.support.v4.content.LocalBroadcastManager;
- import android.util.Log;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- import java.util.concurrent.TimeUnit;
- import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT;
- import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
- public class MusicService extends Service implements MediaPlayer.OnPreparedListener,MediaPlayer.OnErrorListener,MediaPlayer.OnCompletionListener,AudioManager.OnAudioFocusChangeListener {
- private MediaPlayer player;
- private List<Song> songs;
- private int songposn;
- private final IBinder musicBinder=new MusicBinder();
- private String songTitle="";
- private String songArtist="";
- private static final int NOTIFY_ID=1;
- public static boolean shuffle=false;
- private Random random;
- private boolean repeat=false;
- private List<Integer> shuffleList=new ArrayList<>();
- private AudioManager mAudioManager;
- private AudioAttributes mAudioAttributes;
- private AudioFocusRequest mAudioFocusRequest;
- boolean mPlaybackDelayed = false;
- boolean mPlaybackNowAuthorized = false;
- private final Object mFocusLock = new Object();
- private boolean mResumeOnFocusGain=true;
- @Override
- public void onCreate() {
- super.onCreate();
- random=new Random();
- songposn=0;
- player=new MediaPlayer();
- initMusicPlayer();
- }
- public void setShuffle() {
- shuffle = !shuffle;
- }
- public void initMusicPlayer(){
- player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
- mAudioManager=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
- if(Build.VERSION.SDK_INT<21){
- player.setAudioStreamType(AudioManager.STREAM_MUSIC);
- }else {
- mAudioAttributes= new AudioAttributes.Builder()
- .setUsage(AudioAttributes.USAGE_MEDIA)
- .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
- .build();
- player.setAudioAttributes(mAudioAttributes);
- }
- if(Build.VERSION.SDK_INT>=26){
- mAudioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
- .setAudioAttributes(mAudioAttributes)
- .setAcceptsDelayedFocusGain(true)
- .setOnAudioFocusChangeListener(this)
- .build();
- int res = mAudioManager.requestAudioFocus(mAudioFocusRequest);
- synchronized(mFocusLock) {
- if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
- mPlaybackNowAuthorized = false;
- } else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
- mPlaybackNowAuthorized = true;
- playSong();
- } else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
- mPlaybackDelayed = true;
- mPlaybackNowAuthorized = false;
- }
- }
- } else if(Build.VERSION.SDK_INT<26){
- int result = 0;
- if (mAudioManager != null) {
- result = mAudioManager.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
- }
- if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
- mPlaybackNowAuthorized = true;
- playSong();
- }
- }
- player.setOnPreparedListener(this);
- player.setOnErrorListener(this);
- player.setOnCompletionListener(this);
- }
- public void setSongs(List<Song> songs) {
- this.songs = songs;
- }
- @Override
- public void onAudioFocusChange(int focusChange) {
- if(Build.VERSION.SDK_INT<26){
- if (focusChange == AudioManager.AUDIOFOCUS_LOSS || focusChange == AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
- pausePlayer();
- LocalBroadcastManager.getInstance(MusicService.this).sendBroadcast(new Intent("STOP_THREAD"));
- } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
- playSong();
- }
- }else {
- switch (focusChange) {
- case AudioManager.AUDIOFOCUS_GAIN:
- if (mPlaybackDelayed || mResumeOnFocusGain) {
- synchronized (mFocusLock) {
- mPlaybackDelayed = false;
- mResumeOnFocusGain = false;
- }
- playSong();
- }
- break;
- case AudioManager.AUDIOFOCUS_LOSS:
- synchronized (mFocusLock) {
- mResumeOnFocusGain = false;
- mPlaybackDelayed = false;
- }
- LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("STOP_THREAD"));
- pausePlayer();
- break;
- case AUDIOFOCUS_LOSS_TRANSIENT:
- synchronized (mFocusLock) {
- mResumeOnFocusGain = true;
- mPlaybackDelayed = false;
- }
- LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("STOP_THREAD"));
- pausePlayer();
- break;
- }
- }
- }
- class MusicBinder extends Binder{
- MusicService getService(){
- return MusicService.this;
- }
- }
- @Nullable
- @Override
- public IBinder onBind(Intent intent) {
- return musicBinder;
- }
- @Override
- public void onCompletion(MediaPlayer mediaPlayer) {
- if(mediaPlayer.getCurrentPosition()>0) {
- mediaPlayer.reset();
- playNext();
- }
- }
- @Override
- public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
- mediaPlayer.reset();
- playSong();
- return true;
- }
- @Override
- public void onPrepared(MediaPlayer mediaPlayer) {
- mediaPlayer.start();
- Intent onPreparedIntent=new Intent("MEDIA_PLAYER_PREPARED").putExtra("CURR_SONG",songposn);
- LocalBroadcastManager.getInstance(this).sendBroadcast(onPreparedIntent);
- Intent notintent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- Notification.Builder builder=new Notification.Builder(this);
- PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notintent,PendingIntent.FLAG_UPDATE_CURRENT);
- PendingIntent prevPendingIntent=PendingIntent.getActivity
- (this,1,new Intent().setAction("PREVIOUS"),PendingIntent.FLAG_UPDATE_CURRENT);
- PendingIntent pausePendingIntent=PendingIntent.getActivity
- (this,2,new Intent().setAction("PAUSE"),PendingIntent.FLAG_UPDATE_CURRENT);
- PendingIntent nextPendingIntent=PendingIntent.getActivity
- (this,3,new Intent().setAction("NEXT"),PendingIntent.FLAG_UPDATE_CURRENT);;
- builder.setContentIntent(pendingIntent).setSmallIcon(R.drawable.playicon)
- .addAction(R.drawable.back, "Previous", prevPendingIntent)
- .addAction(R.drawable.playsmall, "Pause", pausePendingIntent)
- .addAction(R.drawable.forw, "Next", nextPendingIntent)
- .setTicker(songArtist)
- .setOngoing(true).setContentTitle(songTitle).setContentText(songArtist);
- Notification not=builder.build();
- startForeground(MusicService.NOTIFY_ID,not);
- }
- public void setSong(int songIndex){
- songposn=songIndex;
- }
- @Override
- public boolean onUnbind(Intent intent) {
- return false;
- }
- public void playSong(){
- player.reset();
- Song songPlay=songs.get(songposn);
- songTitle=songPlay.getTitle();
- songArtist=songPlay.getArtist();
- long currSong=songPlay.getId();
- Uri currUri= ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currSong);
- try {
- player.setDataSource(getApplicationContext(),currUri);
- player.prepare();
- }catch (IOException e){
- e.printStackTrace();
- }catch (IllegalStateException e){
- e.printStackTrace();
- }
- }
- public int getPosn(){
- return player.getCurrentPosition();
- }
- public int getDur(){
- return player.getDuration();
- }
- public boolean isPng(){
- return player.isPlaying();
- }
- public void pausePlayer(){
- if(player.isPlaying())
- player.pause();
- }
- public void seek(int posn){
- player.seekTo(posn);
- }
- public void go(){
- player.start();
- }
- public void playPrev(){
- songposn--;
- if(songposn<=0)songposn=songs.size()-1;
- playSong();
- }
- public void playNext(){
- if(shuffle){
- do{
- songposn=random.nextInt(this.songs.size());
- if(!shuffleList.contains(songposn)){
- shuffleList.add(songposn);
- repeat= false;
- }else {
- repeat=true;
- }
- }while (repeat);
- }else {
- songposn++;
- if(songposn>=songs.size())
- songposn=0;
- }
- playSong();
- }
- @Override
- public void onDestroy() {
- repeat=false;
- clearShuffle();
- if(Build.VERSION.SDK_INT>=26)
- mAudioManager.abandonAudioFocusRequest(mAudioFocusRequest);
- else mAudioManager.abandonAudioFocus(this);
- stopForeground(true);
- }
- public void clearShuffle(){
- shuffleList.clear();
- }
- public class NotificationReciever extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.e("here","here");
- String action=intent.getAction();
- if(action!=null){
- switch (action){
- case "PREVIOUS":{
- playPrev();
- break;
- }
- case "PAUSE":{
- pausePlayer();
- LocalBroadcastManager.getInstance(MusicService.this).sendBroadcast(new Intent("STOP_THREAD"));
- break;
- }
- case "NEXT":{
- playNext();
- break;
- }
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment