Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there Backgroundworker for java ( like in .Net )

Tags:

java

android

The Backgroundworker that make the process work in background without make lag in application any information about it you will be thanked.

like image 904
Prog_101 Avatar asked Jun 21 '13 06:06

Prog_101


1 Answers

For an Android App use AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

For a Java swing application

For a java swing application use either java.util.concurrent.ExecutorService or javax.swing.SwingWorker.

Depends on what you want to do: If you are using SwingWorker the done method is executed on the Event Dispatch Thread after the doInBackground method is finished. If you use an ExecutorService you must take care that the ui related work is done on the Event Dispatch Thread. E.g. with SwingUtilities.invokeLater.

ExecutorService example from the javadoc

class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept())); 
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }

 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }

SwingWorker example from the swing tutorial

SwingWorker worker = new SwingWorker<ImageIcon[], Void>() {
    @Override
    public ImageIcon[] doInBackground() {
        final ImageIcon[] innerImgs = new ImageIcon[nimgs];
        for (int i = 0; i < nimgs; i++) {
            innerImgs[i] = loadImage(i+1);
        }
        return innerImgs;
    }

    @Override
    public void done() {
        //Remove the "Loading images" label.
        animator.removeAll();
        loopslot = -1;
        try {
            imgs = get();
        } catch (InterruptedException ignore) {}
        catch (java.util.concurrent.ExecutionException e) {
            String why = null;
            Throwable cause = e.getCause();
            if (cause != null) {
                why = cause.getMessage();
            } else {
                why = e.getMessage();
            }
            System.err.println("Error retrieving file: " + why);
        }
like image 139
René Link Avatar answered Oct 17 '22 16:10

René Link