0

I'm trying to implement a service to play a stream in background using mediaplayer class.. anyway in some phone (galaxy tab and some LG model) when my app is in background, the sound chops when I open another application... why this? following some tutorial I implemented the service in this way:

import com.somafm.api.PlayListFile;
import com.somafm.api.Playlist;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

public class PlayerBackgroundService extends Service {

    static MediaPlayer.OnPreparedListener prepared_listener;
    static MediaPlayer.OnBufferingUpdateListener buffering_listener;
    static MediaPlayer.OnCompletionListener completion_listener;
    static MediaPlayer.OnErrorListener error_listener;

    private static Playlist playlist;
    private static PlayerController player;
    private static StreamProxy proxy;
    private static MediaPlayer mp = new MediaPlayer();

    static boolean canPlay;
    static boolean clean;
    static boolean cancelRequest;
    static boolean buffering;
    static boolean isPlaying;

    private static PowerManager.WakeLock powerLock;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        init();
    }

    public void init()
    {
        PowerManager pM = (PowerManager) getSystemService(Context.POWER_SERVICE);
        powerLock = pM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Prevent sleeping");
        powerLock.acquire();

        prepared_listener = new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                canPlay = true;
                clean = true;
            }
        };

        error_listener = new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.i("!!MEDIAERROR!!", "WHAT " + what + " - " + extra);
                canPlay = true;
                clean = false;
                isPlaying = false;
                return true;
            }
        };

        buffering_listener = new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i("BUFFERING", "" + percent);
                if(percent > 0)
                {
                    if(mp.isPlaying() && !buffering)
                    {
                        player.notifyAllBuffering();
                        buffering = true;
                    }
                }
                else
                {
                    if(buffering)
                    {
                        player.notifyAllNotBuffering();
                        buffering = false;
                    }
                }
            }
        };

        completion_listener = new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                //stop();
                Log.i("COMPLETED", "COMPLETED");
            }
        };

    }

    public synchronized static void start(){
        mp.start();
        isPlaying = true;
    }

    public synchronized static void prepare(){

        canPlay = false;
        clean = true;

        proxy = new StreamProxy();
        proxy.init();
        proxy.start();

        if (playlist == null)
        {
            clean = false;
            proxy.stop();
            return;
        }

        int i = 0;

        String proxyUrl = "";

        playlist.fetchContent();
        PlayListFile[] urlsToPlay = playlist.getFiles();

        if (urlsToPlay == null)
        {
            clean = false;
            proxy.stop();
            return;
        }

        if (urlsToPlay.length == 0)
        {
            clean = false;
            proxy.stop();
            return;
        }

        do{
            try{

                proxyUrl = String.format("http://127.0.0.1:%d/%s", proxy
                        .getPort(), Uri.parse(urlsToPlay[i].getUrl()));
                i++;
                Log.i("Trying link", "" + urlsToPlay.length);
                mp = new MediaPlayer();
                mp.setOnPreparedListener(prepared_listener);
                mp.setOnBufferingUpdateListener(buffering_listener);
                mp.setOnErrorListener(error_listener);
                mp.setOnCompletionListener(completion_listener);
                mp.setDataSource(proxyUrl);
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp.prepare();


            }catch(Exception ex)
            {
                clean = false;                 
                ex.printStackTrace();
            }

            if(cancelRequest == true)
            {
                clean = true;
                return;
            }

            if(i >= urlsToPlay.length)
                canPlay = true;   

        }while(canPlay == false);

        if(clean == false && proxy != null)
            proxy.stop();

    }


    public synchronized static void stop() {
        if(proxy != null)
            proxy.stop();
        if(mp != null)
            mp.stop(); 
        isPlaying = false;
    }

    public synchronized static void loadPlaylist(Playlist playlist) {
        PlayerBackgroundService.playlist = playlist;
    }

    public synchronized static void registerPlayer(PlayerController player) {
        PlayerBackgroundService.player = player;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (powerLock != null && powerLock.isHeld())
            powerLock.release(); 
    }


}

And launch it in this way:

this.startService(new Intent(appcontext, PlayerBackgroundService.class));

maybe my class is wrong.. can you help me?

Thanks in advance

Erenwoid
  • 983
  • 6
  • 13
  • 25

1 Answers1

0

You need to manually stop and resume the audio which has been played in Media player using pause and resume Method of activity , take a look at this,

 @Override
protected void onResume() {
    super.onResume();
    if (mediaPlayer != null) {
        mediaPlayer.start();
    }
}

protected void onPause() {
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.pause();
        if (isFinishing()) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
Karthi
  • 13,624
  • 10
  • 53
  • 76
  • Thanks for your fast answer! My service runs for all the whole app running duration, I don't want to stop or pause it, just play music when I need and make the music able to play in background.. what changes with your code? – Erenwoid Sep 21 '11 at 11:53
  • This code not for mediaplayer class , this method for default activity class to avoid chopping your music in background. – Karthi Sep 21 '11 at 11:58
  • It won`t affect your music which is play in background, it make your app to play the audio only when your app is in active mode, if your app goes background means it will handle your music automatically. – Karthi Sep 21 '11 at 12:00
  • Ok but I play my music using the service every time, not directly from the activity.. the oddity is why using a service on some phone my sound chops.. I found that using a service, the music sounds good .. activity just call the play and the stop method in the service, doesn't have a mediaplayer reference ^^ – Erenwoid Sep 21 '11 at 12:12
  • service always runs in background thats it choop your music don`t play the music form service – Karthi Sep 21 '11 at 14:05
  • why can't play from a service? have you got some example? I found this thread http://stackoverflow.com/questions/2097909/playing-bg-music-across-activities-in-android ... many people agree to use a Service to play.. I have the source of another app that makes a similar thing.. the problem is that in some device this doesn't work, in other devices with the same OS version works perfectly ^^ it's strange, isn't it? An android application should work well on every phone, at least on phones with the same OS.. why doesn't this happen? what's the matter? – Erenwoid Sep 21 '11 at 14:31
  • @Erenwoid service is absolutely fine to use. It might be a issue with the StreamProxy taking too much resources on that phone. Try borrowing one and debug directly. – Sebastian Roth Nov 23 '15 at 10:45