小功能整理

一.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";
        }
        final String path = filePath;
        //二维码图片较大时,生成图片、保存文件的时间可能较长,因此放在新线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                success = QRCodeUtil.createQRImage(text, 800, 800, logoBm, path);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (qrCodeListener != null) {
                            qrCodeListener.onQRCode(success, BitmapFactory.decodeFile(path), path);
                        }
                    }
                });
            }
        }).start();
    }

    public static void createQRcode(Context context, String filePath, String text, int logoResId, QRCodeListener qrCodeListener) {
        File file = new File(filePath);
        if (file.exists()) {
            if (qrCodeListener != null) {
                qrCodeListener.onQRCode(true, BitmapFactory.decodeFile(filePath), filePath);
            }
        } else {
            createQRcode(context, filePath, text, BitmapFactory.decodeResource(context.getResources(), logoResId), qrCodeListener);
        }
    }
}
/**
     * dip转换px
     */
    public static int dip2px(Context context, int dip) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * px转换dip
     */
    public static int px2dip(Context context,int px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 从主线程looper里面移除runnable
     */
    public static void removeCallbacks(Runnable runnable) {
        getHandler().removeCallbacks(runnable);
    }

获取状态栏高度

    /**
     * 获取状态栏高度
     */
public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

通知父容器,占用的宽,高;

    /**
     * 通知父容器,占用的宽,高;
     *
     * @param child
     */
    public static void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight,
                    View.MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

取图片上的颜色

private void getBitmapColor() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.background_menu_head);
        //取图片上的颜色
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                Palette.Swatch swatch = palette.getVibrantSwatch(); //充满活力的色板
                if (swatch != null) {
                    int rgb = swatch.getRgb();
                    int titleTextColor = swatch.getTitleTextColor();
                    int bodyTextColor = swatch.getBodyTextColor();
                    //HSL色彩模式
                    // hsl[0] is Hue [0 .. 360)色相
                    //hsl[1] is Saturation [0...1]饱和度
                    //hsl[2] is Lightness [0...1]明度
                    float[] hsl = swatch.getHsl();
                    colorBurn(rgb);
                    colorBurn(titleTextColor);
                    colorBurn(bodyTextColor);
                    Logg.d(hsl[0] + "==" + hsl[1] + "==" + hsl[2]);
                }
            }
        });
    }

    private int colorBurn(int RGBValues) {
        int alpha = RGBValues >> 24;
        int red = RGBValues >> 16 & 0xFF;
        int green = RGBValues >> 8 & 0xFF;
        int blue = RGBValues & 0xFF;
        Logg.d(alpha + "==" + red + "==" + green + "==" + blue);
        return Color.rgb(red, green, blue);
    }

手机的monkey测试

Monkey.jar程序是由一个名为“monkey”的Shell脚本来启动执行,shell脚本在Android文件系统中的存放路径是:/sdk/tools/bin/monkey;

//启动自己的app(一个),-p后指定自己应用包名 后边跟随机事件次数
adb shell monkey -p ai.houzi.xiao  10000
//指定多个包名,表示启动这多个应用
adb shell monkey -p ai.houzi.xiao -p ai.houzi.xiao1 -p ai.houzi.xiao2 10000
//不指定包名,代表可以启动所有应用
adb shell monkey 10000

保持常亮

// 保持背光常亮的设置
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

创建程序的快捷方式

public void createShortCut(){
        try{
            //创建快捷方式的Intent
            Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            //不允许重复创建
            shortcutintent.putExtra("duplicate", false);
            //需要现实的名称
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
            //快捷图片
            Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.icon);
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
            //点击快捷图片,运行的程序主入口
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , LoginActivity.class));
            //发送广播。OK
            sendBroadcast(shortcutintent);
        }catch (Exception e) { 
            closeWindow();
        }

    }
private void createShortCut() {
        // TODO Auto-generated method stub
        //先判断该快捷是否存在
        if(!isExist()){
            Intent intent = new Intent();
            //指定动作名称
            intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
            //指定快捷方式的图标
            Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.congsmall);
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
            //指定快捷方式的名称
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "短信管理器");

            //指定快捷图标激活哪个activity
            Intent i = new Intent();
            i.setAction(Intent.ACTION_MAIN);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName component = new ComponentName(this, MainActivity.class);
            i.setComponent(component);
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i);
            sendBroadcast(intent);
        }
    }

pull解析xml

