E J Chathuranga
E J Chathuranga

Reputation: 925

Android - Runnable object parse into runOnUiThread() params

Please go through the steps,

Created Actor class that inherited with Runnable

public abstract class Actor implements Runnable {


Actor(int queueSize){ 
}

@Override
public void run() {
    onInit();
}
void onInit(){
    // do stuff here
}}

Then I create MyRunner class using Actor

class MyRunner extends Actor{

MyRunner() {
    super(10);
}}

Then in my Activity, I use runOnUiThread as below

Actor runner = new MyRunner();
runOnUiThread(runner);

Then the Main thread freezing, the Whole screen is black and the app is frozen.

I used this thread to implement my code

Where I missed?

Upvotes: 0

Views: 140

Answers (2)

E J Chathuranga
E J Chathuranga

Reputation: 925

The problem was I was using runOnUiThread mechanism incorrectly. In a Android develop it explains very well.

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

runOnUiThread is doing is adding a message into the mainThread that what we need to execute on runtime and it shouldn't be a long process that can freeze mainThread.

Upvotes: 0

savepopulation
savepopulation

Reputation: 11921

It's because you're executing your runnable on MainThread with runOnUiThread You should run your actor in background thread, let it do it's job and post it's result when you need to MainThread with runOnUiThread or Handler

For example:

public abstract class Actor implements Runnable {

        Actor(int queueSize){ 
            // empty block
        }

        @Override
        public void run() {
            onInit();
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        // hello ui i'm done with my job!!
                    }
                });
        }
        void onInit(){
            // do stuff here
        }
}

Create an Executor

private static final int POOL_SIZE_DEFAULT = 4;
private static final int POOL_SIZE_MAX = 10;
private static final int TIME_OUT = 30;

private ThreadPoolExecutor = mThreadPoolExecutor = new ThreadPoolExecutor(POOL_SIZE_DEFAULT,
                POOL_SIZE_MAX,
                TIME_OUT,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(POOL_SIZE_DEFAULT));

And execute your actor:

mThreadPoolExecutor.execute(runner);

Upvotes: 4

Related Questions