• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Custom View and Thread

moap

Newbie
Hi,

I have a custom view and a method like this:

Code:
public method() {

do some stuff...
invalidate();  //This changes some image on view according to some stuff;

Thread.sleep(500); //with try-catch

do some stuff...
invalidate();
}

i think this code pauses view thread.I can't make it work.
 
I have a working solution now but i wonder is this the right way...

Code:
public method() {

do some stuff...
invalidate();  //This changes some image on view according to some stuff;

Handler h = new Handler();
Runnable r = new Runnable() {
do some stuff here
invalidate();
}

h.postDelayed(r, 1000);
}
 
is your view responding/reacting to an adapter that you're calling invalidate() on?

You should not modify adapters directly from background threads or you run the risk of getting an IllegalStateException getting thrown. This happens if the View can't update fast enough to keep up with changes the thread is making to the adapter.

Generally though, yes, Handlers are the correct way for Threads to communicate with the UI activity.

You could also do something like this in your Thread though:

Code:
mHandler.obtainMessage(MY_MESSAGE_TYPE, myObjOrBundle).sendToTarget();
then in your activity

Code:
private final Handler mHandler = new Handler() 
{
        @Override
        public void handleMessage(Message msg) 
        {
            switch (msg.what) 
            {
                  case MY_MESSAGE_TYPE:

                      updateMyAdapter(msg.obj);

                      break;
                    
             }
        }
};
http://developer.android.com/reference/android/os/Handler.html#obtainMessage%28int,%20java.lang.Object%29

hope that helps
 
Back
Top Bottom