如何在Android java插件端等待异步操作(任何I / O)?

问题描述 投票:0回答:1

对于统一游戏,我需要在android-plugin中使用libs来发送websocket请求。我发现我不知道如何使c#代码等待android插件中的异步操作! 我提供了一个概念证明案例(带有简单的http get请求),以简单的方式询问我的问题。这是我没有工作的代码:

package com.example.plug2unity1;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Plug1Class {
  static OkHttpClient client = new OkHttpClient();
  static String doGetRequest(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
  }
  public static String GetPlug2Text() throws IOException {
    String res = "";
    try {
        res = doGetRequest("http://www.google.com");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
  }
}

Unity脚本必须调用插件:

void Start () {
    TextMesh txtm = GetComponent<TextMesh> ();
    var plugin = new AndroidJavaClass("com.example.plug2unity1.Plug1Class");
    txtm.text = plugin.CallStatic<string>("GetPlug1Text");
}

编辑:问题是“不”如何进行http调用,显然从c#我可以做到,我想学习“c#如何等待来自插件的异步操作结果,无论是http调用还是我/ O操作,与javascript中的“promises”相同。 结果: 我的TextMesh不会更改文本,而如果我在插件方面没有任何异步执行POC,则可以正常工作。我怎么能让这个工作?

java c# android unity3d asynchronous
1个回答
1
投票

使用回调来执行此操作。从C#调用Java代理。在Java函数中,启动新线程以执行该任务。完成该任务后,执行从Java到C#的回调,以通知您任务已完成。

C#示例代码:

void makeRequestOnJava() 
{
    TextMesh txtm = GetComponent<TextMesh> ();
    var plugin = new AndroidJavaClass("com.example.plug2unity1.Plug1Class");
    txtm.text = plugin.CallStatic<string>("GetPlug1Text");
}

//Will be called from C# when the request is done
void OnRequestFinished()
{

}

然后在Java端完成任务后,使用UnityPlayer.UnitySendMessage在C#端调用OnRequestFinished函数。

UnityPlayer.UnitySendMessage("GameObjectName", "OnRequestFinished", null);

您可以看到如何设置和使用UnityPlayer.UnitySendMessage函数here

© www.soinside.com 2019 - 2024. All rights reserved.