小功能整理
Posted 我的小侯子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小功能整理相关的知识,希望对你有一定的参考价值。
一.intent相关
卸载apk
//卸载
public void uninstallApk(String packageName)
if (isPackageExist(packageName))
Uri packageURI = Uri.parse("package:" + packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
packageURI);
startActivity(uninstallIntent);
//是否安装
public boolean isPackageExist(String pckName)
try
PackageInfo pckInfo = getPackageManager()
.getPackageInfo(pckName, 0);
if (pckInfo != null)
return true;
catch (PackageManager.NameNotFoundException e)
return false;
跳转到app市场页面
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=包名"));
startActivity(intent);
发送短信
Intent intent=new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"I am a boy");
startActivity(intent);
打开相册
Intent intent=new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivity(intent);
打开浏览器
Intent intent=new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri=Uri.parse("www.baidu.com");
intent.setData(uri);
startActivity(intent);
打电话
//进入拨号页面(不需要CALL_PHONE权限)
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + 10086));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//用intent启动拨打电话,直接拨打(需要CALL_PHONE权限)
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + 10086));
startActivity(intent);
短信发送
//取得短信电话号码 内容
String number = textview.getText().toString();
String message= edittext.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> parts = smsManager.divideMessage(message);//短信超过长度会分成另一条
for(String part : parts)
smsManager.sendTextMessage(number, null, part, null, null);
Uri url = Sms.Sent.CONTENT_URI;
ContentValues values = new ContentValues();
values.put("address", number);
values.put("body", part);
getContentResolver().insert(url, values);
调用系统的短信界面,这个方法需要用户自己输入接收方的电话号码
private void send(String message)
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", message);
sendIntent.setType("vnd.android-dir/mms-sms");
自动设置接收方的号码
private void send1(String number, String message)
Uri uri = Uri.parse("smsto:" + number);
Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
sendIntent.putExtra("sms_body", message);
startActivity(sendIntent);
安装apk
// 新的APK的文件名
String str = "newUpdate.apk";
// 新APK在存储卡上的位置
String fileName = Environment.getExternalStorageDirectory() + str;
// 通过启动一个Intent让系统来帮你安装新的APK
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
startActivity(intent);
打开系统日历
public static void calendar(Context context)
try
Intent i = new Intent();
ComponentName cn = null;
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
cn = new ComponentName("com.android.calendar",
"com.android.calendar.LaunchActivity");
else
cn = new ComponentName("com.google.android.calendar",
"com.android.calendar.LaunchActivity");
i.setComponent(cn);
context.startActivity(i);
catch (ActivityNotFoundException e)
// TODO: handle exception
Logg.e("ActivityNotFoundException", e.toString());
显示应用选择器
Intent cIntent = new Intent(Intent.ACTION_VIEW);
Intent chooser = Intent.createChooser(cIntent, "选择打开方式");
startActivity(chooser);
确认是否存在接收意向的应用
Intent mIntent = new Intent();
ComponentName mComp = new ComponentName("com.hou.zi", "com.hou.zi.activity.login.RegisterActivity");//注意AcitivityName(目标应用程序)要完整的,带包名的PackageName的
mIntent.setComponent(mComp);
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(mIntent,
PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;
showBigToast(activities.size() + "==");
打开其他应用的activity
// android:exported="true"所要调整的activity必须有这个属性
try
Intent mIntent = new Intent();
ComponentName mComp = new ComponentName("com.hou.zi", "com.hou.zi.activity.login.RegisterActivity");//注意AcitivityName(目标应用程序)要完整的,带包名的PackageName的
mIntent.setComponent(mComp);
startActivity(mIntent);
catch (SecurityException e)
showBigToast("没有权限");
catch (ActivityNotFoundException e)
showBigToast("未找到可用应用程序!");
意图过滤
mimeType : 类别
提供另外一种表征处理意向的Activity的方法,通常与用户手势或Activity开始的位置有关。 系统支持多种不同的类别,但大多数都很少使用。 但是,所有隐含意向默认使用 CATEGORY_DEFAULT 进行定义。
用 元素在意向过滤器中指定此内容。
android:mimeType 属性声明您的Activity处理的数据类型,比如 text/plain 或 image/jpeg。
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
二.跟View相关
将布局文件保存成图片文件
/**
* 将布局文件保存成图片文件
*/
public static void saveLayout2File(View view, final SaveFileListener saveFileListener)
handler = new Handler(Looper.getMainLooper());
final Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
view.draw(new Canvas(bmp));
File dir = new File(imagePath);
if (!dir.exists())
dir.mkdirs();
final String photoUrl = imagePath + System.currentTimeMillis() + ".png";//换成自己的图片保存路径
final File file = new File(photoUrl);
new Thread()
@Override
public void run()
try
final boolean bitMapOk = bmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
handler.post(new Runnable()
@Override
public void run()
if (saveFileListener != null)
saveFileListener.onSaveFile(bitMapOk, photoUrl);
);
catch (FileNotFoundException e)
e.printStackTrace();
.start();
三.SD卡相关
SD卡是否存在
/**
* @return SD卡是否存在
*/
public static boolean existSDCard()
return (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED));
SD卡容量信息
/**
* 单位类型
*/
public interface Unit
int BYTE = 0, KBYTE = 1, MBYTE = 2;
/**
* @param unit 单位类型:0:Byte,1:KB,other:MB
* @return SD卡剩余空间
*/
public static long getSDFreeSize(int unit)
//取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
//获取单个数据块的大小(Byte)
long blockSize = sf.getBlockSize();
//空闲的数据块的数量
long freeBlocks = sf.getAvailableBlocks();
//返回SD卡空闲大小
if (unit == 0)
return freeBlocks * blockSize; //单位Byte
else if (unit == 1)
return (freeBlocks * blockSize) / 1024; //单位KB
else
return (freeBlocks * blockSize) / 1024 / 1024; //单位MB
/**
* @return SD卡总容量
*/
public static long getSDAllSize()
//取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
//获取单个数据块的大小(Byte)
long blockSize = sf.getBlockSize();
//获取所有数据块数
long allBlocks = sf.getBlockCount();
//返回SD卡大小
//return allBlocks * blockSize; //单位Byte
//return (allBlocks * blockSize)/1024; //单位KB
return (allBlocks * blockSize) / 1024 / 1024; //单位MB
四.Bitmap相关
图像的放大缩小方法
/**
* 图像的放大缩小方法
*
* @param src 源位图对象
* @param scaleX 宽度比例系数
* @param scaleY 高度比例系数
* @return 返回位图对象
*/
public static Bitmap zoomBitmap(Bitmap src, float scaleX, float scaleY)
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY);
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
图像放大缩小--根据宽度和高度
/**
* 图像放大缩小--根据宽度和高度
*
* @param src
* @param width
* @param height
* @return
*/
public static Bitmap zoomBimtap(Bitmap src, int width, int height)
return Bitmap.createScaledBitmap(src, width, height, true);
Bitmap转byte[]
/**
* Bitmap转byte[]
*
* @param bitmap
* @return
*/
public static byte[] bitmapToByte(Bitmap bitmap)
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
return out.toByteArray();
byte[]转Bitmap
/**
* byte[]转Bitmap
*
* @param data
* @return
*/
public static Bitmap byteToBitmap(byte[] data)
if (data.length != 0)
return BitmapFactory.decodeByteArray(data, 0, data.length);
return null;
绘制带圆角的图像
/**
* 绘制带圆角的图像
*
* @param src
* @param radius
* @return
*/
public static Bitmap createRoundedCornerBitmap(Bitmap src, int radius)
final int w = src.getWidth();
final int h = src.getHeight();
// 高清量32位图
Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Paint paint = new Paint();
Canvas canvas = new Canvas(bitmap);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(0xff424242);
// 防止边缘的锯齿
paint.setFilterBitmap(true);
Rect rect = new Rect(0, 0, w, h);
RectF rectf = new RectF(rect);
// 绘制带圆角的矩形
canvas.drawRoundRect(rectf, radius, radius, paint);
// 取两层绘制交集,显示上层
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// 绘制图像
canvas.drawBitmap(src, rect, rect, paint);
return bitmap;
创建选中带提示图片
/**
* 创建选中带提示图片
*
* @param context
* @param srcId
* @param tipId
* @return
*/
public static Drawable createSelectedTip(Context context, int srcId, int tipId)
Bitmap src = BitmapFactory.decodeResource(context.getResources(), srcId);
Bitmap tip = BitmapFactory.decodeResource(context.getResources(), tipId);
final int w = src.getWidth();
final int h = src.getHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Paint paint = new Paint();
Canvas canvas = new Canvas(bitmap);
//绘制原图
canvas.drawBitmap(src, 0, 0, paint);
//绘制提示图片
canvas.drawBitmap(tip, (w - tip.getWidth()), 0, paint);
return bitmapToDrawable(bitmap);
带倒影的图像
/**
* 带倒影的图像
*
* @param src
* @return
*/
public static Bitmap createReflectionBitmap(Bitmap src)
// 两个图像间的空隙
final int spacing = 4;
final int w = src.getWidth();
final int h = src.getHeight();
// 绘制高质量32位图
Bitmap bitmap = Bitmap.createBitmap(w, h + h / 2 + spacing, Config.ARGB_8888);
// 创建燕X轴的倒影图像
Matrix m = new Matrix();
m.setScale(1, -1);
Bitmap t_bitmap = Bitmap.createBitmap(src, 0, h / 2, w, h / 2, m, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
// 绘制原图像
canvas.drawBitmap(src, 0, 0, paint);
// 绘制倒影图像
canvas.drawBitmap(t_bitmap, 0, h + spacing, paint);
// 线性渲染-沿Y轴高到低渲染
Shader shader = new LinearGradient(0, h + spacing, 0, h + spacing + h / 2, 0x70ffffff, 0x00ffffff, Shader.TileMode.MIRROR);
paint.setShader(shader);
// 取两层绘制交集,显示下层。
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// 绘制渲染倒影的矩形
canvas.drawRect(0, h + spacing, w, h + h / 2 + spacing, paint);
return bitmap;
独立的倒影图像
/**
* 独立的倒影图像
*
* @param src
* @return
*/
public static Bitmap createReflectionBitmapForSingle(Bitmap src)
final int w = src.getWidth();
final int h = src.getHeight();
// 绘制高质量32位图
Bitmap bitmap = Bitmap.createBitmap(w, h / 2, Config.ARGB_8888);
// 创建沿X轴的倒影图像
Matrix m = new Matrix();
m.setScale(1, -1);
Bitmap t_bitmap = Bitmap.createBitmap(src, 0, h / 2, w, h / 2, m, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
// 绘制倒影图像
canvas.drawBitmap(t_bitmap, 0, 0, paint);
// 线性渲染-沿Y轴高到低渲染
Shader shader = new LinearGradient(0, 0, 0, h / 2, 0x70ffffff,
0x00ffffff, Shader.TileMode.MIRROR);
paint.setShader(shader);
// 取两层绘制交集。显示下层。
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// 绘制渲染倒影的矩形
canvas.drawRect(0, 0, w, h / 2, paint);
return bitmap;
灰色图像
/**
*灰色图像
*/
public static Bitmap createGreyBitmap(Bitmap src)
final int w = src.getWidth();
final int h = src.getHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
// 颜色变换的矩阵
ColorMatrix matrix = new ColorMatrix();
// saturation 饱和度值,最小可设为0,此时对应的是灰度图;为1表示饱和度不变,设置大于1,就显示过饱和
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
paint.setColorFilter(filter);
canvas.drawBitmap(src, 0, 0, paint);
return bitmap;
保存图片
/**
* 保存图片
*
* @param src
* @param filepath
* @param format:[Bitmap.CompressFormat.PNG,Bitmap.CompressFormat.JPEG]
* @return
*/
public static boolean saveImage(Bitmap src, String filepath, CompressFormat format)
boolean rs = false;
File file = new File(filepath);
try
FileOutputStream out = new FileOutputStream(file);
if (src.compress(format, 100, out))
out.flush(); //写入流
out.close();
rs = true;
catch (Exception e)
e.printStackTrace();
return rs;
添加水印效果
/**
* 添加水印效果
*
* @param src 源位图
* @param watermark 水印
* @param direction 方向
* @param spacing 间距
* @return
*/
public static Bitmap createWatermark(Bitmap src, Bitmap watermark, int direction, int spacing)
final int w = src.getWidth();
final int h = src.getHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
if (direction == LEFT_TOP)
canvas.drawBitmap(watermark, spacing, spacing, null);
else if (direction == LEFT_BOTTOM)
canvas.drawBitmap(watermark, spacing, h - watermark.getHeight() - spacing, null);
else if (direction == RIGHT_TOP)
canvas.drawBitmap(watermark, w - watermark.getWidth() - spacing, spacing, null);
else if (direction == RIGHT_BOTTOM)
canvas.drawBitmap(watermark, w - watermark.getWidth() - spacing, h - watermark.getHeight() - spacing, null);
return bitmap;
合成图像
/**
* 合成图像
*
* @param direction
* @param bitmaps
* @return
*/
public static Bitmap composeBitmap(int direction, Bitmap... bitmaps)
if (bitmaps.length < 2)
return null;
Bitmap firstBitmap = bitmaps[0];
for (Bitmap bitmap : bitmaps)
firstBitmap = composeBitmap(firstBitmap, bitmap, direction);
return firstBitmap;
/**
* 合成两张图像
*
* @param firstBitmap
* @param secondBitmap
* @param direction
* @return
*/
private static Bitmap composeBitmap(Bitmap firstBitmap, Bitmap secondBitmap,
int direction)
if (firstBitmap == null)
return null;
if (secondBitmap == null)
return firstBitmap;
final int fw = firstBitmap.getWidth();
final int fh = firstBitmap.getHeight();
final int sw = secondBitmap.getWidth();
final int sh = secondBitmap.getHeight();
Bitmap bitmap = null;
Canvas canvas = null;
if (direction == TOP)
bitmap = Bitmap.createBitmap(sw > fw ? sw : fw, fh + sh, Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawBitmap(secondBitmap, 0, 0, null);
canvas.drawBitmap(firstBitmap, 0, sh, null);
else if (direction == BOTTOM)
bitmap = Bitmap.createBitmap(fw > sw ? fw : sw, fh + sh, Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawBitmap(firstBitmap, 0, 0, null);
canvas.drawBitmap(secondBitmap, 0, fh, null);
else if (direction == LEFT)
bitmap = Bitmap.createBitmap(fw + sw, sh > fh ? sh : fh, Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawBitmap(secondBitmap, 0, 0, null);
canvas.drawBitmap(firstBitmap, sw, 0, null);
else if (direction == RIGHT)
bitmap = Bitmap.createBitmap(fw + sw, fh > sh ? fh : sh,
Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawBitmap(firstBitmap, 0, 0, null);
canvas.drawBitmap(secondBitmap, fw, 0, null);
return bitmap;
简单的截图(View获取bitmap,保存文件)
/**
* 简单的截图(View获取bitmap,保存文件)
*
* @param view 需要转成图片的View
* @param filePath 存储路径
* @return 返回生成的bitmap
*/
public static Bitmap screenShot(View view, String filePath)
long start = System.currentTimeMillis();
// 获取屏幕
view.setDrawingCacheEnabled(true);//开启cache
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Logg.i("===========bmp============" + bmp);
if (bmp != null)
try
// 图片文件路径
filePath = TextUtils.isEmpty(filePath) ? FilePath.imagePath + File.separator + System.currentTimeMillis() + "screenshot.png" : filePath;
File fileF = new File(FilePath.imagePath);
if (!fileF.exists())
fileF.mkdirs();
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
catch (Exception e)
long end = System.currentTimeMillis();
Logg.i("===========截图需要的时间============" + (end - start));
return bmp;
五.工具类
复制到剪切板
ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clip.setText(string);
调用文件选择软件来选择文件
/**
* 调用文件选择软件来选择文件
**/
public static void showFileChooser(Activity activity, int requestCode, String name)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(name + "/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try
activity.startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
requestCode);
catch (android.content.ActivityNotFoundException ex)
// Potentially direct the user to the Market with a Dialog
Toast.makeText(activity, "请安装文件管理器", Toast.LENGTH_SHORT)
.show();
/**
* 调用文件选择软件来选择文件
**/
public static void showForderChooser(Activity activity, int requestCode)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("forder/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try
activity.startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
requestCode);
catch (android.content.ActivityNotFoundException ex)
// Potentially direct the user to the Market with a Dialog
Toast.makeText(activity, "请安装文件管理器", Toast.LENGTH_SHORT)
.show();
MD5处理字符串
/**
* MD5处理字符串
*/
public class MD5
public static String md5(String string)
byte[] hash;
try
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
catch (NoSuchAlgorithmException e)
throw new RuntimeException("Huh, MD5 should be supported?", e);
catch (UnsupportedEncodingException e)
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash)
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
return hex.toString();
检查网络是否开启
1.连接网络
/**
* 检查网络是否开启
*/
public static boolean isNetworkAvailable(Context context)
// 获得网络系统连接服务
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null)
return false;
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
return !(networkinfo == null || !networkinfo.isAvailable());
2.网络可用
public static boolean isNetworkConnect(Context context)
if (context == null)
return false;
// 获得网络系统连接服务
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null)
return false;
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
return !(networkinfo == null || !networkinfo.isConnected() || networkinfo.getState() != NetworkInfo.State.CONNECTED);
二维码生成工具类
/**
* 二维码生成工具类
*/
public class QRCodeUtil
private static Handler handler;
/**
* 生成二维码Bitmap
*
* @param content 内容
* @param widthPix 图片宽度
* @param heightPix 图片高度
* @param logoBm 二维码中心的Logo图标(可以为null)
* @param filePath 用于存储二维码图片的文件路径
* @return 生成二维码及保存文件是否成功
*/
public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath)
try
if (content == null || "".equals(content))
return false;
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 1); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++)
for (int x = 0; x < widthPix; x++)
if (bitMatrix.get(x, y))
pixels[y * widthPix + x] = 0xff000000;
else
pixels[y * widthPix + x] = 0xffffffff;
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null)
bitmap = addLogo(bitmap, logoBm);
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
catch (WriterException | IOException e)
e.printStackTrace();
return false;
/**
* 在二维码中间添加Logo图案
*/
private static Bitmap addLogo(Bitmap src, Bitmap logo)
if (src == null)
return null;
if (logo == null)
return src;
//获取图片的宽高
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int logoWidth = logo.getWidth();
int logoHeight = logo.getHeight();
if (srcWidth == 0 || srcHeight == 0)
return null;
if (logoWidth == 0 || logoHeight == 0)
return src;
//logo大小为二维码整体大小的1/7
float scaleFactor = srcWidth * 1.0f / 7 / logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
catch (Exception e)
bitmap = null;
e.getStackTrace();
return bitmap;
public interface QRCodeListener
void onQRCode(boolean isSuccess, Bitmap qrBitmap, String filePath);
private static boolean success = false;
public static void createQRcode(Context context, String filePath, final String text, final Bitmap logoBm, final QRCodeListener qrCodeListener)
handler = new Handler(Looper.getMainLooper());
if (TextUtils.isEmpty(filePath))
filePath = FilePath.imagePath
+ "qr_" + MyApplication.userId + ".jpg";
以上是关于小功能整理的主要内容,如果未能解决你的问题,请参考以下文章