全局变量
private static final int SAVE_SUCCESS = 0;//保存图片成功
private static final int SAVE_FAILURE = 1;//保存图片失败
private static final int SAVE_BEGIN = 2;//开始保存图片
点击事件
子线程保存图片
new Thread(new Runnable() {
@Override
public void run() {
mHandler.obtainMessage(SAVE_BEGIN).sendToTarget();
Bitmap bitmap = returnBitMap(url);
saveImageToPhotos(context,bitmap);
}
}).start();
handler
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what) {
case SAVE_BEGIN:
AllUtils.MyToast(context,"开始保存图片...");
break;
case SAVE_SUCCESS:
AllUtils.MyToast(context,"图片保存成功,请到相册查找");
break;
case SAVE_FAILURE:
AllUtils.MyToast(context,"图片保存失败,请稍后再试...");
break;
}
return true;
}
});
保存图片的方法
private void saveImageToPhotos(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
return;
}
// 最后通知图库更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
}
返回bitmap的方法
public final static Bitmap returnBitMap(String url) {
URL myFileUrl;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
HttpURLConnection conn;
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}