从服务中获取媒体播放器服务屏幕

时间:2013-12-10 23:46:58

标签: android android-service instance

我有一个在后台播放音乐的媒体播放器服务,这项服务是从活动中调用的。现在,当我前。退出该活动,再次回到它,我想看看状态是什么,播放什么歌等。

以下是我服务的代码:

public class MediaPlayerService extends Service implements
    OnCompletionListener, OnClickListener {
    MediaPlayer mediaPlayer;
    String url;
    int mediaPos, mediaMax, position;
    boolean isShufle;
    WeakReference<SeekBar> seekbar;
    WeakReference<TextView> reciter, songTitle, songPos;
    private WeakReference<ImageView> play, forward, backward;
    ArrayList<Songs> songs;
    Handler handler;

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

    @Override
    public void onCreate() {
        // mediaPlayer = MediaPlayer.create(this,url);// raw/s.mp3
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    }

    private void play(final int position) throws IllegalArgumentException,
            SecurityException, IllegalStateException, IOException {
        /*
         * dialog = ProgressDialog.show(AlbumDetails.this, "",
         * getString(com.darkovski.quran.R.string.buffering), true);
         * dialog.setCancelable(true); dialog.show();
         */

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(songs.get(position).getLink());

        // prepare track
        mediaPlayer.prepare();
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                play.get().setImageResource(R.drawable.pause);
                // play.setImageResource(R.drawable.pause);

                // this is new

                mediaPos = mp.getCurrentPosition();
                mediaMax = mp.getDuration();
                reciter.get().setText(songs.get(position).getRecitorName());
                songTitle.get().setText(songs.get(position).getTitle());
                songPos.get().setText((position + 1) + " of 114");
                seekbar.get().setMax(mediaMax);
                seekbar.get().setProgress(mediaPos);

                handler.removeCallbacks(moveSeekBarThread);
                handler.postDelayed(moveSeekBarThread, 100);
                mp.start();
                // dialog.dismiss();
            }
        });
        // when truck finishes
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // if(shuffle)
                try {
                    if (isShufle) {
                        play(new Random().nextInt(songs.size()));

                    } else {
                        if (position == songs.size())
                            play(0);
                        else
                            play(position + 1);
                    }
                    AlbumDetails.position += 1;
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        url = intent.getStringExtra("url");
        handler = new Handler();
        position = intent.getIntExtra("position", -1);
        forward = new WeakReference<ImageView>(AlbumDetails.forward);
        backward = new WeakReference<ImageView>(AlbumDetails.backward);
        play = new WeakReference<ImageView>(AlbumDetails.play);
        play.get().setOnClickListener(this);
        forward.get().setOnClickListener(this);
        backward.get().setOnClickListener(this);
        seekbar = new WeakReference<SeekBar>(AlbumDetails.seekbar);
        reciter = new WeakReference<TextView>(AlbumDetails.reciter);
        songTitle = new WeakReference<TextView>(AlbumDetails.songTitle);
        songPos = new WeakReference<TextView>(AlbumDetails.songPos);
        songs = AlbumDetails.songs;

        seekbar.get().setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                if (fromUser && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(progress);
                }
            }
        });
        /*
         * try { mediaPlayer.setDataSource(url); mediaPlayer.prepare();
         * mediaPlayer.setOnCompletionListener(this); } catch
         * (IllegalArgumentException e) { // TODO Auto-generated catch block
         * e.printStackTrace(); } catch (SecurityException e) { // TODO
         * Auto-generated catch block e.printStackTrace(); } catch
         * (IllegalStateException e) { // TODO Auto-generated catch block
         * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated
         * catch block e.printStackTrace(); } if (!mediaPlayer.isPlaying()) {
         * mediaPlayer.start(); }
         */

        try {
            play(position);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return START_STICKY;
    }

    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
    }

    public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
    }


    private Runnable moveSeekBarThread = new Runnable() {

        public void run() {
            if (mediaPlayer.isPlaying()) {
                int mediaPos_new = mediaPlayer.getCurrentPosition();
                int mediaMax_new = mediaPlayer.getDuration();
                seekbar.get().setMax(mediaMax_new);
                seekbar.get().setProgress(mediaPos_new);
                handler.postDelayed(this, 100);
            }

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.playeer_back:
            try {
                if (mediaPlayer != null)
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                    }
                if (position - 1 < 0) {
                    play(songs.size());
                    position = songs.size();
                } else
                    play(position - 1);
            } catch (IllegalArgumentException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } catch (SecurityException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } catch (IllegalStateException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            break;
        case R.id.playeer_forward:
            try {
                if (mediaPlayer != null)
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                    }
                play(position + 1);
                position += 1;
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        case R.id.playeer_play:
            if (mediaPlayer == null) {
                try {
                    play(position);
                } catch (IllegalArgumentException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (SecurityException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IllegalStateException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                play.get().setImageResource(R.drawable.pause);
            } else if (mediaPlayer != null) {
                mediaPlayer.start();
                play.get().setImageResource(R.drawable.play_play);
            }
            // playFunction();
            break;
        }
    }

}

我的活动代码 - onClick:

case R.id.playeer_play:
            playbackServiceIntent
            .putExtra("url", songs.get(position).getLink());
            playbackServiceIntent
            .putExtra("position", position);
            startService(playbackServiceIntent);
                        break;

1 个答案:

答案 0 :(得分:1)

有不同的方法来实现它。

  1. 使用LocalBroadcastManager
  2. 使用应用程序跟踪您的服务状态,即歌曲名称,长度,......
  3. 使用SharedPreferences
  4. 恕我直言,我认为使用LocalBroadcastManager更清洁。
    - 向服务发送广播消息
    - 当服务收到消息时,让它广播其状态。