应该在后台下载 JSON



用户按下按钮后,它会启动天气功能。但它不会记录任何 JSON 数据或任何错误。应该在后台完成吗?我已经使用 gson 库下载了 JSON。

编辑

:我编辑了我的代码,但用户必须输入粘贴到链接中的城市。那么点击按钮时是否可以在后台进程中运行?

public class MainActivity extends AppCompatActivity {
public class Download extends AsyncTask<String,Void,String>{

    @Override
    protected String doInBackground(String... strings) {
        try {
            URL url = new URL("api.openweathermap.org/data/2.5/weather?q="+strings[0]+"&APPID=****");
            URLConnection request = url.openConnection();
            request.connect();
            JsonParser jp=new JsonParser();
            JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
            JsonObject rootobj = root.getAsJsonObject();
            String weather = rootobj.getAsString();
            Log.i("weather:",weather);
        }
        catch (Exception e){
            e.printStackTrace();;
        }
        return null;
    }
}

public void weather(View view){
    TextView textView=(TextView) findViewById(R.id.editText);
    String city=textView.getText().toString();
    Download download=new Download();
    download.execute(city);

}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}

所有io操作都应该在后台执行,因为所有这些操作都很耗时。 这意味着如果您不在后台执行这些代码,您将阻塞您的主线程,并可能导致 Android 不响应异常。 UI线程中的IO操作通常会导致用户体验不佳。所以我强烈建议你在后台这样做。

您绝对应该在后台加载数据。主线程,即 UI 线程是呈现 UI 组件的线程,因此不应在那里进行繁重的操作。如果在 UI 线程中执行大量操作,它将冻结 UI。

您应该查看 AsyncTask 类以在后台执行加载。

这里有一些很好的教程:

  • https://alvinalexander.com/android/asynctask-examples-parameters-callbacks-executing-canceling
  • https://www.journaldev.com/9708/android-asynctask-example-tutorial
  • https://www.tutorialspoint.com/android-asynctask-example-and-explanation

最新更新