繁体   English   中英

android.os.NetworkOnMainThreadException 不知道怎么解决

[英]android.os.NetworkOnMainThreadException no idea how to solve

我在网上查了我的错误,人们告诉我在另一个线程或 asyncTask 上运行网络内容,但我不知道如何解决这个问题......所以一切正常,应用程序启动但随后崩溃并告诉我“android.os.NetworkOnMainThreadException ”

这是我的代码:

public class Activity2 extends AppCompatActivity {
    private static final String TAG = Activity2.class.getSimpleName();
    private TextView fileContent;
    String endstring = "";

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
        fileContent = (TextView) findViewById(R.id.content_from_server);
        try {
            loadstuff();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private void loadstuff() throws IOException {


        URL url = new URL("http://ipaddress/login.php"); // URL to your application
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("username", "test"); // All parameters, also easy
        params.put("password", "test");

        StringBuilder postData = new StringBuilder();
        // POST as urlencoded is basically key-value pairs, as with GET
        // This creates key=value&key=value&... pairs
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        // Convert string to byte array, as it should be sent
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        // Connect, easy
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        // Tell server that this is POST and in which format is the data
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        // This gets the output from your server
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)

            endstring = endstring + (char)c;
            fileContent.setText(endstring);


    }
}

这个异常发生在API 11或者Android 3.0版本,比如实名,在主进程中讨论链消息的进程(因此得名MainThread),在以前的历史中这个操作是允许的,虽然不推荐,取决于进程需要的时间,ANR(应用无响应)。

理想的方案之所以这么叫,是因为它是android社区规定的形式,要实现这个方案我们必须继承AsyncTask类,这个类允许在后台执行操作

您也可以使用一些库,如改造、协程等。

如果您解决了这个问题,请告诉我:)

嗨,像 Henrique 说你需要使用 AsyncTask,它是你班级中的一个类,就像这样

public class NameOfTask extends AsyncTask<Void, Void, Boolean>{

    @Override
    protected Boolean doInBackground(Void... voids) {
        /*your code goes here*/
        return true;
    }
    @Override
    protected void onPostExecute(final Boolean success) {
       /*If you need to do something after the task*/
    }

    @Override
    protected void onCancelled() {
        //if cancel you may need to do something in here
    }
}

调用你只需要调用你创建的类。 像这样:

 NameOfTask task = new NameOfTask();
 task.execute((Void)null);
public class Activity2 extends AppCompatActivity {
    private static final String TAG = Activity2.class.getSimpleName();
    private TextView fileContent;
    String endstring = "";

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

        fileContent = (TextView) findViewById(R.id.content_from_server);

        new AsyncLoadStuff().execute()


    }

    private void loadstuff() throws IOException {


        URL url = new URL("http://ipaddress/login.php"); // URL to your application
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("username", "test"); // All parameters, also easy
        params.put("password", "test");

        StringBuilder postData = new StringBuilder();
        // POST as urlencoded is basically key-value pairs, as with GET
        // This creates key=value&key=value&... pairs
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        // Convert string to byte array, as it should be sent
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        // Connect, easy
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        // Tell server that this is POST and in which format is the data
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        // This gets the output from your server
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)

            endstring = endstring + (char)c;
            fileContent.setText(endstring);


    }
}


You can do something like this ...

//Its may be a inner class
// LoadStuff inside this class, it will be executed on separated class 
 private class AsyncLoadStuff extends AsyncTask<String, String, String> {


        @Override
        protected String doInBackground(String... params) {
             try {
                loadstuff();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(String result) {
            //put load wait
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM