XenoAmp - Free Joomla! 3.0 Template

Run on UI Thread - the painless way

You know there are things in Android that need to run on main thread. There's .runOnUiThread method, that (as usual) is pretty useles, as it exists only in Activity. There's .post method in View(I guess) and for all other issues Google guys will tell you to use AsyncTask, which is ugly and inconvinient beast. OK, sometimes is useful, I do use it, but still hate it. So? Whad do I like to use? Glad you've asked. I use my own runnable:

package pl.qus.xenoamp.helper;

import android.os.Handler;
import android.os.Looper;

public abstract class UIRunnable implements Runnable {

	public abstract void uiRun();
	
	@Override
	public void run() {
		if (Looper.myLooper() == Looper.getMainLooper()) {
			uiRun();
		} else {
			new Handler(Looper.getMainLooper()).post(new Runnable() {
				@Override
				public void run() {
					uiRun();
				}
			});
		}
	}
}

And then in case I want to run something on UI thread, all I have to do is:

new UIRunnable(){
	@Override
	public void uiRun() {
		// this will run on UI thread!
	}}.run();


Better, eh?

© Meet Gavern - Free Joomla! 3.0 Template 2019