org.apache.commons.net.ftp.FTPClient.storeFile freezing interaction and animations

831 views Asked by At

I'm using org.apache.commons.net.ftp.FTPClient to communicate with an ftp server via an android app I'm making that records video and then uploads it to the ftp server. Everything is fine until I call storeFile at which point the app prevents any interaction until the uploading is completed. Is there any way around this? I'm currently developing for API lvl 12. My set up is as follows I have a class that calls a service in the background to handle recording of the video as well as the ftp setup. In the FTP class I have any of my fptclient interaction within asynctasks. Here is my method for uploading the file:

public boolean upload(String srcFilePath, String desFileName, String desDirectory)
{
    if(!isLoggedIn())
    {
        return false;
    }
    boolean status = false;
    try
    {
        status = new AsyncTask<String, Void, Boolean>(){
            @Override
            protected Boolean doInBackground(String... args) {
                boolean status = false;
                try {
                    String srcFilePath = args[0];
                    String desFileName = args[1];
                    String desDirectory = args[2];
                    FileInputStream srcFileStream = new FileInputStream(srcFilePath);

                    // change working directory to the destination directory
                    if (changeDirectory(desDirectory,true)) {
                        status = mFTPClient.storeFile(desFileName, srcFileStream);
                    }
                    srcFileStream.close();
                    return status;
                } catch (Exception e) {
                    Log.d(TAG, "upload failed");
                    e.printStackTrace();
                    return false;
                }
            }
         }.execute(srcFilePath, desFileName, desDirectory).get();
    } catch (InterruptedException e)
    {
        e.printStackTrace();
        return status;
    } catch (ExecutionException e)
    {
        e.printStackTrace();
        return status;
    }
    return status;

}

Any help would be immensely appreciated!

Devunwired's post worked! Hoorah!

1

There are 1 answers

2
devunwired On BEST ANSWER

You've started down the right path by placing this long-running task into a background thread using AsyncTask so that it doesn't block the UI. However, by immediately calling get() on the task after executing it, you effectively block the UI thread anyway because get() is a blocking method. From the SDK docs:

AsyncTask.get()

Waits if necessary for the computation to complete, and then retrieves its result.

What you should do is refactor your AsyncTask to make use of the onPostExecute() method. This method will be called when the background task is complete, with your result value as a parameter, and will be called on the UI thread so you can safely update anything you like with it.

HTH