public class UpdateInfoParser {
    /**
     * 获取服务器上的更新信息
     * @param is 服务器更新信息的返回的流
     * @return UpdateInfo 封装的更新信息
     */
    public static UpdateInfo getUpdateInfo(InputStream is) {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(is, "UTF-8");
            int type = parser.getEventType();
            UpdateInfo info = null;
            while(type!=XmlPullParser.END_DOCUMENT){
                switch (type) {
                case XmlPullParser.START_TAG:
                    String tagname = parser.getName();
                    if("info".equals(tagname)){
                        info = new UpdateInfo();
                    }else if("version".equals(tagname)){
                        String version = parser.nextText();
                        info.setVersion(version);
                    }
                    break;}
                type = parser.next();}
            return info;

下载apk后自动安装

/**
     * 安装下载完成的APK
     * @param savedFile
     */
    private void installAPK(File savedFile) {
        //调用系统的安装方法
        Intent intent=new Intent();
        intent.setAction(intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(savedFile), "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }

检测一个应用是否安装

//检查某个应用是否安装
    public static boolean checkAPP(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

过滤特殊字符

private String StringFilter(String str) throws PatternSyntaxException {  
    // 只允许字母和数字  
    // String regEx = "[^a-zA-Z0-9]";  
    // 清除掉所有特殊字符  
    String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";  
    Pattern p = Pattern.compile(regEx);  
    Matcher m = p.matcher(str);  
    return m.replaceAll("").trim();  
}  

获取主题中属性(例如背景色,文字颜色)

TypedArray array = getTheme().obtainStyledAttributes(new int[]{
                android.R.attr.colorBackground,
                android.R.attr.textColorPrimary,
        });
        backgroundColor = array.getColor(0, 0xFF00FF);
        int textColor = array.getColor(1, 0xFF00FF);
        array.recycle();

dp,px互转

    public static int dp2px(Context ct, int dp) {
        return (int) (ct.getResources().getDisplayMetrics().density * dp + 0.5f);
    }

    public static int px2dp(Context ct, int px) {
        return (int) (px / ct.getResources().getDisplayMetrics().density + 0.5f);
    }

两个图片切换(Kitkat以上)

drawable新建transition_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ye"/>
    <item android:drawable="@drawable/bye"/>
</transition>

代码中:

TransitionDrawable transitionDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.transition_drawable);
iv.setImageDrawable(transitionDrawable);
//会以渐变的形式切换图片
transitionDrawable.startTransition(500);

或者在xml中给iamgeview设置src=”@drawable/transition_drawable”在代码中start

TransitionDrawable td = (TransitionDrawable) iv.getDrawable();
td.startTransition(1000);

或者代码中创建TransitionDrawable设置(效果一样):

Drawable[] drawables = {getResources().getDrawable(R.drawable.ye), getResources().getDrawable(R.drawable.bye)};
TransitionDrawable transitionDrawable1 = new TransitionDrawable(drawables);
iv.setImageDrawable(transitionDrawable1);
transitionDrawable1.startTransition(500);

切换场景Scene

//获得scene,指定rootGroup
Scene scene1 = Scene.getSceneForLayout(rootView, R.layout.scene1, DetailActivity.this);
ChangeBounds changeBounds = new ChangeBounds();
changeBounds.setInterpolator(new DecelerateInterpolator()).setDuration(500);
//以ChangeBounds的方式从当前scene切换到scene1
TransitionManager.go(scene1, changeBounds);
//设置进入的过渡时间(v21)
getWindow().getEnterTransition().setDuration(500);
//退出时
finishAfterTransition();

例:

if (Util.isLollipop()) {
       Slide slideTransition = new Slide();
       slideTransition.setSlideEdge(Gravity.LEFT);
       slideTransition.setDuration(500);
       getWindow().setReenterTransition(slideTransition);
       getWindow().setExitTransition(slideTransition);
}

透明状态栏(沉浸式)

style-v19中添加,就能显示状态栏的情况下全屏

<item name="android:windowTranslucentStatus">true</item>

通过设置paddingTop,在dimens中
toolbar_padding_top=0dp
在dimens-v19中
toolbar_padding_top=25dp(状态栏的高度)

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        app:maxButtonHeight="40dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:paddingTop="@dimen/toolbar_padding_top"
        app:contentInsetStart="0dp">

注:不用android:fitsSystemWindows=”true”是因为有输入框时,弹出键盘布局上移的bug
app:contentInsetStart=”0dp”去掉toolbar前边的space(自定义toolbar的布局时)

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值