gpt4 book ai didi

java - 跳过了 104 帧!应用程序可能在其主线程上做了太多工作

转载 作者:行者123 更新时间:2023-12-02 02:59:53 25 4
gpt4 key购买 nike

我在 StackOverflow 上检查了答案,但没有找到太多。所以,我这样做是为了练习,就像使用 JSON 的 Hello World 一样,我从 openweather API 获取 JSON 响应。我在 EditText 中写入城市名称,然后按按钮进行搜索并在日志中显示 JSON 字符串。

public class MainActivity extends AppCompatActivity {
EditText city;
public void getData(View view){
String result;
String cityName = city.getText().toString();
getWeather weather = new getWeather();
try {
result = weather.execute(cityName).get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

public class getWeather extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection connection = null;
String result = "";

try {
String finalString = urls[0];
finalString = finalString.replace(" ", "%20");
String fullString = "http://api.openweathermap.org/data/2.5/forecast?q=" + finalString + "&appid=a18dc34257af3b9ce5b2347bb187f0fd";
url = new URL(fullString);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;

}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
city = (EditText) findViewById(R.id.editText);
}
}

我该怎么做才能不收到该消息?

最佳答案

weather.execute(cityName).get()

当您执行 get() 时,您正在等待 AsyncTask 完成。因此,您正在 Ui 线程上运行所有繁重的操作。

来自documentation of get() :

Waits if necessary for the computation to complete, and then retrieves its result.

删除 get()

关于java - 跳过了 104 帧!应用程序可能在其主线程上做了太多工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42513906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com