2014-01-07 157 views
-1

我重構我的線程,以避免內存泄漏,我得到了有關處理程序和startActivityForResult 2個誤差從線程中被調用(處理Google雲端硬盤)Android的 - 不能讓一個靜態引用非靜態方法

我有我的DownloadActivity:

公共類DownloadActivity延伸活動{ .... 私人無效getFolderId(){ getFolderIdThread =新getFolderIdThread(); getFolderIdThread.start(); }

private static class GetFolderIdThread extends Thread { 
    private Boolean mRunning = false; 

    @Override 
    public void run() { 
     mRunning = true; 

        fResultList = new ArrayList<File>(); 
      Files f1 = mService.files(); 
      Files.List request = null; 
      aFolderId = null; 
      do { 
       try { 
        request = f1.list(); 
        String aQuery = "'root' in parents and mimeType='application/vnd.google-apps.folder' and title='"+ aFolderName + "'"; 
        request.setQ(aQuery);      
        FileList fileList = request.execute(); 
        fResultList.addAll(fileList.getItems()); 
        request.setPageToken(fileList.getNextPageToken()); 
       } catch (UserRecoverableAuthIOException e) { 
        startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION); <= THIS RAISES THE ERROR 
       } catch (IOException e) { 
        e.printStackTrace(); 
        if (request != null){ 
         request.setPageToken(null); 
        } 
       } 
      } while (request.getPageToken() !=null && request.getPageToken().length() > 0); 

      if (fResultList.size() == 0) { 
       Log.d(TAG, "cannot find the training folder at root level"); 
       Message msg = handler.obtainMessage(); <= THIS RAISES THE ERROR 
        Bundle bundle = new Bundle(); 
        bundle.putInt("msgKey", DownloadActivity.NO_TRAININGS_FOLDER); 
          msg.setData(bundle); 
          handler.sendMessage(msg); <= THIS RAISES THE ERROR 
      } else { 
       File folder = fResultList.get(0); 
       aFolderId = folder.getId(); 
       getFolderContents(); <= THIS RAISES THE ERROR 
     } 
    } 
    public void close() { 
     mRunning = false; 
    } 
} 

我已經在我的活動

Handler handler = new Handler() { 
     @Override 
    public void handleMessage(Message msg) { 
     ... 
     } 
    } 

和onActivityResult定義的處理程序

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { 
    switch (requestCode) { 
     case REQUEST_ACCOUNT_PICKER: 
        .... 
        break; 
      } 
    } 

我有哪些選擇繞過這個錯誤?

回答

1

GetFolderIdThread類是靜態的,並且靜態嵌套類不能在創建它的外部類的實例中引用非靜態方法和字段。這樣的嵌套類只能訪問Activity中的靜態方法和字段。從類定義中刪除靜態,我認爲你的問題將解決。

您還需要將您的調用發佈到UI線程上的startActivityForResult。當然,你應該能夠使用您的處理程序是,是這樣的:

handler.post(new Runnable() 
{ 
    public void run() 
    { 
     startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION); 
    } 
}); 

確保當你這樣做,因爲這將繼續運行你的線程可以正常完成爲好。

+0

我試圖寫我的線程爲靜態,以避免任何顯式引用封閉類,所以活動實例不會泄漏時,配置更改...我在我的onDestroy()方法中添加一個thread.close() (Activity class)...我需要再讀一些關於Runnable類的文檔...以更好地理解如何泄漏 – erwin

+0

找到了一個非常好的帖子,如何安全地處理我的線程和避免memoty泄漏.. http: //www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html – erwin

相關問題