无法连接音乐服务

时间:2017-03-05 06:47:12

标签: android

您好,我是初学者,我正在创建一个音乐应用程序,我差不多完成了,我创建了两个活动,一个用于歌曲列表,一个用于现在播放,我使用的是材料设计我现在正在进行的活动的互动视图我想将我的音乐服务连接到我的正在播放的活动请帮助我,我尝试连接但没有发生

感谢您的帮助

enter image description here

NowPlaying.java

public class NowPlaying extends AppCompatActivity implements OnActionClickedListener {
private MediaPlayer mp;
private ImageView previous, next;

//Set the View Layout
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.toolbar_layout);

    //Buttons for moving song position
    previous = (ImageView) findViewById(R.id.prev);
    next = (ImageView) findViewById(R.id.next);

    final InteractivePlayerView mInteractivePlayerView = (InteractivePlayerView) findViewById(R.id.interactivePlayerView);
    mInteractivePlayerView.setMax(80);
    mInteractivePlayerView.setProgress(0);
    mInteractivePlayerView.setOnActionClickedListener(this);
    mInteractivePlayerView.getParentForAccessibility();

    final ImageView imageView = (ImageView) findViewById(R.id.control);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (!mInteractivePlayerView.isPlaying()) {
                mInteractivePlayerView.start();
                imageView.setBackgroundResource(R.drawable.ic_action_pause);
            } else {
                mInteractivePlayerView.stop();
                imageView.setBackgroundResource(R.drawable.ic_action_play);
            }
        }
    });
}

   @Override
   public void onActionClicked(int id) {
        switch (id) {
           case 1:
               break;
           case 2:
               break;
           case 3:
               break;
           default:
               break;
       }
   }

}

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

   //Notification Id
   private static final int NOTIFY_ID = 1;
   //Binder
   private final IBinder musicBind = new MusicBinder();
   //Media Player
   private MediaPlayer player;
   //Song List
   private ArrayList<Song> songs;
   //Current Position
   private int songPosn;
   //Title of current song
   private String songTitle;
   //shuffle flag and random
   private boolean shuffle = false;
   private Random rand;

public void onCreate() {
    //Create the service
    super.onCreate();
    //Initialize position
    songPosn = 0;
    //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 listener
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
}

//Pass the song
public void setList(ArrayList<Song> theSong) {
    songs = theSong;
}

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

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

//For playing 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(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("Now 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();
}

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

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

//toggle shuffle
public void setShuffle(){

    if(shuffle) shuffle=false;
    else shuffle=true;
}

}

0 个答案:

没有答案