Android – Refresh an imageview in android with an image I got on background

androidbackgroundimageviewmultithreadingsockets

My question concerns this thread-
How to refresh imageview in android

Im too trying to get an image via socket, decode it, and setting it on an imageview.
The socket need to stay open in case another image will be sent and then ill update the imageview again.

I didnt got the part when in the other thread they response not to do it in the main thread.

From the main activity I should open a new thread which will be 'stuck' on "while (true)"
so it can keep listening to up coming images, and when ever a full image had sent, it needs to update the imageview.
But the imageview is in the main thread (main thread equals UI thread?) so its starting to be a bit problematic for me…

Any one?

// ADDED –
this is the asyncTask I had –

public class AsyncTask extends AsyncTask<Void, Void, Void> {
 private DataInputStream dataInputStream = null;
 private ImageView iv = null;

 public RobotMapAsyncTask(DataInputStream dataStream, ImageView imageView) {
     dataInputStream = dataStream;
     iv = imageView;
 }

@Override
protected Void doInBackground(Void... params) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    byte[] byteChunk = new byte[1024];
    Bitmap bitmap = null;
    int c;

    if (dataInputStream != null) {
        while (true) {
            try {
                byteChunk = new byte[1024];
                while ((c = dataInputStream.read(byteChunk)) != -1){
                    buffer.write(byteChunk, 0, c);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            bitmap = BitmapFactory.decodeByteArray(byteChunk, 0, byteChunk.length);

            if (bitmap != null) {
                //runOnUiThread(new Runnable() {
                    //public void run() {
                        //iv.setImageBitmap(bitmap);
                    //}
               // }); 
            }
        }
    }

    return null;
}

but then I obvious cant call runOnUiThread because this is not an activity…

Best Answer

After you get a new image, call this:

runOnUiThread(new Runnable() {
        public void run() {
            imView.setBackgroundResource(yourResource);
        }
    });   

Just make the obvious changes to fit your code