简体   繁体   English

在Android上使用ASyncTask通过Google Drive API读取文件

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

I am using Google Drive API on an Android device. 我在Android设备上使用Google Drive API。

I need to get the contents of a file on Google Drive to a string. 我需要将Google云端硬盘上文件的内容获取为字符串。 Something simple like 简单的东西

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

I am implementing a "GoogleDrive" object. 我正在实现“ GoogleDrive”对象。 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. 这是一个示例:我实现了一个名为“ findFileByPath”的方法,该方法返回路径名作为参数给出的文件的文件ID。 However, the Android gods have forced any calls to this -- because it deals with network activity -- to happen in a thread or AsyncTask. 但是,Android众神已经强迫对此进行任何调用-因为它处理网络活动-发生在线程或AsyncTask中。 The problem is that any pause to wait for the task to complete causes the Google Drive API threads to pause. 问题在于,等待任务完成的任何暂停都会导致Google Drive API线程暂停。 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. 在名为“ FindFileWithAsyncTask”的AsyncTask中完成对“ findFileByPath”的调用,它只是挂起了所有内容。 The Google Drive API only proceeds when the "get" times out. 仅当“获取”超时时,Google Drive API才会继续运行。

HELP! 救命! There has got to be a way to do this that can avoid -- or mask -- all the asynchronous BS. 必须一种方法可以避免或掩盖所有异步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. 使用网络服务时,很难摆脱AsyncTasks,因为否则您的UI将冻结以等待结果。

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. 然后,您将等待onPostExecute方法上的结果。 And creating the AsyncTask on the fly will reduce the boring code. 动态创建AsyncTask会减少无聊的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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