Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Handler将应用程序延迟_Java_Android_Handler_Runnable - Fatal编程技术网

Java Handler将应用程序延迟

Java Handler将应用程序延迟,java,android,handler,runnable,Java,Android,Handler,Runnable,我正在用Seekbar编程一个音乐播放器。为了管理它,我使用了一个带有Runnable的处理程序,它会更新。不知怎么的,它落后于我的用户界面。我怎样才能阻止这种滞后 一旦创建: mHandler = new Handler(); 当我播放歌曲时: public static void updateProgressBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } 我的Runnable: private

我正在用Seekbar编程一个音乐播放器。为了管理它,我使用了一个带有Runnable的处理程序,它会更新。不知怎么的,它落后于我的用户界面。我怎样才能阻止这种滞后

一旦创建:

mHandler  = new Handler();
当我播放歌曲时:

 public static void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }   
我的Runnable:

private static Runnable mUpdateTimeTask = new Runnable() {
         public void run() {

             try {
             long totalDuration = songService.getTotalDuration();
             int currentDuration = songService.getCurrentDuration();

             // Displaying Total Duration time
             player_time_length.setText(""+utils.milliSecondsToTimer(totalDuration));

             // Displaying time completed playing
             player_time_current.setText(""+utils.milliSecondsToTimer(currentDuration));

             // Updating progress bar
             int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));

             SB_song.setProgress(currentDuration);

             // Running this thread after 100 milliseconds
             mHandler.postDelayed(this, 100);
             }catch(Exception e){}
         }
      };

我怎样才能在我的应用程序中防止这种延迟呢?

我会说,这是因为它运行在延迟的UI线程上。但是您必须使用UI元素,这样就不可能有另一个线程。。我说得对吗?

延迟是因为
Runnable
正在
UI线程中执行。要减少或消除延迟,您必须减少在
可运行
中所做的工作量

您可以做的一件事是删除
longtotalduration=songService.getTotalDuration()Runnable
中选择code>,然后将其放在外部,就像我在音乐播放器中所做的那样


如果包含用于将毫秒转换为人类可读时间的“utils”方法,我可以为这个答案添加更多内容。

确保文本视图未设置为换行内容。这将在每次调用setText时触发布局传递。

这很有帮助!但我也改变了一些不同的东西:“mHandler.postDelayed(这个,100);”我实际上在这里打错了。这不需要每100毫秒调用一次我的处理程序。我添加了一个0,现在它每1秒运行一次,就像一个符咒:D@AhmetKazaman我的是100毫秒,绝对没有滞后。我喜欢seekbar更新看起来平滑,所以它是100毫秒。无论如何,很高兴知道你的问题解决了。有一个新问题也许你有了一个想法,因为你准备了一个音乐播放器: