首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TimerTask已排定

TimerTask已排定
EN

Stack Overflow用户
提问于 2013-05-13 00:25:28
回答 1查看 10.1K关注 0票数 3

我有一个播放本地音频文件的MediaPlayer对象。在播放音频时,我使用TimerTask更新SeekBar的位置和TextView上的文本。

有一个按钮。当用户按下按钮时,音频开始。当他们第二次按下它时,音频就会停止。当他们第三次按下它再次开始播放时,应用程序崩溃并出现错误

代码语言:javascript
复制
'causedby: TimerTask is scheduled already and InvocationTargetException'.

下面是我的代码:

代码语言:javascript
复制
    public void onAudioClicked(View v) {
    if (mainPlayer == null) {
        mainPlayer = MediaPlayer.create(this, R.raw.session1);
        // Get audio duration and set textview
        int d = mainPlayer.getDuration();
        TextView t = (TextView)findViewById(R.id.totalTime);
        t.setText(String.format("%d:%d", 
                TimeUnit.MILLISECONDS.toMinutes(d),
                TimeUnit.MILLISECONDS.toSeconds(d) - 
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));

        sb.setProgress(0);
        sb.setMax(mainPlayer.getDuration());
        mainPlayer.start();
        timer = new Timer();
        timer.schedule(task, 1000);
    } else {
        mainPlayer.stop();
        mainPlayer.release();
        mainPlayer = null;
        timer.cancel();
        task.cancel();
        timer = null;
    }
}

    TimerTask task = new TimerTask(){
    public void run(){
        int currentPosition = 0;
        int total = mainPlayer.getDuration();
        sb.setMax(total);
        while (mainPlayer != null && currentPosition < total) {
            try {
                Thread.sleep(1000);
                currentPosition = mainPlayer.getCurrentPosition();
                runOnUiThread(updateControlsRunnable);
            } catch (InterruptedException e) {
                return;
            } catch (Exception e) {
                return;
            }
            sb.setProgress(currentPosition);
        }

    }
};

final Runnable updateControlsRunnable = new Runnable () {
    public void run(){
        int d = mainPlayer.getCurrentPosition();
        TextView t = (TextView)findViewById(R.id.currentTime);
        t.setText(String.format("%d:%d", 
                TimeUnit.MILLISECONDS.toMinutes(d),
                TimeUnit.MILLISECONDS.toSeconds(d) - 
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));
        }
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-13 00:53:31

请尝试此代码块:

代码语言:javascript
复制
sb.setProgress(0);
sb.setMax(mainPlayer.getDuration());
mainPlayer.start();
timer = new Timer();
MyTask task=new MyTask();
timer.schedule(task,0, 1000);

private class MyTask extends TimerTask {
    public void run() {
        //Your code...
    }
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16509503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档