AsyncTask - How to use a Handler with postDelayed(Runnable, int) inside an AsyncTask?
AsyncTask - How to use a Handler with postDelayed(Runnable, int) inside an AsyncTask?
I'm trying to write from a BufferedInputStream, I used while statement before and it worked well, but now I want to delay the loop of writing each 250 millisecond. So, I thought about using a Handler with postDelayed.
while
250 millisecond
Handler
postDelayed
This was my code using while:
while
while (count = input.read(data)) > 0)
//File writing...
But when I turned it to this:
new Handler().postDelayed(new Runnable()
@Override
public void run()
try
//File writing...
catch (IOException e)
, 250);
I got this RuntimeException:
Can't create handler inside thread that has not called Looper.prepare().
I think, it says that I cant create a handler inside a thread (AsyncTask/Thread), but I hope someone has a workaround for this.
Thanks in advance!
2 Answers
2
Try calling Thread.sleep() instead of calling postDelayed on a hanler, because inside the doInBackround method you are already in backround thread and there is no issues in calling sleep for a small time interval
try
Thread.sleep(250)
//File writing...
catch (IOException e)
catch (InterruptedException e)
`
Thread.sleep(250)
while
Yeah, Handler posts messages to the Thread that you create it on - this means you created your handler on another thread where the looping thing isn't set up by default (whereas on main thread the looping thing is set up by default - thats why handlers work right away when created on main thread).
Handler
Thread
You can use standard Java Timer for scheduling actions in future, this timer uses its own thread to execute your actions, example is:
Timer
Timer timer = new Timer();
timer.schedule(new TimerTask()
@Override
public void run()
// your action
, your delay);
Another solution would be to use RxJava, however if you are unfamilliar with it, it takes some time to learn. Example of code that runs your action on another thread, returns result on main thread and is delayed by 250 milliseconds :
(Kotlin here) Completable.fromAction(object : Action
override fun run()
// your action
).subscribeOn(Schedulers.newThread())
.subscribeOn(AndroidSchedulers.mainThread())
.delay(250, TimeUnit.MILLISECONDS)
.subscribe()
AsyncTask is generally obsolete to do any threading
AsyncTask
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks, it worked! I did put
Thread.sleep(250)insidewhilestatement and did the trick!– kh3e
Aug 29 at 22:16