异常信息:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.synology.synologycloud/com.synology.synologycloud.MainActivity}: android.os.NetworkOnMainThreadException
第一次看到这异常,字面意思是说:在主线程中的网络异常。然后我就去了解了下这个异常,先看看官方的说明
public classNetworkOnMainThreadException
extends RuntimeExceptionjava.lang.Object | ||||
? | java.lang.Throwable | |||
? | java.lang.Exception | |||
? | java.lang.RuntimeException | |||
? | android.os.NetworkOnMainThreadException |
Class Overview
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it‘s heavily discouraged. See the document Designing for Responsiveness.
Also see StrictMode
.
所以get请求不能在主UI线程中发起,我的解决办法是另外开一个线程,方法如下:
//android中不能再主线程中访问网络资源
new Thread(new Runnable(){
@Override
public void run() {
try {
getOauthToken();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();