imageView.setOnLongClickListener(new LongClickHandler());
class LongClickHandler implements View.OnLongClickListener{
@Override
public boolean onLongClick(View view) {
LogHelper.ShowLog("LongClickHandler");
boolean bRet = PublicUtil.SaveJpg((ImageView) view);
if(bRet){
Toast.makeText(getContext(), "图片保存成功", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getContext(), "图片保存失败", Toast.LENGTH_SHORT).show();
}
return true;
}
}
public static boolean SaveJpg(ImageView view) {
try{
Drawable drawable = view.getDrawable();
if (drawable == null) {
return false;
}
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri dataUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri fileUri = view.getContext().getContentResolver().insert(dataUri, values);
// 如果保存不成功,insert没有任何错误信息,此时调用update会有错误信息提示
// view.getContext().getContentResolver().update(dataUri, values, "", null);
if(fileUri == null){
LogHelper.ShowLog("fileUri == null");
return false;
}
OutputStream outStream = view.getContext().getContentResolver().openOutputStream(fileUri);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
// 刷新相册
/*
String[] files = new String[1];
String[] mimeTypes = new String[1];
files[0] = filePath;
mimeTypes[0] = "image/jpeg";
MediaScannerConnection.scanFile(view.getContext(), files, mimeTypes, null);
*/
view.getContext().sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", fileUri));
LogHelper.ShowLog("保存图片到相册完毕...");
return true;
}
catch (IOException ex) {
LogHelper.ShowException(ex);
}
return false;
}