当歌曲从歌曲列表播放时,mediaplayer.seekTo()工作正常但是当我按下后退按钮然后出来应用程序然后打开应用程序,然后mediaplayer.seetTo()无法工作,每当我试图更改歌曲从头开始的搜索栏进度。
这是我的代码 MainActivity.class
private ServiceConnection serviceConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
// We've bound to LocalService, cast the IBinder and get LocalService instance
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
player = binder.getService();
updateProgressBar();
Toast.makeText(MainActivity.this, "Servcie instance got it", Toast.LENGTH_SHORT).show();
serviceBound = true;
setSongPlayView();
if (requestCode != 0)
{
//finish();
setSongPlayView();
setSongView();
// songView();
slidingUpPanelLayout.setPanelState(PanelState.EXPANDED);
}
if (playlistname != null)
{
if (category != null)
{
getCategorydata(category, playlistname);
getPlaylist(sList, position);
} else {
getPlaylistItems(playlistname);
getPlaylist(sList, position);
}
}
}
@Override
public void onServiceDisconnected(ComponentName name)
{
serviceBound = false;
Toast.makeText(MainActivity.this,"Servcie instance disconnected",Toast.LENGTH_SHORT).show();
}
};
public void updateProgressBar() {
if(hand!=null)
hand.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if(hand!=null) {
long totalDuration = player.mp.getDuration();
long currentDuration = player.mp.getCurrentPosition();
// Displaying Total Duration time
endtime.setText("" + utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
starttime.setText("" + utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
// int progress=player.progress;
updater.setProgress(progress);
// waveLoadingView.setProgressValue(progress);
//updateui(progress,"" + utils.milliSecondsToTimer(currentDuration),"" + utils.milliSecondsToTimer(totalDuration));
// Running this thread after 100 milliseconds
hand.postDelayed(this, 100);
}
}
};
/**
*
* */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
if(fromTouch){
updater.setProgress(progress);
waveLoadingView.setProgressValue(progress);
player.seekBarProgress(progress);
//updateui(progress,currentprogress,totalprogress);
updateui(progress);
Message message = MainActivity.hand.obtainMessage();
message.obj = position;
message.obj=sList;
MainActivity.hand.sendMessage(message);
updateProgressBar();
}
}
/**
* When user starts moving the progress handler
* */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
if(hand!=null)
hand.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(hand!=null) {
hand.removeCallbacks(mUpdateTimeTask);
int totalDuration = player.mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
player.mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
}
protected void onStart()
{
if(intent==null) {
intent = new Intent(this, MusicService.class);
}
//startService(intent);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
super.onStart();
}}
MusicService.class
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(this,Getdata.class);
intent.setAction(str_receiver);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
this.sList=new ArrayList<>();
helper = new Getmusic(this);
db = helper.getReadableDatabase();
return MusicService.START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this,"service desttoyed",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void setPlaylist(ArrayList<SongModel> sList, int location) {
this.sList = sList;
this.position = location;
/*this.mp = new MediaPlayer();*/
if (sList.size() > 0)
getStart(position);
}
public class LocalBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
public void getStart(final int pos) {
try {
if (sList.size() > 0) {
buildNotification();
mp.reset();
mp.setDataSource(getApplicationContext(), sList.get(pos).getUri());
mp.prepare();
mp.start();
// updateProgressBar();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (isRepeat) {
// repeat is on play same song again
getStart(position);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
position = rand.nextInt((sList.size() - 1) - 0 + 1) + 0;
getStart(position);
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
} else {
// no repeat or shuffle ON - play next song
if (position < (sList.size() - 1)) {
getStart(position + 1);
position = position + 1;
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
} else {
// play first song
getStart(0);
position = 0;
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
}
}
}
});
}
} catch(IllegalArgumentException e){
e.printStackTrace();
} catch(IllegalStateException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
public int getProgressPercentage(long currentDuration, long totalDuration) {
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 1000);
long totalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage = (((double) currentSeconds) / totalSeconds) * 100;
// return percentage
return percentage.intValue();
}
public long getDuration() {
long totalDuration = mp.getDuration();
return totalDuration;
}
public long gettotalDuration() {
long currentDuration = mp.getCurrentPosition();
return currentDuration;
}
public int progress(){
return (int)(utils.getProgressPercentage(mp.getCurrentPosition(), mp.getDuration()));
}
public void getRepeat(boolean isRepeat) {
if (isRepeat) {
this.isRepeat = true;
} else {
// make repeat to true
this.isRepeat = false;
// make shuffle to false
/* this.isShuffle = false;*/
}
}
public void getShuffle(boolean isShuffle) {
if (isShuffle) {
this.isShuffle = true;
} else {
// make repeat to true
this.isShuffle = false;
// make shuffle to false
/* this.isRepeat = false;*/
}
}
public void getNextSong() {
if (isRepeat) {
// repeat is on play same song again
getStart(position);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
position = rand.nextInt((sList.size() - 1) - 0 + 1) + 0;
getStart(position);
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
} else {
// no repeat or shuffle ON - play next song
if (position < (sList.size() - 1)) {
getStart(position + 1);
position = position + 1;
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
} else {
// play first song
getStart(0);
position = 0;
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
}
}
}
public void getPreviousSong() {
if (isRepeat) {
// repeat is on play same song again
getStart(position);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
position = rand.nextInt((sList.size() - 1) - 0 + 1) + 0;
getStart(position);
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
} else {
// no repeat or shuffle ON - play next song
if (position > 0) {
getStart(position - 1);
position = position - 1;
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
} else {
// play last song
getStart(sList.size() - 1);
position = sList.size() - 1;
playbackStatus = PlaybackStatus.PLAYING;
buildNotification();
}
}
}
public void seekBarProgress(final int data) {
hand = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Message message = MainActivity.hand.obtainMessage();
mp.seekTo(data);
}
};
}