需求:
壁紙是url鏈接,get就能請求到,所以就用get請求到圖片,把圖片轉(zhuǎn)化為bitmap,然后設(shè)置壁紙。
代碼:
這里我封裝了工具類
package xxxxx.utils; import android.app.Activity;import android.app.WallpaperManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL; /** * 設(shè)置壁紙 * 1、下載網(wǎng)絡(luò)圖片,使用HttpURLConnection * 2、設(shè)置壁紙 * Created by zst on 2018/10/15. */ public class HttpURLConnectionUtil { /** * 設(shè)置系統(tǒng)壁紙 * 1、把網(wǎng)絡(luò)圖片設(shè)置系統(tǒng)壁紙 * 2、因?yàn)楣雀璨痪S護(hù)其他框架了,所以使用HttpURLConnection來下載和配置 * * @param activity * @param imgUrl */ public static void setWallpaper(final Activity activity, final String imgUrl) { //Log.e("壁紙", "鏈接:" + imgUrl); new Thread(new Runnable() { @Override public void run() { try { URL httpUrl = new URL(imgUrl);//獲取傳入進(jìn)來的url地址 并捕獲解析過程產(chǎn)生的異常 //使用是Http訪問 所以用HttpURLConnection 同理如果使用的是https 則用HttpsURLConnection try { HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();//通過httpUrl開啟一個(gè)HttpURLConnection對(duì)象 conn.setReadTimeout(5000);//設(shè)置顯示超市時(shí)間為5秒 conn.setRequestMethod("GET");//設(shè)置訪問方式 conn.setDoInput(true);//設(shè)置可以獲取輸入流 InputStream in = conn.getInputStream();//獲取輸入流 //創(chuàng)建一個(gè)寫入ID卡的文件對(duì)象 FileOutputStream out = null; File download = null; String filename = String.valueOf(System.currentTimeMillis());//獲取系統(tǒng)時(shí)間 //判斷文件是否存在 Environment.MEDIA_MOUNTEDID卡是否掛載 如果是則創(chuàng)建文件對(duì)象 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File parent = Environment.getExternalStorageDirectory();//獲取ID卡目錄 download = new File(parent, filename);//在父類的目錄下創(chuàng)建一個(gè)以當(dāng)前下載的系統(tǒng)時(shí)間為文件名的文件 out = new FileOutputStream(download); } byte[] b = new byte[2 * 1024]; int len; if (out != null) {//id卡如果存在 則寫入 while ((len = in.read(b)) != -1) { out.write(b, 0, len); } } //讀取該文件中的內(nèi)容 final Bitmap bitmap = BitmapFactory.decodeFile(download.getAbsolutePath()); activity.runOnUiThread(new Runnable() { @Override public void run() { //設(shè)置圖片為壁紙 //Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.bg_user_top);//設(shè)置項(xiàng)目res中的圖片 WallpaperManager manager = WallpaperManager.getInstance(activity); try { manager.setBitmap(bitmap); UiUtil.showToastLong(activity, "壁紙?jiān)O(shè)置成功,請?jiān)谧烂嫔喜榭?); } catch (IOException e) { UiUtil.showToast(activity, "壁紙?jiān)O(shè)置成失敗"); e.printStackTrace(); } } }); } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } } }).start(); } }以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選