android.os.NetworkOnMainThreadException


<strong>NetworkOnMainThreadException</strong>: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
 
You should call sendfeedback method on asynctask then only  above  code  will work. As webserver is taking lot of time to response main thread <br>becomes unresponsive. To  avoid  it you should call it on another thread. Hence asynctask is better.


当在主线程中执行网络操作时,NetworkOnMainThreadException会抛出这个异常;

你应该调用“asynctask”的“sendfeedback”方法来执行网络操作;当Web服务器花费很多时间响应主线程而变成迟钝,为了避免这种情况,使用“asynctask”更好

package com.example.lj.imagedemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            imageView = (ImageView) findViewById(R.id.imageView);
/*
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //图片资源
                    String url = "http://s16.sinaimg.cn/orignal/89429f6dhb99b4903ebcf&690";
                    //得到可用的图片
                    Bitmap bitmap = getHttpBitmap(url);
                    if (bitmap == null) {
                        Log.i(TAG, "bitmap is null");
                    }
                    //显示
                    imageView.setImageBitmap(bitmap);
                }
            }).start();
*/
            new DownloadUrlBitmap().execute("http://192.168.118.120:8888/img/dn1.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class DownloadUrlBitmap extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return loadImageFromNetwork(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);
        }
    }


    private Bitmap loadImageFromNetwork(String url) {
        //得到可用的图片
        Bitmap bitmap = simpleNetworkImage(url);
        if (bitmap == null) {
            Log.i(TAG, "bitmap is null");
        }
        return bitmap;
    }


    public Bitmap simpleNetworkImage(String url) {
        Bitmap pngBM = null;
        try {
            URL picUrl = new URL(url);
            pngBM = BitmapFactory.decodeStream(picUrl.openStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pngBM;
    }

    /**
     * 获取网落图片资源
     *
     * @param url
     * @return
     */
    public Bitmap getHttpBitmap(String url) {
        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            //获得连接
            HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
            //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //这句可有可无,没有影响
            //conn.connect();
            //得到数据流
            InputStream is = conn.getInputStream();
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            //关闭数据流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值