当前位置: 首页 > 知识库问答 >
问题:

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

湛联
2023-03-14

我查看了StackOverflow的答案,但没找到多少。所以,我这样做是为了练习,就像Hello World使用JSON一样,我从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);
}
}

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

共有1个答案

郭俊拔
2023-03-14

<代码>天气。执行(cityName)。get()

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

从get()的文档中:

如有必要,等待计算完成,然后检索其结果。

删除get()。

 类似资料: