4

为什么这段代码有效?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.i("onCreate", Thread.currentThread().toString());
    textView = (TextView) findViewById(R.id.textView);
    imageView = (ImageView) findViewById(R.id.imageView);

    HandlerThread thread = new HandlerThread("myHandlerThread");
    thread.start();
    mUiHandler = new Handler(thread.getLooper());
    mUiHandler.post(new Runnable() {
        @Override
        public void run() {
            Log.i("Thread: ", Thread.currentThread().toString());
            Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
            textView.setText("Hello Cats");
            imageView.setImageResource(R.mipmap.ic_launcher);
        }
    });

}

我从某个地方读到唯一可以与 UI 对象通信的线程是 UI 线程,或者我错过了一些东西

我有一些研究,但还没有找到答案,请帮助,非常感谢你们。

这是我从日志中得到的

10-13 18:47:42.888 23841-23841/th.co.me.sampleapp I/onCreate: Thread[main,5,main] 10-13 18:47:42.891 23841-24041/th.co.me.sampleapp I/Thread:: Thread[myHandlerThread,5,main]

更新 1

我从@nshmura 尝试了这段代码,但发生了错误,现在让我很困惑

   textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        HandlerThread thread = new HandlerThread("myHandlerThread");
        thread.start();
        mUiHandler = new Handler(thread.getLooper());
        mUiHandler.post(new Runnable() {
            @Override
            public void run() {
                Log.i("Thread: ", Thread.currentThread().toString());
                Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
                textView.setText("Hello Cats");
                imageView.setImageResource(R.mipmap.ic_launcher);
            }
        });

    }
});

android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图。

4

4 回答 4

0

Handler 对象向创建它的线程注册自己。它提供了一个将数据发送到该线程的通道。例如,如果您在 Activity 的 onCreate() 方法中创建一个新的 Handler 实例,它可以用于将数据发布到主线程。可以通过 Handler 类发布的数据可以是 Message 或 Runnable 类的实例。

因此,根据以下行,您的处理程序应该属于 HandlerThread。

mUiHandler = new Handler(thread.getLooper());

我理解 OnCreate() 的一件事是主线程,但 OnClick 侦听器是单独的类。这意味着存在上下文差异。

例如:

// onCreate() we are writing like this
 Toast.makeText(this, "Hello Cats!", Toast.LENGTH_SHORT).show();
// but in Onclick method we are writing like this
 Toast.makeText(MainActivity.this, "Hello Cats!", Toast.LENGTH_SHORT).show();
于 2016-10-13T12:52:42.670 回答
0

只有在以下情况android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.下才会抛出异常:

  1. 从非 ui 线程调用
  2. 该调用需要更改布局。例如,如果 a 的大小(宽度和高度)TextView应该扩展,因为字符串太长

因此,如果您的 ui 操作没有导致布局更改(创建或重新创建),则可能不会抛出异常。

于 2016-10-13T12:34:40.687 回答
-1

像这样检查:

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HandlerThread thread = new HandlerThread("myHandlerThread");
            thread.start();
            mUiHandler = new Handler(thread.getLooper());
            mUiHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.i("Thread: ", Thread.currentThread().toString());
                    Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
                    textView.setText("Hello Cats");
                    imageView.setImageResource(R.mipmap.ic_launcher);
                }
            });

        }
    });

会发生异常:

  android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
      at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
      at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942)
      at android.view.ViewGroup.invalidateChild(ViewGroup.java:5081)
      at android.view.View.invalidateInternal(View.java:12719)
      at android.view.View.invalidate(View.java:12683)
      at android.view.View.invalidate(View.java:12667)
      at android.widget.TextView.checkForRelayout(TextView.java:7156)
      at android.widget.TextView.setText(TextView.java:4347)
      at android.widget.TextView.setText(TextView.java:4204)
      at android.widget.TextView.setText(TextView.java:4179)

也许ViewRootImpl.checkThread()没有调用Activity.onCreate()

于 2016-10-13T12:21:05.053 回答
-2

试试这个代码

mHandler = new Handler();

new Thread(new Runnable() {
    @Override
    public void run () {
        // Perform long-running task here
        // (like audio buffering).
        // you may want to update some progress
        // bar every second, so use handler:
        mHandler.post(new Runnable() {
            @Override
            public void run () {
                // make operation on UI - on example
                // on progress bar.
            }
        });
    }
}).start();
于 2016-10-13T12:03:11.557 回答