Reputation: 369
I'm working on an app that synchronizes some graphic UI events with an audio track. Right now you need to press a button to set everything in motion, after onCreate exits. I'm trying to add functionality to make the audio/graphical interaction start 10 seconds after everything is laid out.
My first thought is, at the end of onCreate, to make the UI thread sleep for 10000 miliseconds using the solution here and then to call button.onClick(). That seems like really bad practice to me, though, and nothing came of trying it anyway. Is there a good way to implement this autostart feature?
Upvotes: 0
Views: 103
Reputation: 837
Yes, putting the UI thread to sleep isnt a good idea.
Try this
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(task, 10, TimeUnit.SECONDS);
Upvotes: 0
Reputation: 2366
Handler handler=new Handler();
Runnable notification = new Runnable()
{
@Override
public void run()
{
//post your code............
}
};
handler.postDelayed(notification,10000);
Upvotes: 0
Reputation: 68187
Never ever put sleep/delay on UI-thread. Instead, use Handler
and its postDelayed method to get it done inside onCreate, onStart or onResume of your Activity. For example:
@Override
protected void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//do whatever you want here
}
}, 10000L); //the runnable is executed on UI-thread after 10 seconds of delay
}
Upvotes: 1