android 常用方法汇总

/**
     * 判断当前网络是否连接
     *
     * @param activity 上下文
     * @return
     */
    public static boolean isNetworkAvailable(Context activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 获取网络状态,wifi,wap,2g,3g.
     *
     * @param context 上下文
     * @return String 网络状态
     */
    public static int getNetWorkType(Context context) {
        String res = "";
        int mNetWorkType = 0;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                mNetWorkType = WebConfig.NETWORKTYPE_WIFI;
            } else if (type.equalsIgnoreCase("MOBILE")) {
                String proxyHost = android.net.Proxy.getDefaultHost();

                mNetWorkType = TextUtils.isEmpty(proxyHost)
                        ? (isFastMobileNetwork(context) ? WebConfig.NETWORKTYPE_3G : WebConfig.NETWORKTYPE_2G)
                        : WebConfig.NETWORKTYPE_WAP;
            }
        } else {
            mNetWorkType = WebConfig.NETWORKTYPE_INVALID;
        }
        return mNetWorkType;

    }

    /**
     * 判断是否是FastMobileNetWork,将3G或者3G以上的网络称为快速网络
     *
     * @param context
     * @return
     */
    private static boolean isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        switch (telephonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            case TelephonyManager.NETWORK_TYPE_EHRPD:
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return false; // ~25 kbps
            case TelephonyManager.NETWORK_TYPE_LTE:
                return true; // ~ 10+ Mbps
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                return false;
            default:
                return false;
        }
    }


    /**
     * InputStream convert String
     *
     * @param is
     * @return
     */
    public static String inputStreamConvertToString(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();
    }


    /**
     * 自动生成验证码
     *
     * @param type 1标识数字 2标识 数字+字母 3标识字母
     * @param num  个数
     * @return
     */
    public static String getValidCode(int type, int num) {
        char[] numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        char[] numberWords = {
                '0', '1',
                '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
                'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        };
        char[] words = {
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
                'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        };
        StringBuffer str = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < num; i++) {
            if (type == 1)
                str.append(numbers[random.nextInt(numbers.length)]);
            else if (type == 2)
                str.append(numberWords[random.nextInt(numberWords.length)]);
            else
                str.append(words[random.nextInt(words.length)]);
        }
        return str.toString();
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /*
        移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
      联通:130、131、132、152、155、156、185、186
      电信:133、153、180、189、(1349卫通)
      总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9
      */
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 判断email格式是否正确
     */
    public static boolean isEmail(String email) {
        if (TextUtils.isEmpty(email)) return false;
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        Pattern p = Pattern.compile(str);

        Matcher m = p.matcher(email);

        return m.matches();

    }

    /**
     * 获取屏幕高度与宽度
     * 宽度
     * 高度
     *
     * @param activity
     * @return
     */
    public static int[] getScreenHeightWidth(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度(像素)
        int height = metric.heightPixels;   // 屏幕高度(像素)
        float density = metric.density;      // 屏幕密度(0.75 / 1.0 / 1.5)
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI(120 / 160 / 240)
        return new int[]{width, height};
    }


    /**
     * InputStream 转 byte[]
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStreamByte(InputStream inputStream) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = inputStream.read()) != -1)
            byteArrayOutputStream.write(ch);

        byte[] data = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        return data;
    }


    /**
     * 调用系统分享功能 分享文本
     *
     * @param context 操作对象
     * @param content 内容
     * @param title   标题
     */
    public static void systemShareText(Context context, String content, String title) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, content);
        sendIntent.setType("text/plain");
        context.startActivity(Intent.createChooser(sendIntent, title));
    }

    /**
     * 调用系统分享功能 分享图片
     *
     * @param context 操作对象
     * @param imgPath 图片路径
     * @param title   标题
     */
    public static void systemShareImg(Context context, String imgPath, String title) {
        File f = new File(imgPath);
        if (f.exists()) {
            Uri u = Uri.fromFile(f);
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, u);
            shareIntent.setType("image/png");
            context.startActivity(Intent.createChooser(shareIntent, title));
        }
    }


    /**
     * 获取字符串中的数字
     *
     * @param str 源字符串
     * @return
     */
    public static String getIntFromString(String str) {
        Pattern p = Pattern.compile("[^0-9]");
        Matcher m = p.matcher(str);
        str = m.replaceAll("");
        return str;
    }


    /**
     * 将Bitmap保存到本地
     *
     * @param picName 文件名
     * @param bm      Bitmap
     * @throws Exception
     */
    public static void saveBitmap(String picName, Bitmap bm) throws Exception {
        /*File temp = new File(path);
        if (!temp.exists()) temp.mkdir();*/
        //File f = new File(path, picName);
        File f = getAlbumStorageDir(picName);
        if (f.exists()) f.delete();
        else f.createNewFile();
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //&&获取图片公共路径
    public static File getAlbumStorageDir(String albumName) {
        // Get the directory for the user's public pictures directory.

        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
        if (!file.mkdirs()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * Drawable 转 Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap DrawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        }
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 通过Map对象转成Url参数
     *
     * @param map ?key=value&key=value
     * @return
     */
    public static String getURLParaFromMap(Map<String, String> map) {
        StringBuffer sb = new StringBuffer("?");
        boolean isFirst = true;
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> temp : entries) {
            String key = temp.getKey();
            String name = temp.getValue();
            if (isFirst) {
                sb.append(key).append("=").append(name);
                isFirst = false;
            } else
                sb.append("&").append(key).append("=").append(name);
        }
        return sb.toString();
    }

    /**
     * 通过Map对象转成Url参数
     *
     * @param map
     * @return
     */
    public static String getURlParaFromMap_utf_8(String url, Map<String, String> map) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        if (map != null) {
            sb.append("?");
            boolean isFirst = true;
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> temp : entries) {
                String key = temp.getKey();
                String name = temp.getValue();
                if (isFirst) {
                    sb.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(name, "UTF-8"));
                    isFirst = false;
                } else
                    sb.append("&").append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(name, "UTF-8"));
            }
        }
        return sb.toString();
    }

    /**
     * 利用Volley异步加载图片
     * <p>
     * 注意方法参数:
     * getImageListener(ImageView view, int defaultImageResId, int errorImageResId)
     * 第一个参数:显示图片的ImageView
     * 第二个参数:默认显示的图片资源
     * 第三个参数:加载错误时显示的图片资源
     */
    public static void loadImageByVolley(Context context, String imageUrl, RoundImageView imageView, final Users users) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public void putBitmap(String key, Bitmap value) {
                lruCache.put(key, value);
            }

            @Override
            public Bitmap getBitmap(String key) {
                return lruCache.get(key);
            }
        };
        ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, R.mipmap.header, R.mipmap.header);
        imageLoader.get(imageUrl, listener);
        //&&写入缓存文件
        if (users != null)
            SPUtils.putUsersSp(users, context);
    }

    /**
     * 利用Volley异步加载图片
     * <p>
     * 注意方法参数:
     * getImageListener(ImageView view, int defaultImageResId, int errorImageResId)
     * 第一个参数:显示图片的ImageView
     * 第二个参数:默认显示的图片资源
     * 第三个参数:加载错误时显示的图片资源
     *
     * @param context
     * @param imageUrl  图片url
     * @param imageView 显示控件
     * @param defaultID 默认显示图片
     * @param errorID   请求发生错误显示图片
     */
    public static void loadImageByVolley(Context context, String imageUrl, ImageView imageView, int defaultID, int errorID) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
        // Use 1/8th of the available memory for this memory cache.
        int cacheSize = 1024 * 1024 * memClass / 4;
        final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(cacheSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {

            @Override
            public void putBitmap(String key, Bitmap value) {
                lruCache.put(key, value);
            }

            @Override
            public Bitmap getBitmap(String key) {
                return lruCache.get(key);
            }
        };
        ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, defaultID, errorID);
        imageLoader.get(imageUrl, listener);

    }

    /**
     * 获取网络图片
     *
     * @param url
     * @return
     */
    public static void getBitmapFromURL(final Context context, String url, final RoundImageView imageView, final Users users) {
        //RequestQueue mQueue = Volley.newRequestQueue(context);

        ImageRequest imageRequest = new ImageRequest(
                url,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                        imageView.setImageBitmap(bitmap);
                        try {
                            saveBitmap(users.getAccount(), bitmap);
                            users.setPhoto(
                                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/"
                                            + users.getAccount()
                            );
                            SPUtils.putUsersSp(users, context);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, 0, 0, Bitmap.Config.RGB_565,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //if (error != null)
                        //Log.e("yz1309", "Error:" + error.getMessage());
                    }
                });
        //mQueue.add(imageRequest);
        CusQuesApplication.getInstance().addToRequestQueue(imageRequest, users.getAccount() + "_img");
    }

    /**
     * 获取ActionBar的高度
     *
     * @param activity 页面对象
     * @return
     */
    public static int getActionBarHeight(Activity activity) {
        int actionBarHeight = 0;
        TypedValue tv = new TypedValue();
        if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }

    /**
     * 获取versionname的值
     *
     * @param context
     * @return
     */
    public static String getVersion(Context context)//获取版本号
    {
        String ver = "";
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            ver = pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            ver = context.getString(R.string.version);
        }
        return "V" + ver;

    }

    /**
     * 判断是否存在SDCard
     *
     * @return
     */
    public static boolean HasSDCard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }


    /**
     * 暂时未用
     * 获取JsonObject中某个key 的值
     *
     * @param jsonObject
     * @param key
     * @param type         1 int、2 Bool、3 Double、4 JsonArray、5 JsonObject、6 Long、7 String
     * @param defaultValue 默认值
     * @return
     */
    public static Object getJsonObject(JSONObject jsonObject, String key, int type, Object defaultValue) {
        Object obj = null;
        if (jsonObject.isNull(key))
            obj = defaultValue;
        else {
            try {
                switch (type) {
                    case 1:
                        obj = jsonObject.getInt(key);
                        break;
                    case 2:
                        obj = jsonObject.getBoolean(key);
                        break;
                    case 3:
                        obj = jsonObject.getDouble(key);
                        break;
                    case 4:
                        obj = jsonObject.getJSONArray(key);
                        break;
                    case 5:
                        obj = jsonObject.getJSONObject(key);
                        break;
                    case 6:
                        obj = jsonObject.getLong(key);
                        break;
                    case 7:
                        obj = jsonObject.getString(key);
                        break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return obj;
    }

    /**
     * 自定义Toast显示
     *
     * @param context Activity
     * @param mes     消息内容
     * @param times   1 Long 0 Short
     */
    public static void cusToast(Activity context, String mes, int times) {
        //获取LayoutInflater对象,该对象能把XML文件转换为与之一直的View对象
        LayoutInflater inflater = context.getLayoutInflater();
        //根据指定的布局文件创建一个具有层级关系的View对象
        //第二个参数为View对象的根节点,即LinearLayout的ID
        View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) context.findViewById(R.id.llToast));
        //查找ImageView控件
        TextView text = (TextView) layout.findViewById(R.id.tvMes);
        text.setText(mes);
        Toast toast = new Toast(context);
        //设置Toast的位置
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(times);
        //让Toast显示为我们自定义的样子
        toast.setView(layout);
        toast.show();
    }

    /**
     * 此方法保存图片到手机sd卡中
     *
     * @param bm       文件
     * @param fileName 文件名
     * @throws IOException
     */
    public static void saveFileToSdCord(Bitmap bm, String fileName) throws IOException {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            String path = sdcardDir.getPath() + "/yikeedu";
            File foder = new File(path);
            if (!foder.exists()) {
                foder.mkdirs();
            }
            File myCaptureFile = new File(path, fileName);
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }


            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
        }
        //else{
        //Log.i("path no path:", "失败");
        //}
    }

    /**
     * md5加密
     */

    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        //16位加密,从第9位到25位
//        return md5StrBuff.substring(8, 24).toString().toUpperCase();
        return md5StrBuff.toString().toLowerCase();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值