简体   繁体   中英

Using ASyncTask for Reading from a File with Google Drive API on Android

I am using Google Drive API on an Android device.

I need to get the contents of a file on Google Drive to a string. Something simple like

String dbData = driveObject.downloadFileToString("db_export.txt");

I am implementing a "GoogleDrive" object. I need to do this without all the mess of tasks and threads and callbacks. However, I can't do it.

Here's an example: I have implemented a method called "findFileByPath" that returns the file ID of a file whose pathname is given as a parameter. However, the Android gods have forced any calls to this -- because it deals with network activity -- to happen in a thread or AsyncTask. The problem is that any pause to wait for the task to complete causes the Google Drive API threads to pause. So....if I do this:

FindFileWithAsyncTask ffwat = new FindFileWithAsyncTask();
ffwat.execute(filePath);
File f = ffwat.get(5, TimeUnits.SECONDS);

where the call to "findFileByPath" is done in a AsyncTask called "FindFileWithAsyncTask" it just hangs everything. The Google Drive API only proceeds when the "get" times out.

HELP! There has got to be a way to do this that can avoid -- or mask -- all the asynchronous BS.

Any clues? Thanks!

It's hard to get rid of AsyncTasks when using network services because otherwise your UI will freeze waiting for the result.

Try to do this:

new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            String dbData = driveObject.downloadFileToString("db_export.txt");
            return dbData;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            File f = new File(s);
        }
    }.execute();

Then you will wait for the result on onPostExecute method. And creating the AsyncTask on the fly will reduce the boring code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM