Search code examples
androidmultithreadinghandlerrunnableui-thread

run code in a non-UI thread android


I have an image application and I'm playing music while the images are displayed. Right now, I have both the functionality in the UI thread.

I want to move the music playback part of it into another thread that is different from the UI thread.

How do I achieve this?

The complication if I use handlers and runnables:

the run() has to have everything that is to be executed but the music code is scattered all over the place because it is event based and there's a different piece of code to execute each time

so the only way i can implement this with handler and runnable is if I have several runnables each doing a particular function which means that all the music code will not run in the same thread, they would run in different threads which is not a good thing.

So how do you do this?


Solution

  • This is what I did:

     public static void startTrack() {
        PLAYER_STATE = IS_PLAYING;
                /*Setup the handler and runnable*/
        mMusicHandler = new Handler() {         
        }; 
    
        mMusicRunnable = new Runnable() {
            public void run() {
                 Log.d(TAG,"inside Music Runnable");
                try {
                    mPlayer.start();        
                } catch (IllegalStateException e) {
                    Log.d(TAG,"ILLEGAL STATE-START");
                    handleIllegalState();
                }
            }
        };
        mMusicHandler.post(mMusicRunnable);
    
    }
    

    So only the start part of the music setup is done on a different thread.