Android-okhttp下载网络图片并设置壁纸

在AndroidManifest.xml配置网络访问权限:

  <!-- 访问网络是危险的行为 所以需要权限 -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- 设置壁纸是危险的行为 所以需要权限 -->
    <uses-permission android:name="android.permission.SET_WALLPAPER" />

 

在 app/build.gradle 加入 

implementation ‘com.squareup.okhttp3:okhttp:3.10.0‘

  然后点击 sync now 下载okhttp支持包

Android-okhttp下载网络图片并设置壁纸

 

 

MainActivity

package liudeli.async.okhttp2;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

import liudeli.async.R;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity {

    private final static String TAG = MainActivity.class.getSimpleName();

    // 图片地址
    private final String PATH = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000" +
            "&sec=1544714792699&di=3c2de372608ed6323f583f1c1b445e51&imgtype=0&src=http%3A%2F%2Fp" +
            "2.qhimgs4.com%2Ft0105d27180a686e91f.jpg";

    private ImageView imageView;
    private Button bt_set_wallpaper;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main4);

        imageView = findViewById(R.id.iv_image);
        bt_set_wallpaper = findViewById(R.id.bt_set_wallpaper);

        Button bt_get_image = findViewById(R.id.bt_get_image);
        bt_get_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出进度条
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Download ...");
                progressDialog.show();

                /**
                 * 第一种方式下载图片 普通
                 */
                /*new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        downloadImage1();
                    }
                }.start();*/

                /**
                 * 第二种方式下载图片 异步
                 */
                downloadImage2();
            }
        });

        bt_set_wallpaper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != bitmap) {
                    try {
                        setWallpaper(bitmap);
                        Toast.makeText(MainActivity.this, "壁纸设置成功", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "壁纸设置失败", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    private Bitmap bitmap;

    /**
     * 第一种方式
     * 使用okhttp 普通下载图片
     */
    private void downloadImage1() {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(PATH)
                .build();
        try {
            Response response = client.newCall(request).execute();
            InputStream inputStream = response.body().byteStream();

            if (200 == response.code()) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                showUI(bitmap);
            } else {
                showUI(null);
            }

        } catch (IOException e) {
            e.printStackTrace();
            showUI(null);
        }
    }

    /**
     * 第二种方式
     * 使用okhttp 异步下载图片
     */
    private void downloadImage2() {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(PATH)
                .build();
        try {
            Call call = client.newCall(request); // 使用client去请求

            call.enqueue(new Callback() { // 回调方法,>>> 可以获得请求结果信息
                @Override
                public void onFailure(Call call, IOException e) {
                    showUI(null); // 下载失败,更新UI
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream inputStream = response.body().byteStream();

                    if (200 == response.code()) {
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        showUI(bitmap);
                    } else {
                        showUI(null);
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            showUI(null);
        }
    }

    /**
     * 显示UI 此方法是可以在 主线程 子线程 对UI操作显示的哦
     * @param bitmap
     */
    private void showUI(final Bitmap bitmap) {
        this.bitmap = bitmap;
        runOnUiThread(runnable);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (bitmap != null) {

                // 故意放慢两秒,模仿网络差的效果
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 设置从网上下载的图片
                        imageView.setImageBitmap(bitmap);
                        // 设置为可以点击
                        bt_set_wallpaper.setEnabled(true);

                        // 关闭进度条
                        progressDialog.dismiss();

                        Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                    }
                }, 2000);
            } else { //失败
                bt_set_wallpaper.setEnabled(false);
                Toast.makeText(MainActivity.this, "下载失败,请检查原因", Toast.LENGTH_LONG).show();
                // 关闭进度条
                progressDialog.dismiss();
            }
        }
    };
}

 

activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt_get_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取图片"
        android:onClick="getImage"
        android:layout_marginLeft="20dp"
        />

    <Button
        android:id="@+id/bt_set_wallpaper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="设置壁纸"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:enabled="false"
        />

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/bt_get_image" />


</RelativeLayout>

 

执行结果:

Android-okhttp下载网络图片并设置壁纸

 

 

Android-okhttp下载网络图片并设置壁纸

上一篇:推荐一波2018年让人惊喜的手机小众APP


下一篇:InnoDB 的记录结构和页结构