2017-11-25 80 views
0

我能从主要活动类传递一个字符串(一个句子)到Google的NLP API(在名为NLPService.java的单独类中配置),但是我希望能够从NLPService类返回结果(一个特定的实体字符串)返回到我的主要活动进行进一步处理。我可以将实体字符串传回我的主要活动吗?在Android Studio中,我创建了一个NLPService.java用下面的代码:使用Google NLP API将实体字符串传递给主要活动(Android)

//New NLP Model 
public void analyzeText(String textToAnalyze) { 

    Document doc = new Document(); 
     doc.setContent(textToAnalyze) 
      .setType("PLAIN_TEXT"); 

    final String[] result = new String[1]; 
    if (textToAnalyze != null && !doc.isEmpty()) { 
     doc.setContent(textToAnalyze); 
     //Config request to be sent to Google NLP 
     Features features = new Features(); 
     features.setExtractEntities(true); 

     final AnnotateTextRequest request = new AnnotateTextRequest(); 
     request.setDocument(doc); 
     request.setFeatures(features); 

     AsyncTask.execute(new Runnable() { 
      public void run() { 
       try { 
        returnResponse(NLPService.documents().annotateText(request).execute()); 
        result[0] = returnResponse(NLPService.documents().annotateText(request).execute()); 
        Log.i("getAsyncResponse", "RESULT: " + result[0]); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

} 


public String returnResponse(AnnotateTextResponse response) { 
    final List<Entity> entityList = response.getEntities(); 

    String entities = ""; 
    for (Entity entity : entityList) { 
     entities += "\n" + entity.getName().toUpperCase() + " " + entity.getType(); 

    } 
    return entities; 

} 

`

回答

0

的常见的方法将使用广播(LocalBroadcastManager)来传递您打算从服务发送到任何数据活动。 Example of Previous post 或者您可以使用不太可能的SharedPreferences。

相关问题