org.FrancoisDescamps.CatPlayer.MusicService.java Source code

Java tutorial

Introduction

Here is the source code for org.FrancoisDescamps.CatPlayer.MusicService.java

Source

/*
 * Copyright (C) 2016 Franois Descamps <francois-descamps@mailoo.org>
 *
 * This file is part of CatPlayer.
 *
 * CatPlayer 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 program 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.FrancoisDescamps.CatPlayer;

import android.app.*;
import android.content.*;
import android.media.*;
import android.os.*;
import android.support.v4.app.NotificationCompat;

import org.FrancoisDescamps.CatPlayer.Objects.Music;

import java.util.ArrayList;
import java.util.Collections;

public class MusicService extends Service {
    private final IBinder mBinder = new LocalBinder();
    MediaPlayer mp;
    ArrayList<Music> queu;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    NotificationManager manager;
    Notification builder;
    String currentTitle, currentAlbum, currentArtist, currentPath;
    Music initialQueu[];
    String properties[][];

    int positionOfInitialMusic, repeat, cpt = 0;
    boolean alea = false, musicAsChanged = false;

    @Override
    public IBinder onBind(Intent intent) {
        //Rcuprer les prferences concernant repeat et alea
        preferences = getSharedPreferences("File", MODE_PRIVATE);
        alea = preferences.getBoolean("alea", false);
        repeat = preferences.getInt("repeat", 2);

        return mBinder;
    }

    public void playMusic(final String pathToMusic) {
        //register receiver
        IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        HeadphonesUnplugReceiver receiver = new HeadphonesUnplugReceiver();
        registerReceiver(receiver, receiverFilter);

        if (mp != null) {
            mp.stop();
            mp = null;
        }

        try {
            mp = new MediaPlayer();
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDataSource(pathToMusic);
            mp.prepare();
            mp.start();
        } catch (Exception e) {
            /*NOP*/
        }

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                switch (repeat) {
                case 0: // Lecture en boucle dsactive
                    /* NOP */
                    break;
                case 1: // Lecture en boucle d'une seule musique
                    playMusic(pathToMusic);
                    break;
                case 2: // Lecture en boucle de toutes les musiques
                    if (positionOfInitialMusic + cpt + 1 == queu.size()) {
                        cpt = 0;
                        positionOfInitialMusic = 0;
                    } else {
                        cpt++;
                    }
                    playMusic(queu.get(positionOfInitialMusic + cpt).getPath());
                    break;
                }

                currentTitle = properties[0][positionOfInitialMusic + cpt];
                currentAlbum = properties[1][positionOfInitialMusic + cpt];
                currentArtist = properties[2][positionOfInitialMusic + cpt];
                currentPath = properties[3][positionOfInitialMusic + cpt];

                musicAsChanged = true;
                MainActivity.notifyOtherMusicStarted();
                buildNotification(true);

                //save "cpt"
                editor = preferences.edit();
                editor.putInt("cpt", cpt);

                if (Build.VERSION.SDK_INT < 9) {
                    editor.commit();
                } else {
                    editor.apply();
                }
            }
        });
    }

    public void buildNotification(boolean isPlaying) {
        Intent mainIntent = new Intent(this, MainActivity.class);
        Intent pauseIntent = new Intent(this, PauseNotificationReceiver.class);
        Intent nextIntent = new Intent(this, NextNotificationReceiver.class);
        Intent prevIntent = new Intent(this, prevNotificationReceiver.class);
        PendingIntent mainPendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
                mainIntent, 0);
        PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(),
                pauseIntent, 0);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(),
                nextIntent, 0);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(),
                prevIntent, 0);

        if (isPlaying) {
            builder = new NotificationCompat.Builder(this).setContentTitle(currentTitle)
                    .setContentText(currentAlbum).setSmallIcon(R.drawable.ic_titles)
                    .setContentIntent(mainPendingIntent)
                    .addAction(R.drawable.ic_prev_notif, getString(R.string.previous), prevPendingIntent)
                    .addAction(R.drawable.ic_pause_notif, getString(R.string.pause), pausePendingIntent)
                    .addAction(R.drawable.ic_next_notif, getString(R.string.next), nextPendingIntent).build();

            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(0, builder);
        } else {
            builder = new NotificationCompat.Builder(this).setContentTitle(currentTitle)
                    .setContentText(currentAlbum).setSmallIcon(R.drawable.ic_titles)
                    .setContentIntent(mainPendingIntent)
                    .addAction(R.drawable.ic_prev_notif, getString(R.string.previous), prevPendingIntent)
                    .addAction(R.drawable.ic_play_notif, getString(R.string.play), pausePendingIntent)
                    .addAction(R.drawable.ic_next_notif, getString(R.string.next), nextPendingIntent).build();

            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(0, builder);
        }
    }

    public void playPrevMusic() {
        //tester si la musique est dmare depuis moins de secondes
        if (mp.getCurrentPosition() < 5000) {
            //tester si la musique en cours est la premire de la queu
            if (positionOfInitialMusic + cpt == 0) {
                cpt = queu.size() - 1;
                positionOfInitialMusic = 0;
            } else {
                cpt--;
            }
        }
        playMusic(queu.get(positionOfInitialMusic + cpt).getPath());

        currentTitle = properties[0][positionOfInitialMusic + cpt];
        currentAlbum = properties[1][positionOfInitialMusic + cpt];
        currentArtist = properties[2][positionOfInitialMusic + cpt];
        currentPath = properties[3][positionOfInitialMusic + cpt];

        buildNotification(true);
    }

    public void playNextMusic() {
        //tester si la musique en cours est la dernire de la queu
        if (positionOfInitialMusic + cpt == queu.size() - 1) {
            cpt = 0;
            positionOfInitialMusic = 0;
        } else {
            cpt++;
        }
        playMusic(queu.get(positionOfInitialMusic + cpt).getPath());

        currentTitle = queu.get(positionOfInitialMusic + cpt).getTitle();
        currentAlbum = queu.get(positionOfInitialMusic + cpt).getAlbum();
        currentArtist = queu.get(positionOfInitialMusic + cpt).getArtist();
        currentPath = queu.get(positionOfInitialMusic + cpt).getPath();

        buildNotification(true);

    }

    public void notifyAleaValueChanged() {
        if (mp != null) {
            if (alea) {
                initialQueu = new Music[queu.size()];

                //sauvegarder la queu
                for (int cpt = 0; cpt < queu.size(); cpt++) {
                    initialQueu[cpt] = queu.get(cpt);
                }

                //sauvegarder la musique initiale
                Music initialMusic = queu.get(positionOfInitialMusic);

                //enlever la musique initiale de la liste
                queu.remove(positionOfInitialMusic);

                Collections.shuffle(queu);

                queu.add(positionOfInitialMusic, initialMusic);
            } else {
                //clear shuffled musics in queu
                queu.clear();

                for (int cpt = 0; cpt < initialQueu.length; cpt++) {
                    queu.add(cpt, initialQueu[cpt]);
                }
            }
        }
    }

    public void pauseMusic() {
        mp.pause();
        buildNotification(false);
    }

    public void resumeMusic() {
        mp.start();
        buildNotification(true);
    }

    public boolean isPlaying() {
        if (mp != null) {
            return mp.isPlaying();
        } else {
            return false;
        }
    }

    public boolean isMediaPlayerInitialized() {
        return mp != null;
    }

    public int getCurrentPositionOfMusic() {
        if (mp == null) {
            return 0;
        } else {
            return mp.getCurrentPosition();
        }
    }

    public int getDurationOfMusic() {
        if (mp != null) {
            return mp.getDuration();
        } else {
            return 1000;
        }
    }

    public void seekTo(int newTime) {
        if (mp != null) {
            mp.seekTo(newTime);
        }
    }

    public void playMusicFromQueu(int positionOfInitialMusic) {
        cpt = 0;

        playMusic(queu.get(positionOfInitialMusic).getPath());

        currentTitle = queu.get(positionOfInitialMusic + cpt).getTitle();
        currentAlbum = queu.get(positionOfInitialMusic + cpt).getAlbum();
        currentArtist = queu.get(positionOfInitialMusic + cpt).getArtist();
        currentPath = queu.get(positionOfInitialMusic + cpt).getPath();

        buildNotification(true);

        //save "queu" and "positionOfInitialMusic"
        editor = preferences.edit();
        editor.putInt("queuLenght", queu.size());
        for (int cpt = 0; cpt < queu.size(); cpt++) {
            editor.putString("properties[0][" + cpt + "]", queu.get(cpt).getTitle());
            editor.putString("properties[1][" + cpt + "]", queu.get(cpt).getAlbum());
            editor.putString("properties[2][" + cpt + "]", queu.get(cpt).getArtist());
            editor.putString("properties[3][" + cpt + "]", queu.get(cpt).getPath());
        }

        editor.putInt("positionOfInitialMusic", positionOfInitialMusic);
        editor.putInt("cpt", cpt);

        if (Build.VERSION.SDK_INT < 9) {
            editor.commit();
        } else {
            editor.apply();
        }
    }

    public void setQueuAndPlayMusic(String properties[][], int positionOfCurrentMusic) {
        this.properties = properties;
        positionOfInitialMusic = positionOfCurrentMusic;

        queu = new ArrayList<Music>();
        queu.clear();

        for (cpt = 0; cpt < properties[0].length; cpt++) {
            //New instance of "Music"
            Music m = new Music(properties[0][cpt], properties[1][cpt], properties[2][cpt], properties[3][cpt]);

            queu.add(cpt, m);
        }

        cpt = 0;

        if (alea) {

            initialQueu = new Music[queu.size()];

            //sauvegarder la queu
            for (int cpt = 0; cpt < queu.size(); cpt++) {
                initialQueu[cpt] = queu.get(cpt);
            }

            //sauvegarder le chemin d'acces de la musique initiale
            Music initialMusic = queu.get(positionOfInitialMusic);

            //enlever la musique initiale de la liste
            queu.remove(positionOfInitialMusic);

            Collections.shuffle(queu);

            queu.add(positionOfInitialMusic, initialMusic);
        }
        playMusic(properties[3][positionOfInitialMusic]);

        currentTitle = properties[0][positionOfInitialMusic + cpt];
        currentAlbum = properties[1][positionOfInitialMusic + cpt];
        currentArtist = properties[2][positionOfInitialMusic + cpt];
        currentPath = properties[3][positionOfInitialMusic + cpt];

        buildNotification(true);

        //save "queu" and "positionOfInitialMusic"
        editor = preferences.edit();
        editor.putInt("queuLenght", queu.size());
        for (int cpt = 0; cpt < queu.size(); cpt++) {
            editor.putString("properties[0][" + cpt + "]", queu.get(cpt).getTitle());
            editor.putString("properties[1][" + cpt + "]", queu.get(cpt).getAlbum());
            editor.putString("properties[2][" + cpt + "]", queu.get(cpt).getArtist());
            editor.putString("properties[3][" + cpt + "]", queu.get(cpt).getPath());
        }

        editor.putInt("positionOfInitialMusic", positionOfInitialMusic);
        editor.putInt("cpt", cpt);

        if (Build.VERSION.SDK_INT < 9) {
            editor.commit();
        } else {
            editor.apply();
        }
    }

    public class LocalBinder extends Binder {
        MusicService getService() {
            return MusicService.this;
        }
    }
}