如何为音乐播放器的播放暂停服务

时间:2018-12-24 14:43:51

标签: android android-service android-mediaplayer

这是我的代码,它是资源文件夹中的播放歌曲,现在我受困于服务,请帮助我.....

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mHandler=new Handler();

    seekBar=findViewById(R.id.seekBar);

    mp=MediaPlayer.create(MainActivity.this,R.raw.ed);
    final int Duration=mp.getDuration();
  

媒体播放器准备的监听器.....

    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            seekBar.setMax(mp.getDuration());
            updateSeekBar();
            mp.start();
        }
    });
  

Seekbar的可运行线程.....

    runnable=new Runnable() {
    @Override
    public void run() {
   updateSeekBar();
     }
};
  

用于来电和去电的电话状态监听器.....

    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING) {
                mp.pause();
            } else if(state == TelephonyManager.CALL_STATE_IDLE) {
               mp.start();
            } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
                mp.pause();
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };
    TelephonyManager mgr = (TelephonyManager) 
      getSystemService(TELEPHONY_SERVICE);
     if(mgr != null) {
        mgr.listen(phoneStateListener, 
         PhoneStateListener.LISTEN_CALL_STATE);
    }

}
  

搜索栏更新方法。...

private void updateSeekBar() {
    seekBar.setProgress(mp.getCurrentPosition());
    mHandler.postDelayed(runnable, 100);

}

}
  

现在,这是我的服务代码...。

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class MyMusicService extends Service {
  

关于创建服务方法。...

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

关于服务的启动方法。...

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}
  

销毁服务方法......

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

活页夹....

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

1 个答案:

答案 0 :(得分:1)

看到我添加了对我有用的服务代码。

您可以根据需要尝试使用此代码

package com.example.musicplayer;

import java.util.ArrayList;
import java.util.Random;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

/*
 * This is demo code to accompany the Mobiletuts+ series:
 * Android SDK: Creating a Music Player
 * 
 */

public class MusicService extends Service implements 
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {

    //media player
    private MediaPlayer player;
    //song list
    private ArrayList<Song> songs;
    //current position
    private int songPosn;
    //binder
    private final IBinder musicBind = new MusicBinder();
    //title of current song
    private String songTitle="";
    //notification id
    private static final int NOTIFY_ID=1;
    //shuffle flag and random
    private boolean shuffle=false;
    private Random rand;

    public void onCreate(){
        //create the service
        super.onCreate();
        //initialize position
        songPosn=0;
        //random
        rand=new Random();
        //create player
        player = new MediaPlayer();
        //initialize
        initMusicPlayer();
    }

    public void initMusicPlayer(){
        //set player properties
        player.setWakeMode(getApplicationContext(), 
                PowerManager.PARTIAL_WAKE_LOCK);
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //set listeners
        player.setOnPreparedListener(this);
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
    }

    //pass song list
    public void setList(ArrayList<Song> theSongs){
        songs=theSongs;
    }

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

    //activity will bind to service
    @Override
    public IBinder onBind(Intent intent) {
        return musicBind;
    }

    //release resources when unbind
    @Override
    public boolean onUnbind(Intent intent){
        player.stop();
        player.release();
        return false;
    }

    //play a song
    public void playSong(){
        //play
        player.reset();
        //get song
        Song playSong = songs.get(songPosn);
        //get title
        songTitle=playSong.getTitle();
        //get id
        long currSong = playSong.getID();
        //set uri
        Uri trackUri = ContentUris.withAppendedId(
                android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                currSong);
        //set the data source
        try{ 
            player.setDataSource(getApplicationContext(), trackUri);
        }
        catch(Exception e){
            Log.e("MUSIC SERVICE", "Error setting data source", e);
        }
        player.prepareAsync(); 
    }

    //set the song
    public void setSong(int songIndex){
        songPosn=songIndex; 
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        //check if playback has reached the end of a track
        if(player.getCurrentPosition()>0){
            mp.reset();
            playNext();
        }
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Log.v("MUSIC PLAYER", "Playback Error");
        mp.reset();
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        //start playback
        mp.start();
        //notification
        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);
    }

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

    public int getDur(){
        return player.getDuration();
    }

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

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

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

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

    //skip to previous track
    public void playPrev(){
        songPosn--;
        if(songPosn<0) songPosn=songs.size()-1;
        playSong();
    }

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

    @Override
    public void onDestroy() {
        stopForeground(true);
    }

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

}

OR

如果您想从头开始学习

也可以通过以下链接来学习和创造自己的自我。

http://code.tutsplus.com/tutorials/create-a-music-player-on-android-project-setup--mobile-22764

http://code.tutsplus.com/tutorials/create-a-music-player-on-android-song-playback--mobile-22778

http://code.tutsplus.com/tutorials/create-a-music-player-on-android-user-controls--mobile-22787

我希望它能对您有所帮助。

谢谢。