Handling UI from other thread

牧云@^-^@ 提交于 2019-12-10 18:46:46

问题


I have a class which extends the Runnable. This class performs some heavy operation (basically downloads the image from network) in different thread. I want to update the UI (display the downloaded image to an ImageView) from this class. I have tried using handler but did not succeed. Here is my code:

class DataReceiver implements Runnable
{
    public Bitmap bmp;
    Public Handler uiHandle;
    @Override
    public void run()
    {
        while(true)
        {
            //do image download process here
        }
    }
}

In main activity

ImageView img = (ImageView)findViewById(R.id.dispImg);
DataReceiver dr=new DataReceiver();

Handler uiHandler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {
        updateUI();
    }
}

dr.uiHandle = uiHandler;
(new Thread(dr)).start();

public void updateUI()
{
    img.setBitmap(dr.bmp);
}

Is it the correct method for updating UI?


回答1:


almost ;D you need on the class thread add the that linebefore while do:

while(true)
    {
      //do image download process here
    }
uiHandle.sendEmptyMessage(0);



回答2:


You could use AsyncTask instead, do what you're currently doing in run() in doInBackground, and then do the UI update in the task's onPostExecute.




回答3:


To update the UI from another thread use

activity.runOnUIThread(new Runnable());


来源:https://stackoverflow.com/questions/5991178/handling-ui-from-other-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!