关于android主线程不能访问网络异常NetworkOnMainThreadException

获取网络图片:

//图片处理
	ImageGetter imgGetter2 = new Html.ImageGetter() {
		public Drawable getDrawable(String source) {
			Drawable drawable = null;
			URL url;
			try {
				url = new URL(basePath + source.trim());
				drawable = Drawable.createFromStream(url.openStream(), ""); 
			} catch (Exception e) {
				return null;
			}

			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
			return drawable;
		}
	};

然后在handler中给TextView赋值:

String content = data.getString("content");

				//html标签处理    图片处理
				txtContent.setText(Html.fromHtml(content, imgGetter2, null));
				break;

图片一直获取不到:而且网络权限也放开了:


然来还需要加上这个:


①类的上面加个@suppressLint


@SuppressLint("NewApi")
public class InfoActivity extends Activity {


②在onCreate方法中加上StrictMode

@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.info_activity);
		
		StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

关于android主线程不能访问网络异常NetworkOnMainThreadException_第1张图片

你可能感兴趣的:(Android)