前俩天在写一个android的代码时,在一个方法中使用了网络,然后在调试的时候出现了android.os.NetworkOnMainThreadException的错误,整整2天都不知道什么错误,还以为是自己代码写错了,后来google了一下才发现是android 2.3以后访问网络不能直接在主程序中运行。。。坑啊
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
String strVer=GetVersion.GetSystemVersion();
strVer=strVer.substring(0,3).trim();
float fv=Float.valueOf(strVer);
if(fv>2.3)
{
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O
.penaltyLog() //打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects() //探测SQLite数据库操作
.penaltyLog() //打印logcat
.penaltyDeath()
.build());
}
super.onCreate(savedInstanceState);
}
网上说加这段代码能行,但是我的直接报错,很多红色波浪线。。。。
然后想用异步线程写,但是老是提示我要用final,改了final,又说我The final local variable html cannot be assigned, since it is defined in an enclosing。。。。
啊!!!!真是坑啊,求破啊