NetworkOnMainThreadException

NetworkOnMainThreadException

This question already has answers here:
How to fix 'android.os.NetworkOnMainThreadException'?

(58个答案)


9个月前关闭。





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

该应用程序具有一个按钮,当按下该按钮时将执行URL。

爪哇

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");

}


N.B. :我没有运行代码,因此,它可能/可能不需要做一些修改

10-07 19:19