android.os.NetworkOnMainThreadException

來源:互聯網
上載者:User

標籤:

NetworkOnMainThreadException: 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 
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;    }}

 

android.os.NetworkOnMainThreadException

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.