同时播放2个媒体服务

时间:2017-01-15 13:08:30

标签: android android-service android-mediaplayer android-service-binding

MainActivity上的后退按钮(调用它为onDestroy())后,媒体在后台播放(使用前台服务)。

但是再次打开应用程序后((称之为onCreate()),如果我尝试播放另一首歌曲,则第一首歌曲不会停止。两首歌曲一起播放。我该如何解决? 任何帮助表示赞赏。

这是我的MusicService课程:

public void onCreate() {
    super.onCreate();
    Log.i(TAG3, "onCreate");
    songPosn=0;
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    player = new MediaPlayer();
    initMusicPlayer();
    rand=new Random();
}

//initializes the MediaPlayer class
public void initMusicPlayer(){
    Log.i(TAG3, "initMusicPlayer");
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
}

public void setList(ArrayList<Song> theSongs){
    songs=theSongs;
}
//We will call this when the user picks a song from the list.
public void setSong(int songIndex){
    songPosn=songIndex;
}

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

//Let's now set the app up to play a track
public void playSong(){
    Log.i(TAG3, "playSong");
    player.reset();
    //get song
    Song playSong = songs.get(songPosn);
    songTitle=playSong.getTitle();
    //get id
    long currSong = playSong.getID();
    //set uri
    Uri trackUri = ContentUris.withAppendedId(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            currSong);

    try{
        player.setDataSource(getApplicationContext(), trackUri);
    }
    catch(Exception e){
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }
    player.prepareAsync();
}

public void playPrev(){
    songPosn--;
    if(songPosn<0) songPosn=songs.size()-1;
    playSong();
}

//skip to next
public void playNext(){
    if(repeat){playSong();}
    else if(shuffle){
        int newSong = songPosn;
        while(newSong==songPosn){
            newSong=rand.nextInt(songs.size());
        }
        songPosn=newSong;
        playSong();
    }
    else{
        songPosn++;
        if(songPosn>=songs.size()) songPosn=0;
        playSong();
    }
}

public int getPosn(){
    return player.getCurrentPosition();
}

public int getDur(){
    return dr;
}

public boolean isPng(){
    return player.isPlaying();
}

public void pausePlayer(){
    player.pause();
}

public void seek(int posn){
    player.seekTo(posn);
}

public void go(){
    player.start();
}

public void setShuffle(){
    if(shuffle) shuffle=false;
    else {shuffle=true;repeat=false;}
}

public void setRepeat(){
    if(repeat) repeat=false;
    else {repeat=true;shuffle=false;}
}

//When the MediaPlayer is prepared, the onPrepared method will be executed.
@Override
public void onPrepared(MediaPlayer mp) {
    Log.i(TAG3, "onPrepared");
    //start playback
    mp.start();
    dr = player.getDuration();
    Intent notIntent = new Intent(this, MainActivity.class);
    notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendInt = PendingIntent.getActivity(this, 0,
            notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(this);

    builder.setContentIntent(pendInt)
            .setSmallIcon(R.drawable.play)
            .setTicker(songTitle)
            .setOngoing(true)
            .setContentTitle("Playing").setContentText(songTitle);
    Notification not = builder.build();

    startForeground(NOTIFY_ID, not);
}

@Override
public void onCompletion(MediaPlayer mp) {
    Log.i(TAG3, "onCompletion");
    if(player.getCurrentPosition()>0){
        mp.reset();
        playNext();
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Log.i(TAG3, "onError");
    mp.reset();
    return false;
}

@Override
public void onAudioFocusChange(int focusChange) {
    if(focusChange<=0) {
        //LOSS -> PAUSE
        player.pause();
    } else {
        //GAIN -> PLAY
        player.start();
    }
}

@Override
public IBinder onBind(Intent intent) {
    Log.i(TAG3, "onBind");
    return musicBind;
}

@Override
public boolean onUnbind(Intent intent){
    Log.i(TAG3, "onUnbind");

    return false;
}

@Override
public void onDestroy() {
    Log.i(TAG3, "onDestroy");
    mAudioManager.abandonAudioFocus(this);
    stopForeground(true);
}

请注意;我已从player.stop(); player.release();移除了onUnbind(),因为在backbutton上按MainActivity后播放停止了。

1 个答案:

答案 0 :(得分:2)

按下时,后退按钮不应调用onDestroy。 我在这里找到了: https://stackoverflow.com/a/5868534/6737655