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支持包

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>

执行结果:

原文地址:https://www.cnblogs.com/android-deli/p/10251131.html

时间: 2024-08-08 12:08:59

Android-okhttp下载网络图片并设置壁纸的相关文章

android下载网络图片,设置宽高,等比缩放

使用Picasso组件去下载图片会发现图片宽高会变形不受等比缩放控制,即使设置了图片的 scaleType,可能是对Picasso的api没有用对, Picasso.with(this.activity) .load(AppModel.GetInstance().userAvatarPath) .noFade() .fit() .into(avatar) 使用Glide库会更加方便,很好控制下载好的图片宽高等比缩放 1,布局如下: <ImageView android:id="@+id/q

Android异步下载网络图片

最近新做的一个项目,里面需要下载网络上的图片,并显示在UI界面上,学Android有个常识,就是Android中在主线程中没法直接更新UI的,要想更新UI必须另外开启一个线程来实现,当开启的线程完成图片下载的任务后,来去通知主线程去更新UI,当然这就涉及到Handler这个机制,嗯,背景大致就是这样.来简单的理一下思路: 1.主线程中启动一个异步线程AsyncTask来下载图片,一般耗时操作或与网络交互的都要在异步线程中执行. 2.图片下载完成后,来去通知主线程去更新UI. 3.主线程收到消息后

IIS 添加mime 支持 apk,exe,.woff,IIS MIME设置 ,Android apk下载的MIME 设置 苹果ISO .ipa下载mime 设置

站点--右键属性--http头 扩展名  mime类型.apk      application/vnd.android.package-archive.exe      application/octet-stream.woff     application/x-font-woff 字体.ipa      application/iphone-package-archive 其他mime大全(未测试)MIME类型大全application/vnd.lotus-1-2-33gp video/3

Android Launcher 设置壁纸

版本:1.0 日期:2014.11.25 2014.11.26 版权:©kince 特别推荐:泡在网上的日子 一.概述 一般Launcher都带有壁纸设置的功能,Android提供了设置壁纸的API,在包android.app下面的类WallpaperInfo和WallpaperManager.动态壁纸所在的包是android.service.wallpaper,要区别开.但是要注意,WallpaperInfo是描述动态壁纸的类,从WallpaperManager类的getWallpaperIn

android下载网络图片并缓存

异步下载网络图片,并提供是否缓存至内存或外部文件的功能 异步加载类AsyncImageLoader public void downloadImage(final String url, final ImageCallback callback); public void downloadImage(final String url, final boolean cache2Memory, final ImageCallback callback); public void setCache2F

Android设置壁纸和创建桌面图标

写了个小Demo,实现了设置壁纸和创建桌面图标的逻辑: 创建壁纸比较简单,将Drawable转为Bitmap,然后直接用setWallpaper就行了: Bitmap bitmap = BitmapFactory.decodeResource(Main.this.getResources(), R.drawable.wallpaper); try { Main.this.setWallpaper(bitmap); } catch (IOException e) { e.printStackTra

Android学习笔记进阶21之设置壁纸

别忘记在ApplicationManifest.xml 中加上权限的设置. <uses-permission Android:name = "android.permission.SET_WALLPAPER"/> 壁纸设置方法有三种: 第一 通过WallpaperManager方法中的 setBitmap() 第二 通过WallpaperManager方法中的 setResource() 第三 通过ContextWrapper 类中提供的setWallpaper()方法 由

Android实战简易教程-第七十一枪(异步网络下载网络图片及图片廊制作)

首先来实现异步下载网络图片,布局文件如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_pare

Android设置壁纸的几种方案

Android设置壁纸有许多方法,主要思路有两种: 1:通过WallpaperManager设置 2:通过系统程序设置 下文将分开说明: <1>通过WallpaperManager设置 该方法可以直接将图片置为壁纸,对于所有平台的Android系统都使用,但无法裁剪/调整图片. try { WallpaperManager wpm = (WallpaperManager) getActivity().getSystemService( Context.WALLPAPER_SERVICE); i