how to pause and resume a download in javafx

779 views Asked by At

I am building a download manager in javafx

I have added function to download button which initialises new task.More than one download is also being executed properly.

But I need to add pause and resume function. Please tell how to implement it using executor. Through execute function of Executors, task is being started but how do i pause & then resume it??

Below I am showing relevant portions of my code. Please tell if you need more details. thanks.

Main class

public class Controller implements Initializable {

    public Button addDownloadButton;
    public Button pauseResumeButton;
    public TextField urlTextBox;
    public TableView<DownloadEntry> downloadsTable;
    ExecutorService executor;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        // here tableview and table columns are initialised and cellValueFactory is set

        executor = Executors.newFixedThreadPool(4);
    }

    public void addDownloadButtonClicked() {
        DownloadEntry task = new DownloadEntry(new URL(urlTextBox.getText()));
        downloadsTable.getItems().add(task);
        executor.execute(task);
    }


    public void pauseResumeButtonClicked() {
        //CODE FOR PAUSE AND RESUME
    }
}

DownloadEntry.java

public class DownloadEntry extends Task<Void> {

    public URL url;
    public int downloaded;
    final int MAX_BUFFER_SIZE=50*1024;
    private String status;

    //Constructor
    public DownloadEntry(URL ur) throws Exception{
        url = ur;
        //other variables are initialised here
        this.updateMessage("Downloading");
    }

    @Override
    protected Void call() {
        file = new RandomAccessFile(filename, "rw");
        file.seek(downloaded);
        stream = con.getInputStream();

        while (status.equals("Downloading")) {
            byte buffer=new byte[MAX_BUFFER_SIZE];

            int c=stream.read(buffer);
            if (c==-1){
                break;
            }
            file.write(buffer,0,c);
            downloaded += c;
            status = "Downloading";
        }
        if (status.equals("Downloading")) {
            status = "Complete";
            updateMessage("Complete");
        } 
        return null;
    }

}
1

There are 1 answers

2
VinceOPS On

You may be interested in Concurrency in JavaFX.

I guess you should also have a look at pattern Observer.

By the way I think you should not use constant string as a status ("Downloading", etc), creating an enum would be a better approach.

In your loop, around the read/write part, there should be a synchronization mechanism, controlled by your pause/resume buttons (see the two links).