本文介紹了Glide實(shí)現(xiàn)超簡(jiǎn)單的圖片下載功能,具體步驟如下:
添加依賴
compile 'com.github.bumptech.glide:glide:3.7.0'
添加權(quán)限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
工具類代碼
public class SDFileHelper { private Context context; public SDFileHelper() { } public SDFileHelper(Context context) { super(); this.context = context; } //Glide保存圖片 public void savePicture(final String fileName, String url){ Glide.with(context).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() { @Override public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) { try { savaFileToSD(fileName,bytes); } catch (Exception e) { e.printStackTrace(); } } }); } //往SD卡寫入文件的方法 public void savaFileToSD(String filename, byte[] bytes) throws Exception { //如果手機(jī)已插入sd卡,且app具有讀寫sd卡的權(quán)限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String filePath = Environment.getExternalStorageDirectory().getCanonicalPath()+"/budejie"; File dir1 = new File(filePath); if (!dir1.exists()){ dir1.mkdirs(); } filename = filePath+ "/" + filename; //這里就不要用openFileOutput了,那個(gè)是往手機(jī)內(nèi)存中寫數(shù)據(jù)的 FileOutputStream output = new FileOutputStream(filename); output.write(bytes); //將bytes寫入到輸出流中 output.close(); //關(guān)閉輸出流 Toast.makeText(context, "圖片已成功保存到"+filePath, Toast.LENGTH_SHORT).show(); } else Toast.makeText(context, "SD卡不存在或者不可讀寫", Toast.LENGTH_SHORT).show(); }}然后再需要的地方調(diào)用
SDFileHelper helper = new SDFileHelper(MainActivity.this); helper.savePicture("bg.jpg",url);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選