gpt4 book ai didi

java - 修复 NetworkOnMainThreadException

转载 作者:行者123 更新时间:2023-12-01 23:43:30 26 4
gpt4 key购买 nike

我在 Android 应用程序中有一个应该执行 URL 的方法。但我总是得到一个NetworkOnMainThreadException,因为我不允许在主线程上运行它。在网上我找到了很多不同的方法来解决这个问题。不幸的是,我对Java还很陌生,对它了解不多。

该应用程序有一个按钮,按下该按钮即可执行 URL。

Java

package com.softpi.raspbicontroll;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
}

public void doYellow(View view) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://raspberrypi/yellow.php");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
catch (Exception e) {
System.out.println("Shit!");
e.printStackTrace();
} finally {
assert urlConnection != null;
urlConnection.disconnect();
}

}

private static void readStream(InputStream in) {}

}

XML

<Button
...
android:onClick="doYellow"
...
app:layout_constraintTop_toTopOf="parent" />

有人可以帮我找到适合初学者的解决方案吗?

最佳答案

无需在主线程内运行网络调用,只需使用 AsyncTask反而。另外一个更好的解决方案是使用 Retrofit,但对于初学者来说并不是那么简单

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

private String resp;
ProgressDialog progressDialog;

@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://raspberrypi/yellow.php");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
catch (Exception e) {
System.out.println("Shit!");
e.printStackTrace();
} finally {
assert urlConnection != null;
urlConnection.disconnect();
}
return null;
}


@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}


@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}


@Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);

}
}

并且 doYellow 函数如下:

public void doYellow(View view) {
new AsyncTaskRunner().execute("http://stackoverflow.com");

}

注意:我没有运行代码,所以,它可能/可能不需要一些修改

关于java - 修复 NetworkOnMainThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249501/

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