James L.
James L.

Reputation: 14515

Is this a safe usage of Android Threading?

I have created a game in Android using vanilla Android SDK and threading. I have most of my game logic contained in Runnables, which are posted to Handlers or Views.

For example:

Post runnable to a view and edit that view in the runnable

private int currentRotation =0;
private Runnable rotateRunnable = new Runnable(){
    @Override
    public void run() { 
        currentRotation+=DEFAULT_ROTATION_SPEED * direction;
        Gravity_MeteorView.this.setRotation(currentRotation);
        Gravity_MeteorView.this.postIfAlive(this,2*MovingView.HOW_OFTEN_TO_MOVE);
    } 
};
public Gravity_MeteorView(Context context) {
    super(context);//ImageView

    //...
    this.post(rotateRunnable);
}

Post a Runnable to a handler and edit some view in the Runnable

Handler spawningHandler = new Handler();
public final void spawnMeteorShower(final int numMeteors,final int millisecondsBetweenEachMeteor) {
    spawningHandler.post(
            new Runnable(){
            private int numSpawned=0;

            @Override
            public void run() {
                Gravity_MeteorView bob = new Gravity_MeteorView(context);
                someLayout.addView(bob);
                //...
                if(numSpawned<numMeteors){
                    spawningHandler.postDelayed(this,millisecondsBetweenEachMeteor);
                }
           }
       });
}

For the most part everything works. Meteors spawn and rotate consistently. Very, very rarely though, the meteors will spawn but be invisible and immune to damage. I was wondering if these strange errors could be due to my poor handling of the game threading.

I noticed in the Android docs

[modifying] the ImageView from the worker thread instead of the UI thread...can result in undefined and unexpected behavior, which can be difficult and time-consuming to track down.

http://developer.android.com/guide/components/processes-and-threads.html

It seems like the first snippet may be fine, while the second could cause problems (if it's not running on UI thread or something). Am I violating Android best practices here?

Thank you!

Upvotes: 1

Views: 65

Answers (1)

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

It seems like the first snippet may be fine, while the second could cause problems (if it's not running on UI thread or something). Am I violating Android best practices here?

spawningHandler is attached to UI thread Looper, because you work with Views there. Otherwise you would get a crash because you can't do that from a worker thread.

It is thread-safe because there is no parallel execution. All Runnables you post go to the same MessageQueue. I don't see the issue with threading in the code you posted.

Upvotes: 1

Related Questions