保存一整块view的代码
//执行操作
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ViewUtil.createDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_LOADING);
saveView(getViewBitmap(rl_download_code));
}
});
private void saveView(Bitmap drawingCache) {
Observable.create(new SaveObservable(drawingCache))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SaveSubscriber());
}
/**
* 某些机型直接获取会为null,在这里处理一下防止国内某些机型返回null
*/
private Bitmap getViewBitmap(View view) {
if (view == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
处理结果
private class SaveSubscriber extends Subscriber<String> {
@Override
public void onCompleted() {
ViewUtil.dismissDialog();
showLongToast("保存成功");
}
@Override
public void onError(Throwable e) {
ViewUtil.dismissDialog();
showLongToast("保存失败");
Log.i(getClass().getSimpleName(), e.toString());
}
@Override
public void onNext(String s) {
Log.i(getClass().getSimpleName(), s);
}
}
通知相册及保存
private class SaveObservable implements Observable.OnSubscribe<String> {
private Bitmap drawingCache = null;
public SaveObservable(Bitmap drawingCache) {
this.drawingCache = drawingCache;
}
@Override
public void call(Subscriber<? super String> subscriber) {
if (drawingCache == null) {
subscriber.onError(new NullPointerException("View获取为null"));
} else {
FileOutputStream out;
try {
String picturePath = "/mnt/sdcard/DCIM/Camera/";
File file = new File(picturePath);
if (!file.exists()) {
file.mkdir();
}
String pictureName = System.currentTimeMillis() + ".jpg";
File picturefile = new File(file, pictureName);
out = new FileOutputStream(picturefile);
drawingCache.compress(Bitmap.CompressFormat.WEBP, 100, out);
out.flush();
out.close();
try {
MediaStore.Images.Media.insertImage(activity.getContentResolver(),
picturefile.getAbsolutePath(), pictureName, null);
} catch (FileNotFoundException e) {
subscriber.onError(new NullPointerException("View操作异常"));
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(picturefile);
intent.setData(uri);
activity.sendBroadcast(intent);
} else {
activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + picturefile)));
}
subscriber.onNext(picturefile.getPath());
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(new NullPointerException("View操作异常"));
e.printStackTrace();
}
}
}
}