在Runnable中更新TextView会导致Activity停止

时间:2014-04-10 07:30:20

标签: java android runnable

我有一个媒体播放器服务,其中我有一个Runnable,它每100毫秒更新一次搜索栏和当前位置TextView

private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            long totalDuration = mediaPlayer.getDuration();
            long currentDuration = mediaPlayer.getCurrentPosition();

           seekBar.setProgress(progress);
           nowduration.setText("" + utils.milliSecondsToTimer(currentDuration));
           totalduration.setText(""+utils.milliSecondsToTimer(totalDuration));

            // Running this thread after 100 milliseconds
            mHandler.postDelayed(this, 100);
        }
    };

问题是,一段时间(5-10秒)活动停止后,我在logcat中看到的唯一错误就是这个。虽然删除nowduration.setText一切正常,但搜索栏正在更新而没有任何问题,为什么TextView活动会停止?

04-10 10:22:40.610      288-813/system_process I/ActivityManager﹕ Process com.package.appname (pid 3734) has died.
04-10 10:22:40.610     288-3633/system_process I/WindowManager﹕ WIN DEATH: Window{424b5708 com.package.appname/com.package.appname.MainActivity paused=false}

我尝试过:1。在TextView.setText上使用runOnUithread - 相同的行为2.使用Thread而不是Handler - 但我有问题停止线程,有时我需要调用Handler.removeCallBacks,但据我所知停止一个线程是一个非常糟糕的动作,这就是Thread.stop(被折旧)的原因。

2 个答案:

答案 0 :(得分:1)

UserInterface只能由UI线程更新。你需要一个Handler来发布到UI线程:

private void startTimerThread() {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
    private long startTime = System.currentTimeMillis();
    public void run() {

            try {
                Thread.sleep(1000);
            }    
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(new Runnable(){
                public void run() {
        long totalDuration = mediaPlayer.getDuration();
        long currentDuration = mediaPlayer.getCurrentPosition();

       seekBar.setProgress(progress);
       nowduration.setText("" + utils.milliSecondsToTimer(currentDuration));
       totalduration.setText(""+utils.milliSecondsToTimer(totalDuration));


            }
        });
        }

};
new Thread(runnable).start();
}

答案 1 :(得分:0)

尝试使用处理程序消息来执行此操作:

private Handler handler = new Handler(){

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg); 

        switch(msg.what){
            case 1:{
                long totalDuration = mediaPlayer.getDuration();
                long currentDuration = mediaPlayer.getCurrentPosition();

                seekBar.setProgress(progress);
                nowduration.setText("" + utils.milliSecondsToTimer(currentDuration));
                totalduration.setText(""+utils.milliSecondsToTimer(totalDuration));

                // Running this thread after 100 milliseconds
                mHandler.sendEmptyMessageDelayed(1, 100);
            }break;
        }
    }

};

首次更新开始:

...
handler.sendEmptyMessage(1);
...