安卓线程问题
我做了一个通过webservice获得图片地址 并异步展示在ListView 中
遇到 android.os.NetworkOnMainThreadException
这是其解决方案,但是我的程序是在android2.2上设计的没有StrictMode类,如果用的一种方法,异步加载图片又会有 工作线程无法更新UI的问题
有几个方案1、把程序改为android2.3,用第一种方法解决
2、在安卓2.2中添加StrictMode类
3、理清主次线程问题
请问大侠哪个方案好点,应该如何操作 ,有没有其他更好的办法
在android 2.3上设计的下载程序,在android 4.0上运行时报android.os.NetworkOnMainThreadException异常,原来在4.0中,访问网络不能在主程序中进行,有两个方法可以解决,一个是在主程序中增加:
Java代码
// 详见StrictMode文档
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
// 详见StrictMode文档
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
另一种是启动线程执行下载任务:
public void onCreate(Bundle savedInstanceState) {
Java代码
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 启动线程执行下载任务
new Thread(downloadRun).start();
}
/**
* 下载线程
*/
Runnable downloadRun = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
updateListView();
}
};
Android 多线程 Java 网络
[解决办法]
android 4.0,网络请求必须在子线程里做
为何不使用handler???当图片加载完成,给主线程发消息,通知它更新界面。
当然用广播也是一样可以的
[解决办法]
new Thread(){
run(){
//把操作移到这里面来
}
}.start();
这个是最简单的写法,但是会有一些麻烦,也可以尝试用异步任务,百度去吧,很容易的
[解决办法]
AsyncTask是轻量级异步,用handler才是理所当然的做法,做项目的时候会经常用到handler,做两次就很简单了
------解决方案--------------------
http://download.csdn.net/detail/h121baby/5170326
