Can I sleep or stop AsycTask's execution without affect to UI? Is there any way other than creating a new Thread to achieve this (I am sure this doesn't affect UI though)?
Explanation:
public class MyAsync extends AsyncTask<....>{
#Override
..doInbackground(){
//do something
for(....){
//sleep this Asynctask
//I want to delay my for loop
}
//do something
}
}
Creating a new Thread isn't what I want as follow:
//inside doInBackground()
new Thread(new Runnable(){
#Override
public run(){
for(..){
Thread.sleep(1000);//sleeping for 1 second
}
}
});
//other parts
P.S. I am using AsyncTask in Service to run in background every N seconds.
If you call Thread.sleep(1000) from inside the doInBackground() method, this will not affect the UI since doInBackground() is called on a background thread.
Related
I am using AsyncTask to run a background operation. Of course switching to another thread while already working in a background thread does not make a lot of sense in general, except the other thread is the UI thread. This what I would like to to: While the task is running I need to "access" the UI, e.g. to show a dialog to ask the user how to proceed.
run the background task
stop the task at some point to get user feedback
switch to the UI thread to show dialog and ask for input
switch back to background task and continue work
How can this be done? I thought I could use Runnable with myActivity.runOnUiThread(runnable) but this does not work:
private void copyFiles() {
CopyTask copyTask = new CopyTask(this);
copyTask.execute();
}
// CustomAsyncTask is a AsyncTask subclass that takes a reference to the current
// activity as parameter
private class CopyTask extends CustomAsyncTask<Void, Void, Void> {
private doCopy;
#Override
protected Boolean doInBackground(Void... params) {
// Custom code, e.g. copy files from A to B and check for conflict
for (File file : allFiles) {
doCopy = true;
if (isConflict(file)) {
// Stop current thread and ask for user feedback on UI Thread
Runnable uiRunnable = new Runnable() {
public void run() {
// Pos 1. --> Execute custom code, e.g. use AlertDialog to ask user if file should be replaced...
doCopy = false;
synchronized (this) {
this.notify();
}
}
});
synchronized(uiRunnable) {
// Execute code on UI thread
activity.runOnUiThread(uiRunnable);
// Wait until runnable finished
try {
uiRunnable.wait();
}
catch (InterruptedException e ) {
e.printStackTrace();
}
}
}
// Pos 2. --> Continue work
if (doCopy)
copyFromAToB(File);
}
return null;
}
}
Within doInBackground() (--> in a background thread) the AsyncTask calls activity.runOnUiThread(uiRunnable). Next uiRunnable.wait() is called. Regarding to the docu wait() should do the following:
Causes the calling thread to wait until another thread calls the
notify() or notifyAll() method of this object.
Thus the background thread should wait to continue its work until this.notify() (== uiRunnable.notifiy()) is called on another thread (= the UI thread), shouldn't it?
Well, id does not wait! After calling uiRunnable.wait() the background thread immediately continues by jumping to if (doCopy).... It seems that the background thread and the main thread are executed in parallel (not surprising since this is what thread do...) and thus its a race condition whether doCopy = false on the UI thread or if (doCopy) on the background thread is reached first.
How is this possible? Why doesn't wait() works as described? Or am I getting something wrong?
Thank you very much!
EDIT:
To avoid missunderstandings: Of course I know the lifecycle methodes of AsyncTask but as far as I understand them, they are not what I am looking for (see my reply to the comment blow).
Interrupting the AsyncTask as soon as a UI interaction is necessary, query the UI and start a new AsyncTask would be possible of course. However this would result in code which is very hard to read/understand/maintain.
As I understand the docu of wait() everything should work fine here. Primary question is not how to do UI interaction during the lifecycle of an AsyncTask but why wait()does not work as expected.
The Basics
When you start an AsyncTask first the onPreExecute() method runs on the UI thread. You can override this method to make changes to the UI prior to the doInBackground() method running.
After the doInBackground() method finishes, the onPostExecute() method runs on the UI thread, so you can use this to make changes to the UI from here. If you need to make regular changes to the UI Thread during the doInBackground() method you override the onProgressUpdate() method which runs on the UI Thread, and then call it from within doInBackground(), which will allow you to periodically update the UI.
You could use something like the following;
private class DoStuffTask extends AsyncTask {
#Override
protected void doInBackground(Object... args) {
// Do stuff
onProgressUpdate(x);
// Do more stuff
}
#Override
protected void onProgressUpdate(Object... args) {
// Update your UI here
}
}
Now if this doesn't quite do it and you want the AsyncTask to wait for input during the doInBackground() method it is probably worth considering using multiple AsyncTasks instead. You can then finish each AsyncTask, ask for input, and then start a new AsyncTask to continue working.
Given that AlertDialog instances are asynchronous, this is probably the preferred solution because you can start the next AsyncTask from the AlertDialog itself.
Using wait() in an AsyncTask
If you would prefer to use a single AsyncTask you can use wait from within your AsyncTask to prevent execution continuing until some condition is met. Instead of using a new Runnable we are just using two threads in this instance, the thread running doInBackground() and the main thread, and we are synchronizing on the AsycTask itself.
Example below;
public class TestTask extends AsyncTask{
private boolean notified;
private Promptable p;
public interface Promptable { public abstract void prompt(); }
public TestTask(Promptable p){
this.p = p;
}
#Override
protected Object doInBackground(Object... arg0) {
Log.d("First", "First");
onProgressUpdate(null);
synchronized(this){
while(!notified){
try{
this.wait();
}
catch(InterruptedException e){ }
}
}
Log.d("Second", "Second");
return null;
}
#Override
protected void onProgressUpdate(Object... args){
synchronized(this){
notified = true;
p.prompt();
this.notify();
}
}
}
In the example above, assume that your Activity is parsed into the AsyncTask's constructor, and that it implements an interface we create called Promptable. You'll notice that even though we're calling wait() we are putting it in a while loop. If we didn't do this, and somehow notify() got called before wait() then your thread would lock up indefinitely. Also, you can't depend on the fact that your thread will wait forever, so the while loop ensures that it doesn't continue until notify is called.
I hope this helps.
I just solved the problem myself. I had multiple calls for syncCustomers() due to a dialog closing event problem. I solved it by providing the parent JFrame in the JDialog constructor. Pretty stupid error on my side.
My application contains a task that synchronizes with a webservice and a local database. This task may take up to several minutes. Thus I want to notify the user about this time consuming process with a simple dialog (Swing). The user is not supposed to continue working while the sync process is running.
So I thought of:
open modal dialog with the notification for the user
start the sync process in a separate thread
close modal dialog after sync process is done
User clicked on the button to start sync process:
private void syncCustomers() {
if (checkWebserviceAuth()) {
SyncDialog dialog = new SyncDialog();
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
SyncCustomersTask task = new SyncCustomersTask(dialog, getCoach());
task.run(); // task.start() will result in the same problem
} else {
openAuthorizeDialog(true);
}
}
public class SyncDialog extends javax.swing.JDialog {
public SyncDialog() {
initComponents();
// I already noticed that the modal dialog won't work for me since it interrupts within syncCustomers()
//this.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
this.setTitle(Application.getApplicationTitle());
}
...
}
public class SyncCustomersTask extends Thread {
private void doWork() {
System.out.println("Start doWork() and sleep for 10 seconds...");
try {
// for testing purpose
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
System.out.println("Done with doWork().");
}
#Override
public void run() {
doWork();
if (getCallback() != null) {
System.out.println("Invoke callback...");
getCallback().dispose();
System.out.println("Callback invoked.");
}
}
...
}
This will result in an infinite loop of:
Start with doWork()...
Start doWork() and sleep for 10 seconds...
Done with doWork().
Invoke callback...
Callback invoked.
If I comment out
getCallback().dispose();
, the loop will stop after the second execution:
Start with doWork()...
Start doWork() and sleep for 10 seconds...
Done with doWork().
Invoke callback...
Callback invoked.
Start with doWork()...
Start doWork() and sleep for 10 seconds...
Done with doWork().
Invoke callback...
Callback invoked.
I don't get it. What fires the thread to execute over and over again?
I guess this whole thing isn't a good idea to start with, but I wasn't able to get things like ProgressMonitor working either. :(
Call start(), not run(). The latter will simply execute the thread, but not in a separate thread! The start() method will instantiate a new thread, and only then invoke your run() method in that new thread.
This is a surprising common problem, btw.
invoking run() does not execute code in a new thread.
I have an Android service which spawns a thread.This thread waits for network data and after receiving that data I want to show Ok Cancel Dialogbox.
I was getting exception can't create handle that should have Looper.prepare().I added Looper.prepare() and Looper.loop() then now I am not getting any exception but its waiting infinitely.
Instead of using a sole thread it's better to use an AsyncTask which is also a speacialized thread for Android.
You can wait for data in the AsyncTask's doInBackGround method and when you received data you can call publishProgress() which will invoke onProgressUpdate method of AsyncTask.
At onProgressUpdate you can update the UI without blocking the main thread and also this is the preferred way of doing long time operations in background like network listening etc.
Check AsyncTask for more info and how to use it.
http://developer.android.com/reference/android/os/AsyncTask.html
You can invoke the UI thread(showing alert dialog) in non-UI thread by using handlers as like below code
new Thread(new Runnable()
{ public void run()
{
try {
///do your stuff in
mHandlerShowDialog.post(mUpdateShowDialog);
///do your struff
}
} ).start();
final Handler mHandlerShowDialog= new Handler();
final Runnable mUpdateShowDialog = new Runnable() {
public void run() {
// show your dialog here
}
};
I have a main form with a button, that when pressed, should start a new count-down timer thread.
This is the code in the button's action listener:
Counter c = new Counter(timeToFinish);
This is the code for the Counter class:
class Counter implements Runnable {
int waitingTime = 0;
Thread myCounter = new Thread(this);
public Counter(int waitingTime)
{
this.waitingTime = waitingTime;
myCounter.run();
}
public void run(){
//Start countdown:
do
{
waitingTime -= 1;
try {
Thread.sleep(1000);
System.out.println(waitingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (waitingTime >= 0);
}
}
The problem is, when I create a new instance of the Counter class, it pauses the whole program, not just that thread! The problem must be with "Thread.sleep".
Because you are directly calling the run method.
Instead you should wrap it in a Thread and start the thread.
For e.g., replace
myCounter.run();
by
new Thread(this).start();
Just because you call the run method from the Counter constructor. That's not how it works with threads. You'll have to remove this call, wrap the Runnable in a Thread instance and call start() on the thread:
new Thread(new Counter(2)).start();
You aren't actually start()ing multiple threads.
The Thread.run() method simply runs the code associated with the thread, like any other normal function. It doesn't start a separate thread.
You need to call Thread.start(), to start a new thread and run your code in it.
You should use start() method of your thread. Use
c.start();
otherwise you have a class and you are invoking one of its methods, and of course it is running in main thread and sleeping the main thread.
You're calling run directly, it'll run in the current thread, and sleep the current thread, which I guess is the event thread. This cause the pause in your program.
You should use SwingUtilities class
see
http://www.java2s.com/Code/Java/Threads/InvokeExampleSwingandthread.htm
// Report the result using invokeLater().
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resultLabel.setText("Ready");
setEnabled(true);
}
});
}
};
I want a thread to execute in the background every 500 milliseconds. To do that, I extended a Thread, implemented ActionListener and put the class that I extended into a Timer. The Timer calls run() every 500 milliseconds. However, my whole Swing GUI freezes up when this thread is downloading stuff from the Internet. I want it to run in the background, without freezing up the GUI while it waits for IO to finish. I also the downloader to finish downloading before we wait 500 milliseconds.
gogogo() is called to initialize the whole process:
public final class Downloader extends Thread implements ActionListener
{
public static void gogogo()
{
t= new Downloader();
new Timer(500, (ActionListener) t).start();
}
public void run()
{
doStuff(); //the code that i want repeatedly called
}
public void actionPerformed(ActionEvent e)
{
run();
}
}
Just start the thread once, make it loop, and do Thread.sleep(500L) with each iteration. That probably makes more sense that starting a brand new thread every 500ms. No reason to incur the associated cost if you can avoid it.
Instead of using the swing timer try using the java util timer or the ScheduledExecutorService. the swing timers share a pre-existing timer thread and that may be causing the freezing.
A recommendation from the java tutorial:
In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatch thread. However, you might use a general-purpose timer if you don't plan on touching the GUI from the timer, or need to perform lengthy processing
If your GUI is freezing up, then your lengthly task (doStuff) is probably running on the Event Dispatching Thread. While it hogs that thread, other actions can't use it.
If you're trying to run a task repeatedly, you may be better off with the TimerTask class
public class Downloader extends TimerTask {
public void run() {
doStuff();
}
}
... elsewhere ...
Timer myTimer = new Timer();
public void gogogo() {
myTimer.scheduleAtFixedRate(new Downloader(), 0, 500);
}
That's a little different in that your task will be scheduled to run every 500 ms rather than with a 500 ms delay. When you're done, just use myTimer.cancel() to stop the repeating task execution.
You need to start the thread on each timer action. Calling the thread's run() method does not start the thread.
public void actionPerformed(ActionEvent e)
{
//run();
Downloader t = new Downloader();
t.start();
}
Might be better to use an anonymous class for the actionlistener. Excuse my java syntax but I have not verified it...
new Timer(500,
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//run();
Downloader t = new Downloader();
t.start();
}
}).start();
Or without the timer...
public static void gogogo()
{
t= new Downloader();
t.start();
}
public void run()
{
while(true){
doStuff(); //the code that i want repeatedly called
Thread.sleep(500);
}
}
Hmm, most likely all you need to do is reduce the thread priority, so it doesn't eat all your resources.