Question

Why Android have this behavior and how fix the problem ? I just alloc a new object in a new Thread, this Object take a view to post a Log message.

My activity send messages to a new object :

public class WebView2ImageView extends Activity
{
    private View rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_view);
        this.rootView = (View) findViewById(R.id.linear1);
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        // This work :
        new Page(WebView2ImageView.this.rootView, "This message is displayed");

        // This don't work :
        (new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                // (But Work if I wait with Thread.sleep(ms)) :
                new Page(WebView2ImageView.this.rootView, "This one not, why ?");
            }
        })).start();
    }
}

The object receiver :

public class Page
{
    public Page(View rootView, final String message)
    {
        rootView.post(new Runnable()
        {
            @Override
            public void run()
            {
                Log.e("", message);
            }
        });
    }
}
Était-ce utile?

La solution

We must change the constructor :

new Page(WebView2ImageView.this, "This message is displayed");

And use runOnUiThread :

this.webView2ImageView.runOnUiThread (new Runnable() [...]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top