Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 開發實用方法大全

Android 開發實用方法大全

編輯:關於Android編程

1.格式化價格,這個經常在計算費用精度的時候用到

    /**
     * 格式化價格
     * 
     * @param argStr 傳入價格字符串
     * @return
     */
    public static String getFloatDotStr(String argStr) {
        float arg = Float.valueOf(argStr);
        DecimalFormat fnum = new DecimalFormat("##0.00");
        return fnum.format(arg);
    }

2.獲取App的版本號Version

    // 得到versionCode
    public static int getVerCode(Context context) {
        int verCode = 0;
        try {
            verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return verCode;
    }

3.獲取手機屏幕寬高:

    /**
     * 屏幕寬高
     * 
     * @param context
     * @return 0:width,1:height
     */
    public static int[] ScreenSize(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
        return new int[] { metrics.widthPixels, metrics.heightPixels };
    }

4.判斷SD卡是否存在:

 

    /**
     * 判斷sd卡是否存在
     * 
     * @author
     * @return
     */
    public static boolean judgeSDCard() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

5.驗證是否中文:

    /***
     * 驗證是否中文
     * 
     * @param
     * @return
     */
    public static boolean validName(String name) {
        String pattern = "[\u4e00-\u9fa5]";
        if (isNull(name))
            return false;
        return name.matches(pattern);
    }

6.驗證身份證號碼:

    /**
     * 驗證身份證號碼
     * 
     * @author
     * @param idCard
     * @return
     */
    public static boolean validateIdCard(String idCard) {
        if (isNull(idCard))
            return false;
        String pattern = "^[0-9]{17}[0-9|xX]{1}$";
        return idCard.matches(pattern);
    }

7.驗證手機號碼:

    /**
     * 驗證手機號碼
     * 
     * @author
     * @param phone
     * @return
     */
    public static boolean validatePhone(String phone) {
        if (isNull(phone))
            return false;
        String pattern = "^1[3,4,5,6,8]\\d{9}$";
        return phone.matches(pattern);
    }

8.驗證郵編:

    /**
     * 判斷郵編
     * 
     * @param 
     * @return
     */
    public static boolean isZipNO(String zipString) {
        String str = "^[1-9][0-9]{5}$";
        return Pattern.compile(str).matcher(zipString).matches();
    }

9.驗證銀行卡號:

/**
     * 驗證銀行卡號
     * 
     * @param bankCard
     *            信用卡是16位,其他的是13-19位
     * @return
     */
    public static boolean validateBankCard(String bankCard) {
        if (isNull(bankCard))
            return false;
        String pattern = "^\\d{13,19}$";
        return bankCard.matches(pattern);
    }

10.驗證郵箱:

/**
     * 驗證郵箱
     * 
     * @author 
     * @param email
     * @return
     */
    public static boolean validateEmail(String email) {
        if (isNull(email))
            return false;
        String pattern = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
        return email.matches(pattern);
    }

11.將圖片設置為圓角圖片:

    /**
     * 設置圓角的圖片
     * 
     * @author 
     * @param bitmap
     *            圖片
     * @param pixels
     *            角度
     * @return
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        try {
            if (bitmap != null) {
                Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
                Canvas canvas = new Canvas(output);

                final int color = 0xff424242;
                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
                final RectF rectF = new RectF(rect);
                final float roundPx = pixels;

                paint.setAntiAlias(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(color);
                canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

                paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
                canvas.drawBitmap(bitmap, rect, rect, paint);

                return output;
            }
        } catch (Exception e) {
        }

        return bitmap;
    }

    /**
     * 將圖片轉換為圓形的
     * 
     * @author 
     * @param bitmap
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            bitmap = cutSquareBitmap(bitmap);
            return toRoundCorner(bitmap, bitmap.getWidth() / 2);
        }
        return bitmap;
    }

12.判斷有無網絡鏈接

// 判斷有無網絡鏈接
    public static boolean checkNetworkInfo(Context mContext) {
        ConnectivityManager conMan = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (mobile == State.CONNECTED || mobile == State.CONNECTING)
            return true;
        if (wifi == State.CONNECTED || wifi == State.CONNECTING)
            return true;
        return false;
    }

13.判斷是否連接wifi

    /**
     * 判斷是否連接wifi
     * 
     * @param mContext
     * @return 返回true則有wifi
     */
    private static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

14.獲取SIM卡存在的狀態

/** 獲取SIM卡存在的狀態 */
    public static String getSIMCardExist(Context context) {
        manager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        String state = "";
        switch (manager.getSimState()) {
        case TelephonyManager.SIM_STATE_READY:
            state = "良好";
            break;
        case TelephonyManager.SIM_STATE_ABSENT:
            state = "無SIM卡";
            break;
        default:
            state = "SIM卡被鎖定或未知狀態";
            break;
        }
        return state;
    }

15. bitmap和base64類型互轉

// 把bitmap轉換成base64
    public static String getBase64FromBitmap(Bitmap bitmap, int bitmapQuality) {
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, bitmapQuality, bStream);
        byte[] bytes = bStream.toByteArray();
        return Base64.encode(bytes);
    }

    // 把base64轉換成bitmap
    public static Bitmap getBitmapFromBase64(String string) {
        byte[] bitmapArray = null;
        try {
            bitmapArray = Base64.decode(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
    }

16. 把圖片流轉換成byte數組

/**
     * 
     * 方法說明 把圖片流轉換成byte數組
     * 
     * @author 
     * @param
     * @return
     */
    public static byte[] getByteFromStream(InputStream inStream) {
        byte[] data = new byte[1024];
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        try {
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            data = outStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outStream.close();
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

17.把字節數組轉化成bitmap

/**
     * 
     * 把字節數組轉化成bitmap
     * 
     * @author 
     * @param
     * @return
     */
    public static Bitmap getBitmapFromBytes(byte[] bytes, BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }

18.把Stream轉換成String

// 把Stream轉換成String
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

19.防止按鈕連續點擊

/**
     * 防止按鈕連續點擊
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

20.保存圖片到SD卡

/**
     * 保存圖片
     * 
     * @param photoBitmap
     * @param path 保存路徑
     */
    public static void savePhotoToSDCard(Bitmap photoBitmap, String path) {

        File photoFile = new File(path);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(photoFile);
            if (photoBitmap != null) {
                if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream)) {
                    fileOutputStream.flush();
                }
            }
        } catch (FileNotFoundException e) {
            photoFile.delete();
            e.printStackTrace();
        } catch (IOException e) {
            photoFile.delete();
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

21.將字符串轉化為二維碼:

private static int QR_WIDTH = 300;
    private static int QR_HEIGHT = 300;

    public static Bitmap createQRImage(String url) {
        try {
            // 判斷URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 圖像數據轉換,使用了矩陣轉換
            BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            // 下面這裡按照二維碼的算法,逐個生成二維碼的圖片,
            // 兩個for循環是圖片橫列掃描的結果
            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;
                    }
                }
            }
            // 生成二維碼圖片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

22.得到自定義進度框:

/**
     * 得到自定義的progressDialog
     * 
     * @param context
     * @param msg
     * @param bCancel
     *            按返回鍵是否取消
     * @return
     */
    public static Dialog createLoadingDialog(Context context, String msg, boolean bCancel) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加載view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加載布局
        // main.xml中的ImageView
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        // 加載動畫
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context, R.anim.loading_animation);
        // 使用ImageView顯示動畫
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(msg);// 設置加載信息

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 創建自定義樣式dialog

        loadingDialog.setCancelable(bCancel);// 不可以用“返回鍵”取消
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));// 設置布局
        return loadingDialog;

    }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved