我的目標是在遊戲無法到達後端時更改用戶的屏幕。我的代碼按預期執行,除非屏幕永遠不會改變。這裏的初始呼叫:HTTP請求後在單獨的線程上更改呈現屏幕
timer.testTimeToServer(api, game);
這裏的計時器對象的類。我把(我的網址)代替我的後端的實際IP地址:
public class CustomTimer {
private static final float timeToDrop = 2000;
private float time = 0;
private StopWatch watch = new StopWatch();
public void testTimeToServer(ApiCall api,final proofOfConcept game){
watch.start();
api.httpGetWithCallback("(my url)/api/v1/character", new CallBack(){
@Override
public void callback(String resp){
System.out.println("Server Responded");
time = watch.getTime();
watch.stop();
watch.reset();
if(time > timeToDrop){
game.setScreen(new GameOverScreen(game, false));
System.out.println("Should have switched screen")
}
}
});
}
}
這裏是在API對象的httpGetWithCallback方法:
public void httpGetWithCallback (final String URL, final CallBack callback){
Thread th = new Thread(new Runnable(){
@Override
public void run() {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
httpRequest.setUrl(URL);
httpRequest.setHeader("Content-Type", "application/json");
httpRequest.setTimeOut(timeoutTimeInMilli);
Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String successValue = httpResponse.getResultAsString();
if (successValue.contains("\"total_count\": 0"))//wrong credentials
{
callback.callback("EMPTY");
} else//there was a match yo! should probably have a unique conststraint on username. too hard eff it
{
callback.callback(successValue);
}
}
@Override
public void failed(Throwable t) {
callback.callback("FAILED");
}
@Override
public void cancelled() {
callback.callback("CANCELLED");
}
});
}
}
);
}
});
th.start();
threads.add(th);
}
我很爲難,因爲代碼打印出「應該切換屏幕「,所以它的行爲像預期的那樣,除了遊戲被凍結並且屏幕切換從未實際發生。
OpenGL不能很好地處理多線程。 –
您是否嘗試在更改屏幕的渲染方法內創建驗證? 在java中,當你將變量傳遞給方法時,它們是實例的副本,所以在這個方法中調用game.setScreen 對原始實例不起作用,這不是像C,C++這樣的指針。您需要以靜態方式訪問遊戲對象,或者在渲染方法中驗證它並更改屏幕。哦,你需要調用dispose();更換屏幕之後... – Hllink