简体   繁体   中英

Android : is it safe to create a View and a Handler in a worker thread

The android docs states that :

The Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread.

My first question is : is it safe to go against this rule/advice by creating a View in a worker thread, then using a handler to attach it to the window. (See code below to illustrate what I mean).

It seems OK, because I can't see any situation where 2 threads modify the view at the same time. Do I miss something ?

public class DemoActivity extends Activity {

    RelativeLayout rootLayout;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler(Looper.getMainLooper());
        setContentView(R.layout.activity_main);
        rootLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
        myThread.start();
    }

    private Thread myThread = new Thread(){
        @Override
        public void run() {
            final TextView textView = new TextView(DemoActivity.this);
            textView.setText("I'm a TextView created in a worker Thread");
            handler.post(new Runnable() {
                @Override
                public void run() {
                        rootLayout.addView(textView);
                }
            });
        }
    };

My second question is more about the thread creating the Handler:

Is it OK to create the Handler in the worker thread itself? (see code below)

Is there a risk of memory leak ?

   private Thread myOtherThread = new Thread(){
        @Override
        public void run() {
            final TextView textView = new TextView(DemoActivity.this);
            textView.setText("I'm a TextView created in a worker Thread");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                        rootLayout.addView(textView);
                }
            });

            //just to illustrate that the thread don't terminate immediately
            //but it don't touch the textView anymore.
            while(true){  
                doStuff();
            }
        }
    };
}
  1. No, as said, it is not safe.

Being not safe, Android exposes a single thread model that ensures UI is not modified by different threads at the same time. It is done on purpose to avoid such issues.

  1. Yes I think it is okay, because it is another thread :)

Also take a look at runOnUiThread()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM