android.os.NetworkOnMainThreadException异常处理

独自空忆成欢 提交于 2019-12-15 17:45:18

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

第一种:

public void onCreate(Bundle savedInstanceState) {
        
        // 详见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());
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        InitDialog();
    }



在android 2.3上设计的下载程序,在android 4.0上运行时报android.os.NetworkOnMainThreadException异常,原来在4.0中,访问网络不能在主程序中进行,有两个方法可以解决,一个是在主程序中增加:如上 (我是在使用ftpClient.connect(string, int)时出错)。

另外一种方法是启动线程执行下载任务:

public class LoginActivity extends Activity implements SinaMcroBlog {

	private ImageView imgHead;
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				imgHead.setImageBitmap((Bitmap)msg.obj);
				break;
			default:
				break;
			}
		}
	};
	Runnable downloadRun = new Runnable(){
		@Override        
		public void run() {            
			URL url;
            Bitmap bitmap = null;
            try {
                    url = new URL("http://tp1.sinaimg.cn/2118986604/180/5633348097/1");
                    InputStream is = url.openConnection().getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bitmap = BitmapFactory.decodeStream(bis);
                    bis.close();
            } catch (MalformedURLException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            }
            handler.obtainMessage(1,bitmap).sendToTarget();
          //Bitmap bitmap = getBitmapFromUrl("http://tp1.sinaimg.cn/2118986604/50/5633348097/1");
			//imgHead.setImageBitmap(bitmap);
			//imgHead.invalidate();
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		imgHead=(ImageView) this.findViewById(R.id.img_head);
		try {
			new Thread(downloadRun).start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}




易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!