gpt4 book ai didi

java - Android 异步任务已弃用。需要替代示例

转载 作者:行者123 更新时间:2023-12-01 16:14:37 26 4
gpt4 key购买 nike

我是 Android Java 新手,我真的很感激,因为我可以获得一些引用和/或示例,以便在不使用 AsyncTask 的情况下进行一些简单的网络调用。

我正在编写一个程序来从 URL 解析一个简单的 JSON 对象。

在 Android 11 (API 30) 中,所有 AsyncTask 都将被弃用,如下所示:

https://developer.android.com/reference/android/os/AsyncTask

最佳答案

这是如何使用线程在没有 AsyncTask 的情况下发送请求的示例

  void send_request(final String url) {
try {
Thread thread = new Thread() {
public void run() {
Looper.prepare();
final JSONObject[] maindata = {new JSONObject()};

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
String data = "";
String error_data = "";

HttpURLConnection httpURLConnection = null;
try {

httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");






int status = httpURLConnection.getResponseCode();
Log.d("GET RX", " status=> " + status);

try {
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);

int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
Log.d("GET RX =>", " " + data);

sdbw sd = new sdbw(act);
maindata[0] = new JSONObject(data);



} catch (Exception exx) {
InputStream error = httpURLConnection.getErrorStream();
InputStreamReader inputStreamReader2 = new InputStreamReader(error);

int inputStreamData2 = inputStreamReader2.read();
while (inputStreamData2 != -1) {
char current = (char) inputStreamData2;
inputStreamData2 = inputStreamReader2.read();
error_data += current;
}
Log.e("TX", "error => " + error_data);

}


} catch (Exception e) {
Log.e("TX", " error => " + e.getMessage());
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}

handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, 2000);

Looper.loop();
}
};
thread.start();

} catch (Exception ex) {
Log.e("ERROR =>", "" + ex.getMessage());
ex.printStackTrace();
}

}

关于java - Android 异步任务已弃用。需要替代示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62438770/

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