2015-02-05 79 views
0

我在Android设备上使用Google Drive API。使用ASyncTask从Android上的Google Drive API文件中读取

我需要将Google云端硬盘上文件的内容转换为字符串。简单的东西像

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

我正在实施一个“GoogleDrive”对象。我需要做到这一点,没有任何的任务和线程和回调混乱。但是,我做不到。

下面是一个例子:我实现了一个名为“findFileByPath”的方法,该方法返回文件的文件ID,该文件的路径名作为参数给出。然而,Android神已经强制任何对此的调用 - 因为它处理网络活动 - 发生在线程或AsyncTask中。问题是任何等待任务完成的暂停都会导致Google Drive API线程暂停。所以....如果我这样做:

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

其中调用“findFileByPath”在一个名为“FindFileWithAsyncTask”的AsyncTask完成它只是挂起的一切。 Google Drive API仅在“get”超时时才会继续。

帮助!有得到是做到这一点的方式,可以避免 - 或掩盖 - 所有的异步BS。

任何线索?谢谢!

+0

我的答案解决了您的问题吗? – Laerte 2015-02-06 15:54:27

回答

0

使用网络服务时很难摆脱AsyncTasks,否则您的UI将冻结等待结果。

试着这样做:

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(); 

然后你会等待在onPostExecute方法的结果。 即时创建AsyncTask将减少无聊的代码。

相关问题