Search code examples
androidimageviewandroid-4.0-ice-cream-sandwichandroid-imageview

Displaying images without locking the "main" thread


I've run into an issue with my application. I'm porting a series of internal iPad apps from iOS to android and image sequences are integral to their design. They require the standard fullscreen stop, start, pause functionality all of which is working fine from a subclass of ImageView. But it's only currently displaying 2 out of 300 images it gets through before the locked process dialog keeps coming up.

So is there a "good" way to set an image/background without locking the main thread?

Just FYI AnimateDrawable wasn't ideal for what I needed as it doesn't offer pause/resume functionality and the number of sequences I have are easily in the hundreds and are on average a few hundred frames long.


Solution

  • You can load images asyncronously using AsyncTask

    Just put the code related to image loading in doInBackground method and try to set an indicator like a progress bar or a progress dialog so you will start showing the dialog or bar at the begining of loading and after finish dismiss the dialog using handlers in onPostExecute method

    Sample code :

     class SomeClass extends Activity {
    protected ProgressDialog pd ;
    protected Handler handler = new Handler(){
    @Override 
    public void handleMessage(int what){
       if(pd.isShowing())
          pd.dismiss();
    }
         .....
    
         class LoadImageTask extends AsyncTask<URL, Integer, Long> {
              protected void onPreExecute(Long result) {
                pd = ProgressDialog.show(getContext(),"Title","Message");
             }
    
             protected Long doInBackground(URL... urls) {
    
              //Load IMAGEs code
                 return totalSize;
             }
    
    
    
             protected void onPostExecute(Long result) {
                 //finish loadiing images
                  handler .sendEmptyMessage(0);
             }
         }
        }
    

    I hope this would help you