【发布时间】:2018-10-02 04:28:29
【问题描述】:
目前我正在尝试修复我的搜索栏上的一个错误,当我点击确定的位置时,seekBar 和 mediaPlayer 重置为 0。检查下面的代码:
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
final Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (mediaPlayer != null) {
int CurrentPosition = mediaPlayer.getCurrentPosition();
int Duration = mediaPlayer.getDuration();
int progress = (getProgressPercentage(CurrentPosition, Duration));
seekBar.setProgress(progress); // this line is working perfectly, I'm getting a high accuracy using getProgressPercentage
String m_1;
String s_1;
//Toast.makeText(getApplicationContext(), "Current: " + CurrentPosition + " - Duration: " + mediaPlayer.getDuration(), Toast.LENGTH_LONG).show();
final int minutes_1 = (CurrentPosition / 1000) / 60;
final int seconds_1 = ((CurrentPosition / 1000) % 60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
String m_2;
String s_2;
final int minutes_2 = (Duration / 1000) / 60;
final int seconds_2 = ((Duration / 1000) % 60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
int _progress = (getProgressPercentage(progress*1000, mediaPlayer.getDuration()));
mediaPlayer.seekTo(_progress); //the problem is here, the seetkTo is reseting to zero.
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public int getProgressPercentage(long currentDuration, long totalDuration){
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 100);
long totalSeconds = (int) (totalDuration / 100);
percentage =(((double)currentSeconds)/totalSeconds)*100;
return percentage.intValue();
}
这个脚本没有错误,一切正常,除了当我点击确定的位置时,我正在使用int _progress = (getProgressPercentage(progress*1000, mediaPlayer.getDuration()));,因为getProgressPercentage 在final Runnable mRunnable = new Runnable() { 对我来说工作正常。使用这个功能我得到了更高的准确性。
所以,唯一的问题与seekBar.setOnSeekBarChangeListener 有关。我不知道如何解决这个问题,你能帮我吗?谢谢。
【问题讨论】:
标签: java android android-mediaplayer