Is this a bug or function? In some cases, you can access the user interface thread from a task that is not running on the user interface thread.

Developer.android.com says:

Only objects running in the user interface thread have access to other objects in this thread.

However, all of the following examples (A..C cases) should not work, as they try to modify the object in the user interface thread. But in reality, cases A and B have access to the object (TextView) in the user interface thread.

Here we start a new thread from MainActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new Thread(new ClientThread()).start();
}

Case A (the object in the user interface thread has changed)

class ClientThread implements Runnable {
    public void run() {
        final TextView myTextView = (TextView) findViewById(R.id.myTextView);
        myTextView.setText("Hello there!");
    }
}

Case B (an object in the user interface thread changes several times)

class ClientThread implements Runnable {
    public void run() {
        final TextView myTextView = (TextView) findViewById(R.id.myTextView);
        for (int i=0; i < 600; i++) {
            myTextView.setText("Hello there!");
        }
    }
}

C ( )

class ClientThread implements Runnable {
    public void run() {
        final TextView myTextView = (TextView) findViewById(R.id.myTextView);
        try {Thread.sleep(900);} catch (InterruptedException e) {};
        myTextView.setText("Hello there!");
    }
}

C :

CalledFromWrongThreadException: , .

- ? , , ( ).

+4
1

- . . , , . , , .

+1

All Articles