Android多线程问题。android.os.NetworkOnMainThreadException

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kkgbn/article/details/50395335

主线程不能进行访问网络等耗时操作

解决的方式

①另起一个Thread来处理

②用Thread和handler搭配处理,Thread执行耗时操作,结果交给handler来处理。

③用AsyncTask进行耗时操作


展开阅读全文

android.os.NetworkOnMainThreadException

05-16

package com.demo.clientdemo;nnimport java.io.IOException;nimport java.io.InputStream;nnimport org.apache.http.HttpResponse;nimport org.apache.http.client.ClientProtocolException;nimport org.apache.http.client.HttpClient;nimport org.apache.http.client.methods.HttpGet;nimport org.apache.http.impl.client.DefaultHttpClient;nnimport android.support.v7.app.ActionBarActivity;nimport android.graphics.Bitmap;nimport android.graphics.BitmapFactory;nimport android.os.Bundle;nimport android.view.Menu;nimport android.view.MenuItem;nimport android.view.View;nimport android.widget.EditText;nimport android.widget.ImageView;nnpublic class MainActivity extends ActionBarActivity n private EditText et;n private ImageView iv;nn @Overriden protected void onCreate(Bundle savedInstanceState) n super.onCreate(savedInstanceState);n setContentView(R.layout.activity_main);n et = (EditText) findViewById(R.id.et);n iv = (ImageView) findViewById(R.id.iv);n nn public void click(View view) nn String path = et.getText().toString().trim();n //n HttpClient client = new DefaultHttpClient();n // n HttpGet httpGet = new HttpGet(path);n try n HttpResponse response = client.execute(httpGet);n int code = response.getStatusLine().getStatusCode();n if (code == 200) n InputStream is = response.getEntity().getContent();n final Bitmap bitmap = BitmapFactory.decodeStream(is);nn runOnUiThread(new Runnable() n @Overriden public void run() n iv.setImageBitmap(bitmap);n n );n n catch (Exception e) n e.printStackTrace();n nn nnnnn界面nnn nn n n nnnn发布后点击浏览要报错,大牛们帮忙看看怎么解决啊 问答

没有更多推荐了,返回首页