I don't understand "the timing is always off"? what does it mean?
I am not so clear about your question and your description, but Is it true: You want to postpone the execution of a code block after some period of time?
If it's the case, you must consider whether your new Handler().postDelayed(..)
is called inside another UI thread or not. Try this if it's an activity's process:
your_activity_instance.runOnUiThread(new Runnable()
{
@Override
public void run()
{
//delay with thread
try{
Thread.sleep(1500);
}catch(.....)
{..}
//your work load here
}
});
NOTE:
Handler.postDelayed() does NOT create a separated thread for your code block, but only append a new message (related to your Runnable instance) with timer sticker into current thread's message queue.
activity.runOnUiThread() do the similar thing but the
Runnable.run()
has to wait until the system comes back to activity UI thread then be excuted. This's helpful when you want to do some activity's job in its child thread.
Update for modified question:
I may understand your intention: trying to execute wavPlayer.start()
and mp3Player.start()
at the same time; but your current solution is not nice or even it is impossible:
In the same thread which you are using handlers, you will hardly sync the 2 functions (as I mention, handler.run() doesn't spawn separated thread).
you can not pin down the exact time stamp of
hanler.run()
because the system controls when the message is appended to the queue, the post delayed is a relative value.
My suggested solution:
You spawn a separated thread for each player.
Before each thread start(), you mark the time stamp (may use millisecs, not such of accuracy to use nano)
In the second thread which is called later, you also pass to it the DELTA of time stamps (diff between markers). Then use
Thread.Sleep()
orHandler.postDelayed()
for your adjustment of sync.