用到的依赖:
加载框:
/**
* Android仿ios的自定义dialog,loading和toast
* 简书:https://www.jianshu.com/p/9259ad7f857b
* GitHub:https://github.com/mamumu/mmDialog
*/
implementation 'com.github.mamumu:mmDialog:1.2.0'
权限申请
/**
* rxPermission
* https://github.com/tbruyelle/RxPermissions
*/
implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
用到的权限:
<!--网络-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 读写文件 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
工具类
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.blankj.utilcode.util.ToastUtils;
import com.mumu.dialog.MMLoading;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;
public class DownloadSaveImg {
private static Context context;
private static String filePath;
private static Bitmap mBitmap;
private static String mSaveMessage = "失败";
private static MMLoading mmLoading;
public static void downloadImg(Context contexts, String filePaths) {
context = contexts;
filePath = filePaths;
MMLoading.Builder builder = new MMLoading.Builder(contexts)
.setMessage("保存中...")
.setCancelable(false)
.setCancelOutside(false);
mmLoading = builder.create();
mmLoading.show();
new Thread(saveFileRunnable).start();
}
private static Runnable saveFileRunnable = new Runnable() {
@Override
public void run() {
try {
if (!TextUtils.isEmpty(filePath)) { //网络图片
// 对资源链接
URL url = new URL(filePath);
//打开输入流
InputStream inputStream = url.openStream();
//对网上资源进行下载转换位图图片
mBitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
}
saveFile(mBitmap);
mSaveMessage = "图片已保存至相册";
} catch (IOException e) {
mSaveMessage = "图片保存失败!";
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
messageHandler.sendMessage(messageHandler.obtainMessage());
}
};
@SuppressLint("HandlerLeak")
private static Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mmLoading.dismiss();
ToastUtils.showShort(mSaveMessage);
}
};
/**
* 保存图片
* @param bm
* @throws IOException
*/
public static void saveFile(Bitmap bm) throws IOException {
File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
if (!dirFile.exists()) {
dirFile.mkdir();
}
String fileName = UUID.randomUUID().toString() + ".png";
String filePath = getExternalStoragePicPath(fileName);
assert filePath != null;
File myCaptureFile = new File(filePath);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
bos.flush();
bos.close();
//把图片保存后声明这个广播事件通知系统相册有新图片到来
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(myCaptureFile);
intent.setData(uri);
context.sendBroadcast(intent);
}
private static String getExternalStoragePicPath(String imageFileName) {
File storageDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES) + File.separator + "hyx");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
return imageFile.getAbsolutePath();
}
return null;
}
}
使用案例
@OnClick(R.id.btn_save_img)
void saveImgOnClick() {
saveImage(icon);
}
private void saveImage(String src) {
final RxPermissions rxPermissions = new RxPermissions(mActivity);
Disposable disposable = rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.subscribe(granted -> {
if (granted) {
DownloadSaveImg.downloadImg(mActivity, src);
} else {
// Oups permission denied
ToastUtils.showShort("存储权限被拒绝,无法保存");
}
});
}