Search code examples
androidandroid-activityextendsoundpool

Is there anything wrong with exending Activity in order to use runOnUIThread?


I have a class defined like so: (I have pages of code, but I'm only posting the relevant parts for readability).

Now, there's nothing 'wrong' with it, per se and it works great, but someone told me a few days ago that it wasn't a good idea to extend 'Activity' on classes from which I am going to make objects (ie, classes that I will make instances of) - And I do make a MyGLRenderer object at some point in my code.

So my questions are:

1) Is it 'bad' to extend Activity?

2) If so, why?

3) If so, how can I use runOnUIThread to create my soundPool class?

If it's OK to do then I will leave it, but if it potentially could create big problems, I'd be grateful if someone could let me know of an alternative way to access it.

(my classes are separate files, not outer and inner classes and I need to create my SoundPool object in this class as have all of my initiallisations in this class).

Code

public class MyGLRenderer extends Activity implements GLSurfaceView.Renderer{

//Various pieces of code

public void onSurfaceChanged(){

runOnUiThread(new Runnable() {
        public void run() {
           sound = new soundMan(curView.getContext()); 

}

}


Solution

  • Is it 'bad' to extend Activity?

    If it is not a real activity, started by startActivity(), then yes, it is 'bad'.

    If so, why?

    Because lots of things will not work correctly. It is a minor miracle that runOnUiThread() works, and there's no assurance that it will continue to work in the future as Activity is modified. In fact, it's entirely possible that it will not work on some older devices, or ones where the manufacturer has tinkered with Activity in ways that work for real activities but will break for misuses like yours.

    If so, how can I use runOnUIThread to create my soundPool class?

    You don't. Use other facilities, like calling post() on a View or Handler, to route work to be done on the main application thread.