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


当前回答

这显式地抛出一个错误。它说,无论哪个线程创建了一个视图,只有那个线程可以触及它的视图。这是因为创建的视图在线程的空间中。视图创建(GUI)发生在UI(主线程)线程中。你总是使用UI线程来访问这些方法。

在上图中,progress变量位于UI线程的空间中。因此,只有UI线程可以访问这个变量。在这里,您正在通过new Thread()访问进度,这就是为什么您得到了一个错误。

其他回答

当我从Asynctask调用doInBackground而不是使用onPostExecute时,发生了这种情况。

在onPostExecute中处理UI解决了我的问题。

如果你在一个片段中,那么你还需要获取活动对象,因为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))
              })

就我而言, 我在Adaptor中有EditText,它已经在UI线程中。但是,当这个Activity加载时,它会因此错误而崩溃。

我的解决方案是我需要从XML中的EditText中删除<requestFocus />。

如果你不想使用runOnUiThread API,实际上你可以为那些需要几秒钟才能完成的操作实现AsynTask。但在这种情况下,同样在doinBackground()中处理了您的工作之后,您需要在onPostExecute()中返回已完成的视图。Android实现只允许主UI线程与视图交互。

在我的例子中,调用者在很短的时间内调用了太多次就会得到这个错误,我只是简单地把经过的时间检查放在太短的情况下什么都不做,例如,如果函数被调用的时间小于0.5秒就忽略:

    private long mLastClickTime = 0;

    public boolean foo() {
        if ( (SystemClock.elapsedRealtime() - mLastClickTime) < 500) {
            return false;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        //... do ui update
    }