Android-外功篇-Utils

来源:互联网 发布:淘宝买东西返钱的软件 编辑:程序博客网 时间:2024/05/20 11:27

用到的实用代码片段

1.绘制圆角图片
public static Bitmap createCircleImage(Bitmap source, int min) {          final Paint paint = new Paint();          paint.setAntiAlias(true);          Bitmap target = Bitmap.createBitmap(min, min,Config.ARGB_8888);          Canvas canvas = new Canvas(target);          canvas.drawCircle(min / 2, min / 2, min / 2, paint);          paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));          canvas.drawBitmap(source, 0, 0, paint);          return target;  } 
2.获取外置SD卡路径(注:是外置SD卡(或拓展U盘的路径),内置则是通过Environment.getExternalStorageDirectory()获取)
public String getExtPath() {        String sdcard_path = null;        String sd_default = Environment.getExternalStorageDirectory()                .getAbsolutePath();        if (sd_default.endsWith("/")) {            sd_default = sd_default.substring(0, sd_default.length() - 1);        }        // 得到路径        try {            Runtime runtime = Runtime.getRuntime();            Process proc = runtime.exec("mount");            InputStream is = proc.getInputStream();            InputStreamReader isr = new InputStreamReader(is);            String line;            BufferedReader br = new BufferedReader(isr);            while ((line = br.readLine()) != null) {                if (line.contains("secure"))                    continue;                if (line.contains("asec"))                    continue;                if (line.contains("fat") && line.contains("/mnt/")) {                    String columns[] = line.split(" ");                    if (columns != null && columns.length > 1) {                        if (sd_default.trim().equals(columns[1].trim())) {                            continue;                        }                        sdcard_path = columns[1];                    }                } else if (line.contains("fuse") && line.contains("/mnt/")) {                    String columns[] = line.split(" ");                    if (columns != null && columns.length > 1) {                        if (sd_default.trim().equals(columns[1].trim())) {                            continue;                        }                        sdcard_path = columns[1];                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }        return sdcard_path;}
3.获取屏幕宽高
public String getScreenWidthAndHeight(){        DisplayMetrics dm = new DisplayMetrics();        dm = this.getResources().getDisplayMetrics();        int width = dm.widthPixels;// 宽度        int height = dm.heightPixels;// 高度        Log.i("aaaaa", "width11 = " + width);        Log.i("aaaaa", "height11 = " + height);             String msg =  width + ":" + height;             return msg; }
4.判断系统当前语言
private boolean isZh() {        String language = getResources().getConfiguration().locale.getLanguage();        if (language.endsWith("zh"))            return true;        else            return false;}
5.edittext监听小数点,用户只能输入小数点后两位
editText.addTextChangedListener(new TextWatcher() {            @Override            public void onTextChanged(CharSequence s, int start, int before,                    int count) {                //消除小数点后超过两位的字符​                if (s.toString().contains(".")) {                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {                        s = s.toString().subSequence(0,                                s.toString().indexOf(".") + 3);                        editText.setText(s);                        editText.setSelection(s.length());                    }                }                //输入的第一个字符为小数点时,自动在小数点前面不一个零                if (s.toString().trim().substring(0).equals(".")) {                    s = "0" + s;                    editText.setText(s);                    editText.setSelection(2);                }                 //如果输入的第一个和第二个字符都为0,则消除第二个0                if (s.toString().startsWith("0")                        && s.toString().trim().length() > 1) {                    if (!s.toString().substring(1, 2).equals(".")) {                        editText.setText(s.subSequence(0, 1));                        editText.setSelection(1);                        return;                    }                }            }            @Override            public void beforeTextChanged(CharSequence s, int start, int count,                    int after) {            }            @Override            public void afterTextChanged(Editable s) {                // TODO Auto-generated method stub            }});
6.判断当前是否为锁屏界面
KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); if (mKeyguardManager.inKeyguardRestrictedInputMode()) { // keyguard on }
7.根据月日获取星座
    public static String getConstellation(int month, int day) {        final String constellations[] = { "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座",                "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座" };        final int edgeDays[] = { 19, 18, 20, 20, 20, 21, 22, 22, 22, 22, 21, 21 };        if (day > edgeDays[month - 1]) {// 数组角标从零开始,所以-1            return constellations[month - 1];// 数组角标从零开始,所以-1        } else {            return constellations[(month - 2) < 0 ? 11 : (month - 2)];// month-2即month-1-1,当前月的前一个月的月份若小于零,则返回摩羯座        }    }
8. Android之二维码的生成与解析
8.1 根据文本生成对应的二维码:
// 生成QR图    public static Bitmap createImage(String tuid) {        Bitmap bitmap = null;        try {            // 需要引入core包            QRCodeWriter writer = new QRCodeWriter();            Log.i("Util", "生成的文本:" + tuid);            if (tuid == null || "".equals(tuid) || tuid.length() < 1) {                return null;            }            // 把输入的文本转为二维码            BitMatrix martix = writer.encode(tuid, BarcodeFormat.QR_CODE,                    QR_WIDTH, QR_HEIGHT);            System.out.println("w:" + martix.getWidth() + "h:"                    + martix.getHeight());            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");            BitMatrix bitMatrix = new QRCodeWriter().encode(tuid,                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];            for (int y = 0; y < QR_HEIGHT; y++) {                for (int x = 0; x < QR_WIDTH; x++) {                    if (bitMatrix.get(x, y)) {                        pixels[y * QR_WIDTH + x] = 0xff000000;                    } else {                        pixels[y * QR_WIDTH + x] = 0xffffffff;                    }                }            }            bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,                    Bitmap.Config.ARGB_8888);            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);//            qr_image.setImageBitmap(bitmap);        } catch (WriterException e) {            e.printStackTrace();        }        return bitmap;    }
8.2 根据二维码图片读取内容:
// 解析QR图片    private void scanningImage() {        Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>();        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");        // 获得待解析的图片        Bitmap bitmap = ((BitmapDrawable) qr_image.getDrawable()).getBitmap();        RGBLuminanceSource source = new RGBLuminanceSource(bitmap);        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));        QRCodeReader reader = new QRCodeReader();        Result result;        try {            result = reader.decode(bitmap1, hints);            // 得到解析后的文字            qr_result.setText(result.getText());        } catch (NotFoundException e) {            e.printStackTrace();        } catch (ChecksumException e) {            e.printStackTrace();        } catch (FormatException e) {            e.printStackTrace();        }    }
0 0
原创粉丝点击