安卓开发网络相关bug解决方案

两个bug:
1: android.os.NetworkOnMainThreadException
原因:因为main线程要处理UI,默认不能使用网络导致假死
Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。解决方案有两个,一个是使用StrictMode,二是使用线程来操作网络请求。

2: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
原因: 安卓程序的网络访问需要设置权限的

解决方案

  1. // Android 4.0 之后不能在主线程中请求HTTP请求(HttpRequest 方法类要自己定义)
new Thread(new Runnable(){
            @Override
            public void run() {
            //发送GET请求
                String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestGetString", "key=123&v=456");
                System.out.println(s);
                //发送 POST 请求
                String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
                System.out.println(sr);
            }
        }).start();

2:在AndroidManifest.xml中添加如下行,允许网络访问权限就可以了。

<uses-permission android:name="android.permission.INTERNET" />

参考文献:
https://blog.csdn.net/llixiangjian/article/details/72910557
https://blog.csdn.net/hack8/article/details/28038541

猜你喜欢

转载自blog.csdn.net/qq_39412935/article/details/84429019