Android使用okhttp加載圖片

效果圖以下:
在這裏插入圖片描述
前提:在添加了網絡權限及導入了okhttp,okio兩個jar包後開始操做,老規矩,在最後有源碼。
1.定義一個handler爲全局變量,並將其實例化。
在這裏插入圖片描述
2.實例化一個0khttp,傳入網址,實例化一個call的對象{其中有2個方法,在onResponse方法中聲明一個傳遞信息的Message,而後再進行判斷,並將數據傳出去}。
在這裏插入圖片描述
3.回到第一步,將指令和消息放入,並加載圖片。在這裏插入圖片描述
必定要記得加網絡權限java

<uses-permission android:name="android.permission.INTERNET" />**

最後代碼以下:
佈局代碼:就一個圖片控件
android

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
      />

java文件web

public class MainActivity extends Activity {
    private ImageView imageView;
    private Handler handler;
    private String URL="https://www.baidu.com/img/bd_logo1.png";//百度首頁圖片地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case 1://成功
                        byte[]result= (byte[]) msg.obj;
                        Bitmap bitmap=BitmapFactory.decodeByteArray(result,0,result.length);//利用BitmapFactory將數據轉換成bitmap類型
                        imageView.setImageBitmap(bitmap);//加載圖片
                }
                return false;
            }
        });
        OkHttpClient client=new OkHttpClient();//實例化
        final Request request = new Request.Builder().url(URL).build(); //傳入圖片網址,,URL爲本身定義好的網址。
        client.newCall(request).enqueue(new Callback() {//實例化一個call的對象
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
             Message message=handler.obtainMessage();//聲明一個傳遞信息的Message
             if (response.isSuccessful()){//成功
                 Log.e("YF", "onResponse: "+"YES" );//一個log,能夠不寫
                 message.what=1;  //設置成功的指令爲1
                 message.obj=response.body().bytes();//帶入圖片的數據
                 handler.sendMessage(message);//將指令和數據傳出去
             }else{//失敗
                 Log.e("YF", "onResponse: "+"NO" );//一個log,能夠不寫
                 handler.sendEmptyMessage(0);//設置其餘指令爲零,而後進入handler
             }
            }
        });

    }


    private void initView() {
        imageView = (ImageView) findViewById(R.id.imageView);
    }
}

本文同步分享在 博客「計蒙不吃魚」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。網絡

相關文章
相關標籤/搜索