如何从暂停的位置重新启动媒体播放器服务?

时间:2014-09-04 09:01:18

标签: android service

我在Android Developer上阅读了文档但仍无法暂停我的服务,然后从暂停状态启动它(播放歌曲)。

使用我当前的代码,它总是从歌曲的开头重新开始,但我想重新开始歌曲暂停的位置(使用stopClick)。

现在我明白了问题。在MainActivity中使用stopService()方法完全破坏它。 那么当我按下停止按钮暂停时,怎么能说服务等待?

服务类:

  public class BackgroundSoundService extends Service {
    MediaPlayer player;
     int currentPos; 

    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        final int MAX_VOLUME = 100;
        player = MediaPlayer.create(this, R.raw.lightmusic);
        player.setLooping(true);
        float soundVolume = 77;
        final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math
                .log(MAX_VOLUME)));
        player.setVolume(volume, volume);

        player.seekTo(currentPos);
        player.start();

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        player.seekTo(currentPos);
        player.start();

        return 1;
    }

    public void onStart(Intent intent, int startId) {
        player.seekTo(currentPos);
        player.start();
    }

    @Override
    public void onRebind(Intent intent) {
        player.seekTo(currentPos);
        player.start();
        super.onRebind(intent);
    }

    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {
        currentPos = player.getCurrentPosition();
         player.pause(); 

    }



    public void onPause() {
         currentPos = player.getCurrentPosition();
         player.pause(); 


    }

    @Override
    public void onDestroy() {
        currentPos = player.getCurrentPosition();
         player.pause(); 
        //player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

我的主要活动:

public class MainActivity extends QuizActivity {

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

        startService(new Intent(this, BackgroundSoundService.class));


    }



    public void stopClick(View v) {
        stopService(new Intent(this, BackgroundSoundService.class));
    }

    public void playClick(View v) {
        startService(new Intent(this, BackgroundSoundService.class));
    }


    @Override
    protected void onResume() {
        super.onResume();
    }
}

0 个答案:

没有答案