我在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()中触摸它——它没有给我这个抱怨。


当前回答

我的解决方案是:

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

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

其他回答

如果你在一个片段中,那么你还需要获取活动对象,因为runOnUIThread是活动上的一个方法。

Kotlin中的一个例子,有一些周围的上下文,让它更清楚-这个例子是从一个相机片段导航到一个画廊片段:

// Setup image capture listener which is triggered after photo has been taken
imageCapture.takePicture(
       outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {

           override fun onError(exc: ImageCaptureException) {
           Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
        }

        override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                        val savedUri = output.savedUri ?: Uri.fromFile(photoFile)
                        Log.d(TAG, "Photo capture succeeded: $savedUri")
               
             //Do whatever work you do when image is saved         
             
             //Now ask navigator to move to new tab - as this
             //updates UI do on the UI thread           
             activity?.runOnUiThread( {
                 Navigation.findNavController(
                        requireActivity(), R.id.fragment_container
                 ).navigate(CameraFragmentDirections
                        .actionCameraToGallery(outputDirectory.absolutePath))
              })

对于runOnUiThread()方法的一行程序版本,您可以使用lambda函数,即:

runOnUiThread(() -> doStuff(Object, myValue));

其中doStuff()可以表示一些用于修改某些UI对象值的方法(设置文本,改变颜色等)。

我发现当尝试更新多个UI对象而不需要每个对象都有6行Runnable定义时,这要整洁得多,就像投票最多的答案中提到的那样,这绝不是不正确的,它只是占用了更多的空间,而且我发现可读性较差。

所以这个:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        doStuff(myTextView, "myNewText");
    }
});

可以变成这样:

runOnUiThread(() -> doStuff(myTextView, "myNewText"));

doStuff的定义在别处。

或者如果你不需要这么一般化,只需要设置TextView对象的文本:

runOnUiThread(() -> myTextView.setText("myNewText"));

我曾经遇到过这种情况,但我用Handler对象找到了解决方案。

在我的例子中,我想用观察者模式更新一个ProgressDialog。 我的视图实现了观察者并重写了更新方法。

因此,我的主线程创建了视图,另一个线程调用更新方法来更新ProgressDialop和....:

只有创建视图层次结构的原始线程才能接触它 的观点。

可以用Handler对象来解决这个问题。

下面是我代码的不同部分:

public class ViewExecution extends Activity implements Observer{

    static final int PROGRESS_DIALOG = 0;
    ProgressDialog progressDialog;
    int currentNumber;

    public void onCreate(Bundle savedInstanceState) {

        currentNumber = 0;
        final Button launchPolicyButton =  ((Button) this.findViewById(R.id.launchButton));
        launchPolicyButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(PROGRESS_DIALOG);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case PROGRESS_DIALOG:
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setMessage("Loading");
            progressDialog.setCancelable(true);
            return progressDialog;
        default:
            return null;
        }
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch(id) {
        case PROGRESS_DIALOG:
            progressDialog.setProgress(0);
        }

    }

    // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int current = msg.arg1;
            progressDialog.setProgress(current);
            if (current >= 100){
                removeDialog (PROGRESS_DIALOG);
            }
        }
    };

    // The method called by the observer (the second thread)
    @Override
    public void update(Observable obs, Object arg1) {

        Message msg = handler.obtainMessage();
        msg.arg1 = ++currentPluginNumber;
        handler.sendMessage(msg);
    }
}

这个解释可以在这个页面上找到,你必须阅读“示例ProgressDialog with a second thread”。

你必须将后台任务中更新UI的部分移到主线程上。这里有一段简单的代码:

runOnUiThread(new Runnable() {

    @Override
    public void run() {

        // Stuff that updates the UI

    }
});

runonuithread的文档。

只需将此嵌套在后台运行的方法中,然后在块中间复制粘贴实现任何更新的代码。只包含尽可能少的代码,否则就会开始破坏后台线程的目的。

在Kotlin中,简单地将代码放在runOnUiThread活动方法中

runOnUiThread{
    // write your code here, for example
    val task = Runnable {
            Handler().postDelayed({
                var smzHtcList = mDb?.smzHtcReferralDao()?.getAll()
                tv_showSmzHtcList.text = smzHtcList.toString()
            }, 10)

        }
    mDbWorkerThread.postTask(task)
}