我在Android上构建了一个简单的音乐播放器。每首歌的视图都包含一个SeekBar,实现如下:

public class Song extends Activity implements OnClickListener,Runnable {
    private SeekBar progress;
    private MediaPlayer mp;

    // ...

    private ServiceConnection onService = new ServiceConnection() {
          public void onServiceConnected(ComponentName className,
            IBinder rawBinder) {
              appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer
              progress.setVisibility(SeekBar.VISIBLE);
              progress.setProgress(0);
              mp = appService.getMP();
              appService.playSong(title);
              progress.setMax(mp.getDuration());
              new Thread(Song.this).start();
          }
          public void onServiceDisconnected(ComponentName classname) {
              appService = null;
          }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.song);

        // ...

        progress = (SeekBar) findViewById(R.id.progress);

        // ...
    }

    public void run() {
    int pos = 0;
    int total = mp.getDuration();
    while (mp != null && pos<total) {
        try {
            Thread.sleep(1000);
            pos = appService.getSongPosition();
        } catch (InterruptedException e) {
            return;
        } catch (Exception e) {
            return;
        }
        progress.setProgress(pos);
    }
}

这很好。现在我想要一个计时器计算秒/分钟的歌曲的进展。所以我把一个TextView在布局,得到它与findViewById()在onCreate(),并把这个在run()后的progress.setProgress(pos):

String time = String.format("%d:%d",
            TimeUnit.MILLISECONDS.toMinutes(pos),
            TimeUnit.MILLISECONDS.toSeconds(pos),
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(
                    pos))
            );
currentTime.setText(time);  // currentTime = (TextView) findViewById(R.id.current_time);

但最后一句给了我一个例外:

android.view。只有创建视图层次结构的原始线程才能触及它的视图。

然而,我在这里所做的事情基本上与我在SeekBar中所做的事情相同——在onCreate中创建视图,然后在run()中触摸它——它没有给我这个抱怨。


当前回答

Kotlin协程可以让你的代码更简洁和可读,就像这样:

MainScope().launch {
    withContext(Dispatchers.Default) {
        //TODO("Background processing...")
    }
    TODO("Update UI here!")
}

反之亦然:

GlobalScope.launch {
    //TODO("Background processing...")
    withContext(Dispatchers.Main) {
        // TODO("Update UI here!")
    }
    TODO("Continue background processing...")
}

其他回答

我的解决方案是:

private void setText(final TextView text,final String value){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            text.setText(value);
        }
    });
}

在后台线程上调用此方法。

“这是我的代码”

Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    KeyValuePair<String, String> keyValuePair = getCalculateDifferenceBetweenTwoTimes();

                    CharSequence charSequence = getPresenterUtil().contact(
                            getPresenterUtil().messageStyle("Check-in", Color.GRAY, Typeface.NORMAL, 0.9f),
                            UtilPresenter.LINE,
                            getPresenterUtil().messageStyle(keyValuePair.getKey(), Color.BLACK, Typeface.NORMAL, 1.3f),
                            UtilPresenter.LINE,
                            UtilPresenter.LINE,
                            getPresenterUtil().messageStyle("Tempo de execução", Color.GRAY, Typeface.NORMAL, 0.9f),
                            UtilPresenter.LINE,
                            getPresenterUtil().messageStyle(keyValuePair.getValue(), Color.BLACK, Typeface.NORMAL, 1.3f)
                    );

                    if (materialDialog.getContentView() != null) {
                        materialDialog.getContentView().setText(charSequence);
                    }
                }
            });
        }
    }, 0, 1000);

通常,任何涉及用户界面的操作都必须在主线程或UI线程中完成,这就是执行onCreate()和事件处理的线程。一种方法是使用runOnUiThread(),另一种方法是使用Handlers。

ProgressBar.setProgress()有一种机制,它总是在主线程上执行,所以这就是它工作的原因。

参见无痛穿线。

使用AsyncTask时更新onPostExecute方法中的UI

    @Override
    protected void onPostExecute(String s) {
   // Update UI here

     }

芬兰湾的科特林回答

我们必须使用UI线程的工作与真实的方式。我们可以在Kotlin中使用UI线程,例如:

runOnUiThread(Runnable {
   //TODO: Your job is here..!
})