├── .gitignore ├── README.md ├── YHUtils ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── xyz │ │ └── yhsj │ │ └── yhutils │ │ ├── form │ │ └── FormUtils.java │ │ ├── io │ │ ├── AssetUtils.java │ │ ├── FileUtil.java │ │ ├── IOUtils.java │ │ ├── ImageUtils.java │ │ ├── ResouceUtil.java │ │ └── SDCardUtils.java │ │ ├── keyboard │ │ └── KeyBoardUtils.java │ │ ├── logutils │ │ ├── LogType.java │ │ ├── LogUtils.java │ │ ├── Logger.java │ │ ├── Printer.java │ │ └── utils │ │ │ ├── ArrayUtil.java │ │ │ └── SystemUtil.java │ │ ├── notification │ │ └── NotificationUtils.java │ │ ├── phone │ │ ├── AppDataUtils.java │ │ ├── AppUtils.java │ │ ├── CpuUtils.java │ │ ├── DeviceUtils.java │ │ ├── LocationUtils.java │ │ ├── NetWorkUtils.java │ │ ├── NetWorkUtilsBroadcast.java │ │ ├── NetWorkUtils_Broadcast.java │ │ ├── ScreenUtils.java │ │ └── ShellUtils.java │ │ ├── secarity │ │ ├── AESUtils.java │ │ ├── Base64Utils.java │ │ ├── DES3Utils.java │ │ ├── DESUtils.java │ │ ├── HexUtils.java │ │ ├── MD5Utils.java │ │ └── RSAUtils.java │ │ ├── sp │ │ └── SharePreferenceUtil.java │ │ ├── string │ │ ├── DateUtils.java │ │ ├── DensityUtils.java │ │ └── StringUtils.java │ │ └── tools │ │ └── ClassUtils.java │ └── res │ └── values │ └── strings.xml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── xyz │ │ └── yhsj │ │ └── yhutilsDemo │ │ └── MainActivity.java │ └── res │ ├── layout │ ├── activity_main.xml │ └── content_main.xml │ ├── menu │ └── menu_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-v21 │ └── styles.xml │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | ### Android template 2 | # Built application files 3 | *.apk 4 | *.ap_ 5 | 6 | # Files for the Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | ### Example user template template 32 | ### Example user template 33 | 34 | # IntelliJ project files 35 | .idea 36 | *.iml 37 | out 38 | gen 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YHUtls 2 | 常用工具库,包含一些实用工具 3 | 4 | 5 | -------------------------------------------------------------------------------- /YHUtils/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /YHUtils/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 14 9 | targetSdkVersion 23 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | compile 'com.android.support:appcompat-v7:23.1.1' 24 | } 25 | -------------------------------------------------------------------------------- /YHUtils/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Develop\android_SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /YHUtils/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/form/FormUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.form; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONObject; 5 | 6 | import android.annotation.SuppressLint; 7 | import android.inputmethodservice.ExtractEditText; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.AbsoluteLayout; 11 | import android.widget.AutoCompleteTextView; 12 | import android.widget.CheckBox; 13 | import android.widget.EditText; 14 | import android.widget.FrameLayout; 15 | import android.widget.LinearLayout; 16 | import android.widget.MultiAutoCompleteTextView; 17 | import android.widget.RadioButton; 18 | import android.widget.RadioGroup; 19 | import android.widget.RelativeLayout; 20 | import android.widget.TableLayout; 21 | 22 | /** 23 | * 表单工具类,获得数据或者设置数据 24 | * 25 | * @author 修改 by 永恒瞬间(power by zftlive) 26 | * @version 1.0 27 | */ 28 | @SuppressWarnings("deprecation") 29 | public class FormUtils { 30 | /** 31 | * 获取表单的数据(根据Tag获取控件:键-值,返回json格式) 32 | * 33 | * @param root 34 | * 当前表单容器 35 | * @param data 36 | * 当前表单数据 37 | * @return 表单数据(CheckBox多选选项JSONArray拼接) 38 | */ 39 | 40 | @SuppressLint("NewApi") 41 | public static JSONObject getFormInfo(ViewGroup root, JSONObject data) 42 | throws Exception { 43 | if (root.getChildCount() > 0) { 44 | for (int i = 0; i < root.getChildCount(); i++) { 45 | 46 | View view = root.getChildAt(i); 47 | // 容器级别控件需要进行递归 48 | if (view instanceof LinearLayout) { 49 | getFormInfo((LinearLayout) view, data); 50 | } else if (view instanceof RelativeLayout) { 51 | getFormInfo((RelativeLayout) view, data); 52 | } else if (view instanceof FrameLayout) { 53 | getFormInfo((FrameLayout) view, data); 54 | } else if (view instanceof AbsoluteLayout) { 55 | getFormInfo((AbsoluteLayout) view, data); 56 | } else if (view instanceof RadioGroup) { 57 | getFormInfo((RadioGroup) view, data); 58 | } else if (view instanceof TableLayout) { 59 | getFormInfo((TableLayout) view, data); 60 | } 61 | 62 | // 非容器级别控件不用递归 63 | /** 64 | * EditText.class 65 | */ 66 | else if (view instanceof EditText) { 67 | 68 | if (view.getTag() != null) { 69 | data.put((String) view.getTag(), ((EditText) view) 70 | .getText().toString()); 71 | } 72 | 73 | } else if (view instanceof AutoCompleteTextView) { 74 | 75 | if (view.getTag() != null) { 76 | data.put((String) view.getTag(), 77 | ((AutoCompleteTextView) view).getText() 78 | .toString()); 79 | } 80 | 81 | } else if (view instanceof MultiAutoCompleteTextView) { 82 | 83 | if (view.getTag() != null) { 84 | data.put((String) view.getTag(), 85 | ((MultiAutoCompleteTextView) view).getText() 86 | .toString()); 87 | } 88 | 89 | } else if (view instanceof ExtractEditText) { 90 | 91 | if (view.getTag() != null) { 92 | data.put((String) view.getTag(), 93 | ((ExtractEditText) view).getText().toString()); 94 | } 95 | } 96 | 97 | /** 98 | * RadioButton.class 99 | */ 100 | else if (view.getClass().getName() 101 | .equals(RadioButton.class.getName())) { 102 | 103 | if (view.getTag() != null) { 104 | if (((RadioButton) view).isChecked()) { 105 | data.put((String) view.getTag(), 106 | ((RadioButton) view).getText().toString()); 107 | } 108 | } 109 | } 110 | 111 | /** 112 | * CheckBox.class(需要拼装选中复选框) 113 | */ 114 | else if (view.getClass().getName() 115 | .equals(CheckBox.class.getName())) { 116 | 117 | if (view.getTag() != null) { 118 | 119 | if (((CheckBox) view).isChecked()) { 120 | 121 | if (!data.isNull((String) view.getTag())) { 122 | 123 | JSONArray value = data.getJSONArray(view 124 | .getTag().toString()); 125 | value.put(((CheckBox) view).getText() 126 | .toString()); 127 | data.put((String) view.getTag(), value); 128 | } else { 129 | JSONArray arr = new JSONArray(); 130 | arr.put(((CheckBox) view).getText().toString()); 131 | data.put((String) view.getTag(), arr); 132 | 133 | } 134 | } 135 | } 136 | 137 | } 138 | /** 139 | * Spinner.class 140 | */ 141 | else if (view.getClass().getName() 142 | .equals(android.widget.Spinner.class.getName())) { 143 | 144 | if (view.getTag() != null) { 145 | data.put((String) view.getTag(), 146 | ((android.widget.Spinner) view) 147 | .getSelectedItem().toString()); 148 | } 149 | } 150 | } 151 | } 152 | 153 | return data; 154 | } 155 | 156 | 157 | 158 | } 159 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/io/AssetUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.io; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | 6 | import android.content.Context; 7 | import android.content.res.AssetManager; 8 | import android.graphics.drawable.Drawable; 9 | 10 | /** 11 | * Asset 工具类
12 | */ 13 | @SuppressWarnings("deprecation") 14 | public class AssetUtils { 15 | 16 | /** 17 | * 打开Asset下的文件 18 | * 19 | * @param fileName 文件名 20 | * @return 21 | */ 22 | public static InputStream openAssetFile(Context context, String fileName) { 23 | AssetManager am = context.getAssets(); 24 | InputStream is = null; 25 | try { 26 | is = am.open(fileName); 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } 30 | return is; 31 | } 32 | 33 | /** 34 | * 从assets 文件夹中读取文本数据 35 | */ 36 | public static String getTextFromAssets(final Context context, 37 | String fileName) { 38 | String result = ""; 39 | try { 40 | InputStream in = context.getResources().getAssets().open(fileName); 41 | // 获取文件的字节数 42 | int lenght = in.available(); 43 | // 创建byte数组 44 | byte[] buffer = new byte[lenght]; 45 | // 将文件中的数据读到byte数组中 46 | in.read(buffer); 47 | result = new String(buffer, "UTF-8"); 48 | in.close(); 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | } 52 | return result; 53 | } 54 | 55 | /** 56 | * 从assets 文件夹中读取图片 57 | */ 58 | public static Drawable loadImageFromAsserts(final Context ctx, 59 | String fileName) { 60 | try { 61 | InputStream is = ctx.getResources().getAssets().open(fileName); 62 | return Drawable.createFromStream(is, null); 63 | } catch (IOException e) { 64 | if (e != null) { 65 | e.printStackTrace(); 66 | } 67 | } catch (OutOfMemoryError e) { 68 | if (e != null) { 69 | e.printStackTrace(); 70 | } 71 | } catch (Exception e) { 72 | if (e != null) { 73 | e.printStackTrace(); 74 | } 75 | } 76 | return null; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/io/FileUtil.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.io; 2 | 3 | import java.text.DecimalFormat; 4 | 5 | /** 6 | * Created by wangkuan on 15/10/13. 7 | */ 8 | public class FileUtil { 9 | 10 | /** 11 | * 获取文件的大小 12 | * 13 | * @param fileS 14 | * @return 15 | */ 16 | public static String FormetFileSize(long fileS) {//转换文件大小 17 | DecimalFormat df = new DecimalFormat("#.00"); 18 | String fileSizeString = "0K"; 19 | if (fileS < 1024) { 20 | fileSizeString = df.format((double) fileS) + "B"; 21 | } else if (fileS < 1048576) { 22 | fileSizeString = df.format((double) fileS / 1024) + "K"; 23 | } else if (fileS < 1073741824) { 24 | fileSizeString = df.format((double) fileS / 1048576) + "M"; 25 | } else { 26 | fileSizeString = df.format((double) fileS / 1073741824) + "G"; 27 | } 28 | return fileSizeString; 29 | } 30 | 31 | public static String FormatFileSizeByMB(long fileS) {//转换文件大小 32 | 33 | 34 | return String.format("%.2fM", (double) fileS / 1048576); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/io/IOUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.io; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.ByteArrayOutputStream; 6 | import java.io.FileInputStream; 7 | import java.io.FileNotFoundException; 8 | import java.io.FileOutputStream; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.io.InputStreamReader; 12 | import java.io.OutputStreamWriter; 13 | 14 | import android.content.Context; 15 | 16 | /** 17 | * IO流 工具类
18 | * 很简单,仅支持文本操作 19 | * 20 | */ 21 | public class IOUtils { 22 | 23 | /** 24 | * 文本的写入操作 25 | * 26 | * @param filePath 27 | * 文件路径。一定要加上文件名字
28 | * 例如:../a/a.txt 29 | * @param content 30 | * 写入内容 31 | * @param append 32 | * 是否追加 33 | */ 34 | public static void write(String filePath, String content, boolean append) { 35 | BufferedWriter bufw = null; 36 | try { 37 | bufw = new BufferedWriter(new OutputStreamWriter( 38 | new FileOutputStream(filePath, append))); 39 | bufw.write(content); 40 | 41 | } catch (Exception e1) { 42 | e1.printStackTrace(); 43 | } finally { 44 | if (bufw != null) { 45 | try { 46 | bufw.close(); 47 | } catch (IOException e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | } 52 | } 53 | 54 | /** 55 | * 文本的读取操作 56 | * 57 | * @param path 58 | * 文件路径,一定要加上文件名字
59 | * 例如:../a/a.txt 60 | * @return 61 | */ 62 | public static String read(String path) { 63 | BufferedReader bufr = null; 64 | try { 65 | bufr = new BufferedReader(new InputStreamReader( 66 | new FileInputStream(path))); 67 | StringBuffer sb = new StringBuffer(); 68 | String str = null; 69 | while ((str = bufr.readLine()) != null) { 70 | sb.append(str); 71 | } 72 | return sb.toString(); 73 | } catch (Exception e) { 74 | e.printStackTrace(); 75 | } finally { 76 | if (bufr != null) { 77 | try { 78 | bufr.close(); 79 | } catch (IOException e) { 80 | e.printStackTrace(); 81 | } 82 | } 83 | } 84 | return null; 85 | } 86 | 87 | /** 88 | * 文本的读取操作 89 | * 90 | * @param is 输入流 91 | * @return 92 | */ 93 | public static String read(InputStream is) { 94 | BufferedReader bufr = null; 95 | try { 96 | bufr = new BufferedReader(new InputStreamReader(is)); 97 | StringBuffer sb = new StringBuffer(); 98 | String str = null; 99 | while ((str = bufr.readLine()) != null) { 100 | sb.append(str); 101 | } 102 | return sb.toString(); 103 | } catch (Exception e) { 104 | e.printStackTrace(); 105 | } finally { 106 | if (bufr != null) { 107 | try { 108 | bufr.close(); 109 | } catch (IOException e) { 110 | e.printStackTrace(); 111 | } 112 | } 113 | } 114 | return null; 115 | } 116 | 117 | 118 | /** 119 | * @param context 上下文 120 | * @param fileName 文件名 121 | * @return 字节数组 122 | */ 123 | public static byte[] readBytes(Context context, String fileName) { 124 | FileInputStream fin = null; 125 | byte[] buffer = null; 126 | try { 127 | fin = context.openFileInput(fileName); 128 | int length = fin.available(); 129 | buffer = new byte[length]; 130 | fin.read(buffer); 131 | } catch (FileNotFoundException e) { 132 | e.printStackTrace(); 133 | } catch (IOException e) { 134 | e.printStackTrace(); 135 | } finally { 136 | try { 137 | if (fin != null) { 138 | fin.close(); 139 | fin = null; 140 | } 141 | } catch (IOException e) { 142 | e.printStackTrace(); 143 | } 144 | } 145 | return buffer; 146 | } 147 | 148 | /** 149 | * 快速读取程序应用包下的文件内容 150 | * 151 | * @param context 152 | * 上下文 153 | * @param filename 154 | * 文件名称 155 | * @return 文件内容 156 | * @throws IOException 157 | */ 158 | public static String read(Context context, String filename) 159 | throws IOException { 160 | FileInputStream inStream = context.openFileInput(filename); 161 | ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 162 | byte[] buffer = new byte[1024]; 163 | int len = 0; 164 | while ((len = inStream.read(buffer)) != -1) { 165 | outStream.write(buffer, 0, len); 166 | } 167 | byte[] data = outStream.toByteArray(); 168 | return new String(data); 169 | } 170 | 171 | 172 | } 173 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/io/ImageUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.io; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | import android.content.Context; 8 | import android.graphics.Bitmap; 9 | import android.graphics.drawable.BitmapDrawable; 10 | import android.graphics.drawable.ColorDrawable; 11 | import android.graphics.drawable.Drawable; 12 | import android.graphics.drawable.TransitionDrawable; 13 | import android.support.annotation.DrawableRes; 14 | import android.widget.ImageView; 15 | 16 | public class ImageUtils { 17 | 18 | /** 19 | * 渐变显示图片 20 | * 21 | * @param context 22 | * @param imageView 23 | * @param bitmap 24 | */ 25 | @SuppressWarnings("deprecation") 26 | public static void setImageBitmap(Context context, ImageView imageView, 27 | Bitmap bitmap) { 28 | // Use TransitionDrawable to fade in. 29 | final TransitionDrawable td = new TransitionDrawable(new Drawable[]{ 30 | new ColorDrawable(context.getResources().getColor(android.R.color.transparent)), 31 | new BitmapDrawable(context.getResources(), bitmap)}); 32 | // noinspection deprecation 33 | // imageView.setBackgroundDrawable(imageView.getDrawable()); 34 | imageView.setImageDrawable(td); 35 | td.startTransition(200); 36 | } 37 | 38 | /** 39 | * 保存图片 40 | * 41 | * @param filePath 文件路径+文件名 42 | * @param bitmap 文件内容 43 | * @throws IOException 44 | */ 45 | public static void saveAsJPEG(Bitmap bitmap, String filePath) 46 | throws IOException { 47 | FileOutputStream fos = null; 48 | 49 | try { 50 | File file = new File(filePath); 51 | if (!file.getParentFile().exists()) { 52 | file.getParentFile().mkdirs(); 53 | } 54 | fos = new FileOutputStream(file); 55 | bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 56 | fos.flush(); 57 | } finally { 58 | if (fos != null) { 59 | fos.close(); 60 | } 61 | } 62 | } 63 | 64 | /** 65 | * 保存图片 66 | * 67 | * @param filePath 文件路径+文件名 68 | * @param bitmap 文件内容 69 | * @throws IOException 70 | */ 71 | public static void saveAsPNG(Bitmap bitmap, String filePath) 72 | throws IOException { 73 | FileOutputStream fos = null; 74 | 75 | try { 76 | File file = new File(filePath); 77 | if (!file.getParentFile().exists()) { 78 | file.getParentFile().mkdirs(); 79 | } 80 | fos = new FileOutputStream(file); 81 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); 82 | fos.flush(); 83 | } finally { 84 | if (fos != null) { 85 | fos.close(); 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/io/ResouceUtil.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.io; 2 | 3 | import android.content.Context; 4 | import android.content.pm.ApplicationInfo; 5 | import android.content.pm.PackageManager; 6 | import android.content.res.AssetManager; 7 | import android.graphics.drawable.Drawable; 8 | 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | 12 | import xyz.yhsj.yhutils.string.StringUtils; 13 | 14 | 15 | /** 16 | * Asset 工具类
17 | */ 18 | @SuppressWarnings("deprecation") 19 | public class ResouceUtil { 20 | 21 | /** 22 | * 打开Asset下的文件 23 | * 24 | * @param fileName 文件名 25 | * @return 26 | */ 27 | public static InputStream openAssetFile(Context context, String fileName) { 28 | AssetManager am = context.getAssets(); 29 | InputStream is = null; 30 | try { 31 | is = am.open(fileName); 32 | } catch (IOException e) { 33 | e.printStackTrace(); 34 | } 35 | return is; 36 | } 37 | 38 | /** 39 | * 从assets 文件夹中读取文本数据 40 | */ 41 | public static String getStringFromAssets(final Context context, 42 | String fileName) { 43 | String result = ""; 44 | try { 45 | InputStream in = context.getResources().getAssets().open(fileName); 46 | // 获取文件的字节数 47 | int lenght = in.available(); 48 | // 创建byte数组 49 | byte[] buffer = new byte[lenght]; 50 | // 将文件中的数据读到byte数组中 51 | in.read(buffer); 52 | result = new String(buffer, "UTF-8"); 53 | in.close(); 54 | } catch (Exception e) { 55 | e.printStackTrace(); 56 | } 57 | return result; 58 | } 59 | 60 | /** 61 | * 从assets 文件夹中读取图片 62 | */ 63 | public static Drawable loadImageFromAsserts(final Context ctx, 64 | String fileName) { 65 | try { 66 | InputStream is = ctx.getResources().getAssets().open(fileName); 67 | return Drawable.createFromStream(is, null); 68 | } catch (IOException e) { 69 | if (e != null) { 70 | e.printStackTrace(); 71 | } 72 | } catch (OutOfMemoryError e) { 73 | if (e != null) { 74 | e.printStackTrace(); 75 | } 76 | } catch (Exception e) { 77 | if (e != null) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | return null; 82 | } 83 | 84 | 85 | /** 86 | * 从assert文件夹下读取文件到字节数组 87 | * 88 | * @param context 上下文 89 | * @param fileName 文件名 90 | * @return 文件字节数组 91 | */ 92 | public static byte[] readBytesFromAssert(Context context, String fileName) { 93 | InputStream is = null; 94 | byte[] buffer = null; 95 | try { 96 | is = context.getAssets().open(fileName); 97 | int size = is.available(); 98 | buffer = new byte[size]; 99 | is.read(buffer); 100 | } catch (IOException e) { 101 | e.printStackTrace(); 102 | } finally { 103 | if (is != null) { 104 | try { 105 | is.close(); 106 | is = null; 107 | } catch (IOException e) { 108 | e.printStackTrace(); 109 | } 110 | } 111 | } 112 | 113 | return buffer; 114 | } 115 | 116 | /** 117 | * 从raw文件夹下读取文件到字节数组 118 | * 119 | * @param context 上下文 120 | * @param rawId raw资源id 121 | * @return 文件字节数组 122 | */ 123 | public static byte[] readBytesFromRaw(Context context, int rawId) { 124 | InputStream is = null; 125 | byte[] buffer = null; 126 | try { 127 | is = context.getResources().openRawResource(rawId); 128 | int size = is.available(); 129 | buffer = new byte[size]; 130 | is.read(buffer); 131 | } catch (IOException e) { 132 | e.printStackTrace(); 133 | } finally { 134 | if (is != null) { 135 | try { 136 | is.close(); 137 | is = null; 138 | } catch (IOException e) { 139 | e.printStackTrace(); 140 | } 141 | } 142 | } 143 | return buffer; 144 | } 145 | 146 | /** 147 | * 读取raw目录的文件内容 148 | * 149 | * @param context 内容上下文 150 | * @param rawFileId raw文件名id 151 | * @return 152 | */ 153 | public static String readRawValue(Context context, int rawFileId) { 154 | String result = ""; 155 | try { 156 | InputStream is = context.getResources().openRawResource(rawFileId); 157 | int len = is.available(); 158 | byte[] buffer = new byte[len]; 159 | is.read(buffer); 160 | result = new String(buffer, "UTF-8"); 161 | is.close(); 162 | } catch (Exception e) { 163 | e.printStackTrace(); 164 | } 165 | return result; 166 | } 167 | 168 | /** 169 | * 获取 layout 布局文件 170 | * 171 | * @param context Context 172 | * @param resName layout xml 的文件名 173 | * @return layout 174 | */ 175 | public static int getLayoutId(Context context, String resName) { 176 | return context.getResources().getIdentifier(resName, "layout", 177 | context.getPackageName()); 178 | } 179 | 180 | /** 181 | * 获取 string 值 182 | * 183 | * @param context Context 184 | * @param resName string name的名称 185 | * @return string 186 | */ 187 | public static int getStringId(Context context, String resName) { 188 | return context.getResources().getIdentifier(resName, "string", 189 | context.getPackageName()); 190 | } 191 | 192 | /** 193 | * 获取 drawable 194 | * 195 | * @param context Context 196 | * @param resName drawable 的名称 197 | * @return drawable 198 | */ 199 | public static int getDrawableId(Context context, String resName) { 200 | return context.getResources().getIdentifier(resName, 201 | "drawable", context.getPackageName()); 202 | } 203 | 204 | /** 205 | * 获取 mipmap 206 | * 207 | * @param context 208 | * @param resName 209 | * @return 210 | */ 211 | public static int getMipmapId(Context context, String resName) { 212 | return context.getResources().getIdentifier(resName, 213 | "mipmap", context.getPackageName()); 214 | } 215 | 216 | 217 | /** 218 | * 获取 style 219 | * 220 | * @param context Context 221 | * @param resName style的名称 222 | * @return style 223 | */ 224 | public static int getStyleId(Context context, String resName) { 225 | return context.getResources().getIdentifier(resName, "style", 226 | context.getPackageName()); 227 | } 228 | 229 | /** 230 | * 获取 styleable 231 | * 232 | * @param context Context 233 | * @param resName styleable 的名称 234 | * @return styleable 235 | */ 236 | public static Object getStyleableId(Context context, String resName) { 237 | return context.getResources().getIdentifier(resName, "styleable", 238 | context.getPackageName()); 239 | } 240 | 241 | 242 | /** 243 | * 获取 anim 244 | * 245 | * @param context Context 246 | * @param resName anim xml 文件名称 247 | * @return anim 248 | */ 249 | public static int getAnimId(Context context, String resName) { 250 | return context.getResources().getIdentifier(resName, "anim", 251 | context.getPackageName()); 252 | } 253 | 254 | /** 255 | * 获取 id 256 | * 257 | * @param context Context 258 | * @param resName id 的名称 259 | * @return 260 | */ 261 | public static int getId(Context context, String resName) { 262 | return context.getResources().getIdentifier(resName, "id", 263 | context.getPackageName()); 264 | } 265 | 266 | /** 267 | * color 268 | * 269 | * @param context Context 270 | * @param resName color 名称 271 | * @return 272 | */ 273 | public static int getColorId(Context context, String resName) { 274 | return context.getResources().getIdentifier(resName, "color", 275 | context.getPackageName()); 276 | } 277 | 278 | 279 | /** 280 | * 获取Manifest Meta Data 281 | * 282 | * @param context 283 | * @param metaKey 284 | * @return 285 | */ 286 | public static String getMetaData(Context context, String metaKey) { 287 | String name = context.getPackageName(); 288 | ApplicationInfo appInfo; 289 | String msg = ""; 290 | try { 291 | appInfo = context.getPackageManager().getApplicationInfo(name, 292 | PackageManager.GET_META_DATA); 293 | msg = appInfo.metaData.getString(metaKey); 294 | } catch (PackageManager.NameNotFoundException e) { 295 | e.printStackTrace(); 296 | } 297 | 298 | if (StringUtils.isEmpty(msg)) { 299 | return ""; 300 | } 301 | 302 | return msg; 303 | } 304 | 305 | /** 306 | * 获得渠道号 307 | * 308 | * @param context 309 | * @param channelKey 310 | * @return 311 | */ 312 | public static String getChannelNo(Context context, String channelKey) { 313 | return getMetaData(context, channelKey); 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/io/SDCardUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.io; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.InputStreamReader; 9 | import java.util.ArrayList; 10 | 11 | import xyz.yhsj.yhutils.logutils.LogUtils; 12 | 13 | import android.content.Context; 14 | import android.os.Environment; 15 | import android.os.StatFs; 16 | 17 | 18 | /** 19 | * 内存卡 工具类
20 | */ 21 | public class SDCardUtils { 22 | 23 | /** 24 | * 判断SDCard是否可用 25 | */ 26 | public static boolean isSDCardEnable() { 27 | boolean result = Environment.getExternalStorageState().equals( 28 | Environment.MEDIA_MOUNTED); 29 | if (result) 30 | LogUtils.i("当前内存卡有效"); 31 | else 32 | LogUtils.i("当前内存卡无效"); 33 | 34 | return result; 35 | 36 | } 37 | 38 | 39 | /** 40 | * 获取SD卡路径 41 | */ 42 | public static ArrayList getSDCardPathEx() { 43 | ArrayList list = new ArrayList(); 44 | try { 45 | Runtime runtime = Runtime.getRuntime(); 46 | Process proc = runtime.exec("mount"); 47 | InputStream is = proc.getInputStream(); 48 | InputStreamReader isr = new InputStreamReader(is); 49 | String line; 50 | BufferedReader br = new BufferedReader(isr); 51 | while ((line = br.readLine()) != null) { 52 | if (line.contains("secure")) { 53 | continue; 54 | } 55 | if (line.contains("asec")) { 56 | continue; 57 | } 58 | 59 | if (line.contains("fat")) { 60 | String columns[] = line.split(" "); 61 | if (columns.length > 1) { 62 | list.add("*" + columns[1]); 63 | } 64 | } else if (line.contains("fuse")) { 65 | String columns[] = line.split(" "); 66 | if (columns.length > 1) { 67 | list.add(columns[1]); 68 | } 69 | } 70 | } 71 | } catch (FileNotFoundException e) { 72 | e.printStackTrace(); 73 | } catch (IOException e) { 74 | e.printStackTrace(); 75 | } 76 | return list; 77 | } 78 | 79 | /** 80 | * 获取外部存储设备的总空间大小 81 | */ 82 | public static long getSDCardTotalSize(Context context) { 83 | if (isSDCardEnable()) { 84 | // 得到一个外部存储设备的目录/通过getPath得到路径 85 | File path = Environment.getExternalStorageDirectory(); 86 | // 文件系统的帮助类,传入一个路径可以得到路径的信息 87 | StatFs stat = new StatFs(path.getPath()); 88 | // 得到该存储空间每一块存储空间的大小 89 | long blockSize = stat.getBlockSize(); 90 | // 得到空间总个数 91 | long totalBlocks = stat.getBlockCount(); 92 | 93 | // 得到总空间大小 94 | long totalSize = totalBlocks * blockSize; 95 | 96 | // String totalStr = Formatter.formatFileSize(context, totalSize); 97 | 98 | return totalSize; 99 | } 100 | return 0; 101 | } 102 | 103 | /** 104 | * 获取外部存储设备的剩余空间大小 105 | */ 106 | public static long getSDCardAvailSize(Context context) { 107 | if (isSDCardEnable()) { 108 | // 得到一个外部存储设备的目录/通过getPath得到路径 109 | File path = Environment.getExternalStorageDirectory(); 110 | // 文件系统的帮助类,传入一个路径可以得到路径的信息 111 | StatFs stat = new StatFs(path.getPath()); 112 | // 得到该存储空间每一块存储空间的大小 113 | long blockSize = stat.getBlockSize(); 114 | // 得到可用的空间个数 115 | long availableBlocks = stat.getAvailableBlocks(); 116 | // 得到可用空间大小 117 | long availSize = availableBlocks * blockSize; 118 | // String availStr = Formatter.formatFileSize(context, availSize); 119 | return availSize; 120 | } 121 | return 0; 122 | } 123 | 124 | /** 125 | * 获取内部存储设备的总空间大小 126 | * 127 | * @param context 128 | * @return 129 | */ 130 | public static long getRomSpaceTotalSize(Context context) { 131 | if (isSDCardEnable()) { 132 | // 得到一个内部存储设备的目录/通过getPath得到路径 133 | File path = Environment.getDataDirectory(); 134 | // 文件系统的帮助类,传入一个路径可以得到路径的信息 135 | StatFs stat = new StatFs(path.getPath()); 136 | // 得到该存储空间每一块存储空间的大小 137 | long blockSize = stat.getBlockSize(); 138 | // 得到空间总个数 139 | long totalBlocks = stat.getBlockCount(); 140 | // 得到总空间大小 141 | long totalSize = totalBlocks * blockSize; 142 | 143 | // String totalStr = Formatter.formatFileSize(context, totalSize); 144 | 145 | return totalSize; 146 | } 147 | return 0; 148 | } 149 | 150 | /** 151 | * 获取内部存储设备的剩余空间大小 152 | * 153 | * @param context 154 | * @return 155 | */ 156 | public static long getRomSpaceAvailSize(Context context) { 157 | if (isSDCardEnable()) { 158 | // 得到一个内部存储设备的目录/通过getPath得到路径 159 | File path = Environment.getDataDirectory(); 160 | // 文件系统的帮助类,传入一个路径可以得到路径的信息 161 | StatFs stat = new StatFs(path.getPath()); 162 | // 得到该存储空间每一块存储空间的大小 163 | long blockSize = stat.getBlockSize(); 164 | // 得到可用的空间个数 165 | long availableBlocks = stat.getAvailableBlocks(); 166 | // 得到可用空间大小 167 | long availSize = availableBlocks * blockSize; 168 | 169 | // String availStr = Formatter.formatFileSize(context, availSize); 170 | return availSize; 171 | } 172 | return 0; 173 | } 174 | 175 | /** 176 | * 获取系统存储路径 177 | * 178 | * @return 179 | */ 180 | public static String getRootDirectoryPath() { 181 | String path = Environment.getRootDirectory().getAbsolutePath(); 182 | LogUtils.i("当前存储路径:" + path); 183 | return path; 184 | } 185 | 186 | /** 187 | * 判断SDCard是否已满 188 | * 189 | * @return 190 | */ 191 | @SuppressWarnings({"deprecation", "unused"}) 192 | public static boolean isSDCardSizeOverflow() { 193 | boolean result = false; 194 | // 取得SDCard当前的状态 195 | String sDcString = Environment.getExternalStorageState(); 196 | 197 | if (sDcString.equals(Environment.MEDIA_MOUNTED)) { 198 | 199 | // 取得sdcard文件路径 200 | File pathFile = Environment 201 | .getExternalStorageDirectory(); 202 | StatFs statfs = new StatFs(pathFile.getPath()); 203 | 204 | // 获取SDCard上BLOCK总数 205 | long nTotalBlocks = statfs.getBlockCount(); 206 | 207 | // 获取SDCard上每个block的SIZE 208 | long nBlocSize = statfs.getBlockSize(); 209 | 210 | // 获取可供程序使用的Block的数量 211 | long nAvailaBlock = statfs.getAvailableBlocks(); 212 | 213 | // 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块) 214 | long nFreeBlock = statfs.getFreeBlocks(); 215 | 216 | // 计算SDCard 总容量大小MB 217 | long nSDTotalSize = nTotalBlocks * nBlocSize / 1024 / 1024; 218 | 219 | // 计算 SDCard 剩余大小MB 220 | long nSDFreeSize = nAvailaBlock * nBlocSize / 1024 / 1024; 221 | if (nSDFreeSize <= 1) { 222 | result = true; 223 | } 224 | }// end of if 225 | // end of func 226 | return result; 227 | } 228 | 229 | } 230 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/keyboard/KeyBoardUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.keyboard; 2 | 3 | import android.content.Context; 4 | import android.view.inputmethod.InputMethodManager; 5 | import android.widget.EditText; 6 | 7 | /** 8 | * 软键盘工具类 9 | */ 10 | public class KeyBoardUtils { 11 | /** 12 | * 打开软键盘 13 | * 14 | * @param mEditText 输入框(好像关系不大) 15 | * @param mContext 上下文 16 | */ 17 | public static void openKeybord(EditText mEditText, Context mContext) { 18 | InputMethodManager imm = (InputMethodManager) mContext 19 | .getSystemService(Context.INPUT_METHOD_SERVICE); 20 | imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN); 21 | imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 22 | InputMethodManager.HIDE_IMPLICIT_ONLY); 23 | } 24 | 25 | /** 26 | * 关闭软键盘 27 | * 28 | * @param mEditText 输入框(好像关系不大) 29 | * @param mContext 上下文 30 | */ 31 | public static void closeKeybord(EditText mEditText, Context mContext) { 32 | InputMethodManager imm = (InputMethodManager) mContext 33 | .getSystemService(Context.INPUT_METHOD_SERVICE); 34 | imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/logutils/LogType.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.logutils; 2 | 3 | /** 4 | * Created by pengwei08 on 2015/7/20. 5 | * 日志类型 6 | */ 7 | public enum LogType { 8 | Verbose, Debug, Info, Warn, Error, Wtf 9 | } 10 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/logutils/LogUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.logutils; 2 | 3 | import xyz.yhsj.yhutils.logutils.utils.SystemUtil; 4 | 5 | /** 6 | * Created by pengwei08 on 2015/7/16. 日志管理器 7 | */ 8 | public final class LogUtils { 9 | 10 | private static Logger logger; 11 | static { 12 | logger = new Logger(); 13 | } 14 | 15 | /** 允许输出日志 */ 16 | public static boolean configAllowLog = true; 17 | 18 | /** 配置日志Tag前缀 */ 19 | public static String configTagPrefix = ""; 20 | 21 | /** 22 | * verbose输出 23 | * 24 | * @param msg 25 | * @param args 26 | */ 27 | public static void v(String msg, Object... args) { 28 | logger.v(SystemUtil.getStackTrace(), msg, args); 29 | } 30 | 31 | public static void v(Object object) { 32 | logger.v(SystemUtil.getStackTrace(), object); 33 | } 34 | 35 | /** 36 | * debug输出 37 | * 38 | * @param msg 39 | * @param args 40 | */ 41 | public static void d(String msg, Object... args) { 42 | logger.d(SystemUtil.getStackTrace(), msg, args); 43 | } 44 | 45 | public static void d(Object object) { 46 | logger.d(SystemUtil.getStackTrace(), object); 47 | } 48 | 49 | /** 50 | * info输出 51 | * 52 | * @param msg 53 | * @param args 54 | */ 55 | public static void i(String msg, Object... args) { 56 | logger.i(SystemUtil.getStackTrace(), msg, args); 57 | } 58 | 59 | public static void i(Object object) { 60 | logger.i(SystemUtil.getStackTrace(), object); 61 | } 62 | 63 | /** 64 | * warn输出 65 | * 66 | * @param msg 67 | * @param args 68 | */ 69 | public static void w(String msg, Object... args) { 70 | logger.w(SystemUtil.getStackTrace(), msg, args); 71 | } 72 | 73 | public static void w(Object object) { 74 | logger.w(SystemUtil.getStackTrace(), object); 75 | } 76 | 77 | /** 78 | * error输出 79 | * 80 | * @param msg 81 | * @param args 82 | */ 83 | public static void e(String msg, Object... args) { 84 | logger.e(SystemUtil.getStackTrace(), msg, args); 85 | } 86 | 87 | public static void e(Object object) { 88 | logger.e(SystemUtil.getStackTrace(), object); 89 | } 90 | 91 | /** 92 | * assert输出 93 | * 94 | * @param msg 95 | * @param args 96 | */ 97 | public static void wtf(String msg, Object... args) { 98 | logger.wtf(SystemUtil.getStackTrace(), msg, args); 99 | } 100 | 101 | public static void wtf(Object object) { 102 | logger.wtf(SystemUtil.getStackTrace(), object); 103 | } 104 | 105 | /** 106 | * 打印json 107 | * 108 | * @param json 109 | */ 110 | public static void json(String json) { 111 | logger.json(SystemUtil.getStackTrace(), json); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/logutils/Logger.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.logutils; 2 | 3 | import static xyz.yhsj.yhutils.logutils.LogUtils.configTagPrefix; 4 | 5 | import java.util.Collection; 6 | import java.util.Iterator; 7 | import java.util.Map; 8 | import java.util.MissingFormatArgumentException; 9 | import java.util.Set; 10 | 11 | import org.json.JSONArray; 12 | import org.json.JSONException; 13 | import org.json.JSONObject; 14 | 15 | import xyz.yhsj.yhutils.logutils.utils.ArrayUtil; 16 | import xyz.yhsj.yhutils.logutils.utils.SystemUtil; 17 | import android.app.AlertDialog; 18 | import android.content.ClipboardManager; 19 | import android.content.Context; 20 | import android.content.DialogInterface; 21 | import android.text.TextUtils; 22 | import android.util.Log; 23 | import android.util.Pair; 24 | import android.widget.Toast; 25 | 26 | /** 27 | * Created by pengwei08 on 2015/7/20. 28 | */ 29 | public final class Logger implements Printer { 30 | 31 | protected Logger() { 32 | } 33 | 34 | private AlertDialog dialog; 35 | 36 | /** 37 | * 打印字符串 38 | * 39 | * @param type 40 | * @param element 41 | * @param msg 42 | * @param args 43 | */ 44 | private void logString(LogType type, StackTraceElement element, String msg, 45 | Object... args) { 46 | if (!LogUtils.configAllowLog) { 47 | return; 48 | } 49 | String tag = generateTag(element); 50 | msg = String.format(msg, args); 51 | switch (type) { 52 | case Verbose: 53 | Log.v(tag, msg); 54 | break; 55 | case Debug: 56 | Log.d(tag, msg); 57 | break; 58 | case Info: 59 | Log.i(tag, msg); 60 | break; 61 | case Warn: 62 | Log.w(tag, msg); 63 | break; 64 | case Error: 65 | Log.e(tag, msg); 66 | break; 67 | case Wtf: 68 | Log.wtf(tag, msg); 69 | break; 70 | default: 71 | break; 72 | } 73 | } 74 | 75 | /** 76 | * 打印对象 77 | * 78 | * @param type 79 | * @param element 80 | * @param object 81 | */ 82 | private void logObject(LogType type, StackTraceElement element, 83 | Object object) { 84 | if (object != null) { 85 | final String simpleName = object.getClass().getSimpleName(); 86 | if (object instanceof Throwable) { 87 | String tag = generateTag(element); 88 | String msg = object.toString(); 89 | Exception exception = (Exception) object; 90 | switch (type) { 91 | case Verbose: 92 | Log.v(tag, msg, exception); 93 | break; 94 | case Debug: 95 | Log.d(tag, msg, exception); 96 | break; 97 | case Info: 98 | Log.i(tag, msg, exception); 99 | break; 100 | case Warn: 101 | Log.w(tag, msg, exception); 102 | break; 103 | case Error: 104 | Log.e(tag, msg, exception); 105 | break; 106 | case Wtf: 107 | Log.wtf(tag, msg, exception); 108 | break; 109 | default: 110 | break; 111 | } 112 | } else if (object instanceof String) { 113 | try { 114 | logString(type, element, (String) object); 115 | } catch (MissingFormatArgumentException e) { 116 | e(element, e); 117 | } 118 | } else if (object.getClass().isArray()) { 119 | String msg = "Temporarily not support more than two dimensional Array!"; 120 | int dim = ArrayUtil.getArrayDimension(object); 121 | switch (dim) { 122 | case 1: 123 | Pair pair = ArrayUtil.arrayToString(object); 124 | msg = simpleName.replace("[]", "[" + pair.first + "] {\n"); 125 | msg += pair.second + "\n"; 126 | break; 127 | case 2: 128 | Pair pair1 = ArrayUtil.arrayToObject(object); 129 | Pair pair2 = (Pair) pair1.first; 130 | msg = simpleName.replace("[][]", "[" + pair2.first + "][" 131 | + pair2.second + "] {\n"); 132 | msg += pair1.second + "\n"; 133 | break; 134 | default: 135 | break; 136 | } 137 | logString(type, element, msg + "}"); 138 | } else if (object instanceof Collection) { 139 | Collection collection = (Collection) object; 140 | String msg = "%s size = %d [\n"; 141 | msg = String.format(msg, simpleName, collection.size()); 142 | if (!collection.isEmpty()) { 143 | Iterator iterator = collection.iterator(); 144 | int flag = 0; 145 | while (iterator.hasNext()) { 146 | String itemString = "[%d]:%s%s"; 147 | Object item = iterator.next(); 148 | msg += String.format(itemString, flag, 149 | SystemUtil.objectToString(item), 150 | flag++ < collection.size() - 1 ? ",\n" : "\n"); 151 | } 152 | } 153 | logString(type, element, msg + "\n]"); 154 | } else if (object instanceof Map) { 155 | String msg = simpleName + " [\n"; 156 | Map map = (Map) object; 157 | Set keys = map.keySet(); 158 | for (Object key : keys) { 159 | String itemString = "{%s : %s}\n"; 160 | Object value = map.get(key); 161 | msg += String.format(itemString, 162 | SystemUtil.objectToString(key), 163 | SystemUtil.objectToString(value)); 164 | } 165 | logString(type, element, msg + "]"); 166 | } else { 167 | logString(type, element, SystemUtil.objectToString(object)); 168 | } 169 | } else { 170 | logString(type, element, SystemUtil.objectToString(object)); 171 | } 172 | } 173 | 174 | /** 175 | * 自动生成tag 176 | * 177 | * @return 178 | */ 179 | private String generateTag(StackTraceElement caller) { 180 | String stackTrace = caller.toString(); 181 | stackTrace = stackTrace.substring(stackTrace.lastIndexOf('('), 182 | stackTrace.length()); 183 | String tag = "%s%s.%s%s"; 184 | String callerClazzName = caller.getClassName(); 185 | callerClazzName = callerClazzName.substring(callerClazzName 186 | .lastIndexOf(".") + 1); 187 | String Prefix = TextUtils.isEmpty(configTagPrefix) ? "" 188 | : configTagPrefix; 189 | tag = String.format(tag, Prefix, callerClazzName, 190 | caller.getMethodName(), stackTrace); 191 | return tag; 192 | } 193 | 194 | @Override 195 | public void d(StackTraceElement element, String message, Object... args) { 196 | logString(LogType.Debug, element, message, args); 197 | } 198 | 199 | @Override 200 | public void d(StackTraceElement element, Object object) { 201 | logObject(LogType.Debug, element, object); 202 | } 203 | 204 | @Override 205 | public void e(StackTraceElement element, String message, Object... args) { 206 | logString(LogType.Error, element, message, args); 207 | } 208 | 209 | @Override 210 | public void e(StackTraceElement element, Object object) { 211 | logObject(LogType.Error, element, object); 212 | } 213 | 214 | @Override 215 | public void w(StackTraceElement element, String message, Object... args) { 216 | logString(LogType.Warn, element, message, args); 217 | } 218 | 219 | @Override 220 | public void w(StackTraceElement element, Object object) { 221 | logObject(LogType.Warn, element, object); 222 | } 223 | 224 | @Override 225 | public void i(StackTraceElement element, String message, Object... args) { 226 | logString(LogType.Info, element, message, args); 227 | } 228 | 229 | @Override 230 | public void i(StackTraceElement element, Object object) { 231 | logObject(LogType.Info, element, object); 232 | } 233 | 234 | @Override 235 | public void v(StackTraceElement element, String message, Object... args) { 236 | logString(LogType.Verbose, element, message, args); 237 | } 238 | 239 | @Override 240 | public void v(StackTraceElement element, Object object) { 241 | logObject(LogType.Verbose, element, object); 242 | } 243 | 244 | @Override 245 | public void wtf(StackTraceElement element, String message, Object... args) { 246 | logString(LogType.Wtf, element, message, args); 247 | } 248 | 249 | @Override 250 | public void wtf(StackTraceElement element, Object object) { 251 | logObject(LogType.Wtf, element, object); 252 | } 253 | 254 | @Override 255 | public void json(StackTraceElement element, String json) { 256 | int indent = 4; 257 | if (TextUtils.isEmpty(json)) { 258 | d(element, "JSON{json is null}"); 259 | return; 260 | } 261 | try { 262 | if (json.startsWith("{")) { 263 | JSONObject jsonObject = new JSONObject(json); 264 | String msg = jsonObject.toString(indent); 265 | d(element, msg); 266 | } else if (json.startsWith("[")) { 267 | JSONArray jsonArray = new JSONArray(json); 268 | String msg = jsonArray.toString(indent); 269 | d(element, msg); 270 | } 271 | } catch (JSONException e) { 272 | e(element, e); 273 | } 274 | } 275 | 276 | /** 277 | * 弹出log信息 278 | * 279 | * @param context 280 | * @param object 281 | */ 282 | public void alert(final Context context, Object object) { 283 | if (!LogUtils.configAllowLog) { 284 | return; 285 | } 286 | if (null == dialog) { 287 | dialog = new AlertDialog.Builder(context) 288 | .setNegativeButton("复制", listener) 289 | .setPositiveButton("取消", listener).create(); 290 | 291 | } 292 | dialog.setMessage(SystemUtil.objectToString(object)); 293 | dialog.show(); 294 | } 295 | 296 | /** 297 | * dialog事件处理 298 | */ 299 | private DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { 300 | @Override 301 | public void onClick(DialogInterface dialogInterface, int which) { 302 | Context context = dialog.getContext(); 303 | switch (which) { 304 | case DialogInterface.BUTTON_NEGATIVE: 305 | ClipboardManager clip = (ClipboardManager) context 306 | .getSystemService(Context.CLIPBOARD_SERVICE); 307 | 308 | Toast.makeText(context, "已经复制到剪切板", Toast.LENGTH_SHORT).show(); 309 | break; 310 | case DialogInterface.BUTTON_POSITIVE: 311 | dialog.dismiss(); 312 | break; 313 | default: 314 | break; 315 | } 316 | } 317 | }; 318 | } 319 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/logutils/Printer.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.logutils; 2 | 3 | /** 4 | * Created by pengwei08 on 2015/7/20. 5 | */ 6 | public interface Printer { 7 | void d(StackTraceElement element, String message, Object... args); 8 | void d(StackTraceElement element, Object object); 9 | 10 | void e(StackTraceElement element, String message, Object... args); 11 | void e(StackTraceElement element, Object object); 12 | 13 | void w(StackTraceElement element, String message, Object... args); 14 | void w(StackTraceElement element, Object object); 15 | 16 | void i(StackTraceElement element, String message, Object... args); 17 | void i(StackTraceElement element, Object object); 18 | 19 | void v(StackTraceElement element, String message, Object... args); 20 | void v(StackTraceElement element, Object object); 21 | 22 | void wtf(StackTraceElement element, String message, Object... args); 23 | void wtf(StackTraceElement element, Object object); 24 | 25 | void json(StackTraceElement element, String json); 26 | } 27 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/logutils/utils/ArrayUtil.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.logutils.utils; 2 | 3 | import android.util.Pair; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Created by pengwei08 on 2015/7/25. 9 | * Thanks to zhutiantao for providing an array of analytical methods. 10 | */ 11 | public final class ArrayUtil { 12 | 13 | /** 14 | * 获取数组的纬度 15 | * 16 | * @param objects 17 | * 18 | * @return 19 | */ 20 | public static int getArrayDimension(Object objects) { 21 | int dim = 0; 22 | for (int i = 0; i < objects.toString().length(); ++i) { 23 | if (objects.toString().charAt(i) == '[') { 24 | ++dim; 25 | } else { 26 | break; 27 | } 28 | } 29 | return dim; 30 | } 31 | 32 | public static Pair, String> arrayToObject(Object object) { 33 | StringBuilder builder = new StringBuilder(); 34 | int cross = 0, vertical = 0; 35 | if (object instanceof int[][]) { 36 | int[][] ints = (int[][]) object; 37 | cross = ints.length; 38 | vertical = cross == 0 ? 0 : ints[0].length; 39 | for (int[] ints1 : ints) { 40 | builder.append(arrayToString(ints1).second + "\n"); 41 | } 42 | } else if (object instanceof byte[][]) { 43 | byte[][] ints = (byte[][]) object; 44 | cross = ints.length; 45 | vertical = cross == 0 ? 0 : ints[0].length; 46 | for (byte[] ints1 : ints) { 47 | builder.append(arrayToString(ints1).second + "\n"); 48 | } 49 | } else if (object instanceof short[][]) { 50 | short[][] ints = (short[][]) object; 51 | cross = ints.length; 52 | vertical = cross == 0 ? 0 : ints[0].length; 53 | for (short[] ints1 : ints) { 54 | builder.append(arrayToString(ints1).second + "\n"); 55 | } 56 | } else if (object instanceof long[][]) { 57 | long[][] ints = (long[][]) object; 58 | cross = ints.length; 59 | vertical = cross == 0 ? 0 : ints[0].length; 60 | for (long[] ints1 : ints) { 61 | builder.append(arrayToString(ints1).second + "\n"); 62 | } 63 | } else if (object instanceof float[][]) { 64 | float[][] ints = (float[][]) object; 65 | cross = ints.length; 66 | vertical = cross == 0 ? 0 : ints[0].length; 67 | for (float[] ints1 : ints) { 68 | builder.append(arrayToString(ints1).second + "\n"); 69 | } 70 | } else if (object instanceof double[][]) { 71 | double[][] ints = (double[][]) object; 72 | cross = ints.length; 73 | vertical = cross == 0 ? 0 : ints[0].length; 74 | for (double[] ints1 : ints) { 75 | builder.append(arrayToString(ints1).second + "\n"); 76 | } 77 | } else if (object instanceof boolean[][]) { 78 | boolean[][] ints = (boolean[][]) object; 79 | cross = ints.length; 80 | vertical = cross == 0 ? 0 : ints[0].length; 81 | for (boolean[] ints1 : ints) { 82 | builder.append(arrayToString(ints1).second + "\n"); 83 | } 84 | } else if (object instanceof char[][]) { 85 | char[][] ints = (char[][]) object; 86 | cross = ints.length; 87 | vertical = cross == 0 ? 0 : ints[0].length; 88 | for (char[] ints1 : ints) { 89 | builder.append(arrayToString(ints1).second + "\n"); 90 | } 91 | } else { 92 | Object[][] objects = (Object[][]) object; 93 | cross = objects.length; 94 | vertical = cross == 0 ? 0 : objects[0].length; 95 | for (Object[] objects1 : objects) { 96 | builder.append(arrayToString(objects1).second + "\n"); 97 | } 98 | } 99 | return Pair.create(Pair.create(cross, vertical), builder.toString()); 100 | } 101 | 102 | /** 103 | * 数组转化为字符串 104 | * 105 | * @param object 106 | * 107 | * @return 108 | */ 109 | public static Pair arrayToString(Object object) { 110 | StringBuilder builder = new StringBuilder("["); 111 | int length = 0; 112 | if (object instanceof int[]) { 113 | int[] ints = (int[]) object; 114 | length = ints.length; 115 | for (int i : ints) { 116 | builder.append(i + ",\t"); 117 | } 118 | } else if (object instanceof byte[]) { 119 | byte[] bytes = (byte[]) object; 120 | length = bytes.length; 121 | for (byte item : bytes) { 122 | builder.append(item + ",\t"); 123 | } 124 | } else if (object instanceof short[]) { 125 | short[] shorts = (short[]) object; 126 | length = shorts.length; 127 | for (short item : shorts) { 128 | builder.append(item + ",\t"); 129 | } 130 | } else if (object instanceof long[]) { 131 | long[] longs = (long[]) object; 132 | length = longs.length; 133 | for (long item : longs) { 134 | builder.append(item + ",\t"); 135 | } 136 | } else if (object instanceof float[]) { 137 | float[] floats = (float[]) object; 138 | length = floats.length; 139 | for (float item : floats) { 140 | builder.append(item + ",\t"); 141 | } 142 | } else if (object instanceof double[]) { 143 | double[] doubles = (double[]) object; 144 | length = doubles.length; 145 | for (double item : doubles) { 146 | builder.append(item + ",\t"); 147 | } 148 | } else if (object instanceof boolean[]) { 149 | boolean[] booleans = (boolean[]) object; 150 | length = booleans.length; 151 | for (boolean item : booleans) { 152 | builder.append(item + ",\t"); 153 | } 154 | } else if (object instanceof char[]) { 155 | char[] chars = (char[]) object; 156 | length = chars.length; 157 | for (char item : chars) { 158 | builder.append(item + ",\t"); 159 | } 160 | } else { 161 | Object[] objects = (Object[]) object; 162 | length = objects.length; 163 | for (Object item : objects) { 164 | builder.append(SystemUtil.objectToString(item) + ",\t"); 165 | } 166 | } 167 | return Pair.create(length, builder.replace(builder.length() - 2, builder.length(), "]").toString()); 168 | } 169 | 170 | /** 171 | * 是否为数组 172 | * 173 | * @param object 174 | * 175 | * @return 176 | */ 177 | public static boolean isArray(Object object) { 178 | return object.getClass().isArray(); 179 | } 180 | 181 | /** 182 | * 获取数组类型 183 | * 184 | * @param object 185 | * 如L为int型 186 | * @return 187 | */ 188 | public static char getType(Object object) { 189 | if(isArray(object)){ 190 | String str = object.toString(); 191 | return str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("[") + 2).charAt(0); 192 | } 193 | return 0; 194 | } 195 | 196 | /** 197 | * 遍历数组 198 | * 199 | * @param result 200 | * @param object 201 | */ 202 | private static void traverseArray(StringBuilder result, Object object) { 203 | if (!isArray(object)) { 204 | result.append(object.toString()); 205 | return; 206 | } 207 | if (getArrayDimension(object) == 1) { 208 | switch (getType(object)) { 209 | case 'I': 210 | result.append(Arrays.toString((int[]) object)).append("\n"); 211 | return; 212 | case 'D': 213 | result.append(Arrays.toString((double[]) object)).append("\n"); 214 | return; 215 | case 'Z': 216 | result.append(Arrays.toString((boolean[]) object)).append("\n"); 217 | return; 218 | case 'B': 219 | result.append(Arrays.toString((byte[]) object)).append("\n"); 220 | return; 221 | case 'S': 222 | result.append(Arrays.toString((short[]) object)).append("\n"); 223 | return; 224 | case 'J': 225 | result.append(Arrays.toString((long[]) object)).append("\n"); 226 | return; 227 | case 'F': 228 | result.append(Arrays.toString((float[]) object)).append("\n"); 229 | return; 230 | case 'L': 231 | result.append(Arrays.toString((Object[]) object)).append("\n"); 232 | default: 233 | return; 234 | } 235 | } 236 | for (int i = 0; i < ((Object[]) object).length; i++) { 237 | traverseArray(result, ((Object[]) object)[i]); 238 | } 239 | } 240 | 241 | public static String traverseArray(Object object) { 242 | StringBuilder result = new StringBuilder(); 243 | traverseArray(result, object); 244 | return result.toString(); 245 | } 246 | 247 | } 248 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/logutils/utils/SystemUtil.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.logutils.utils; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | /** 6 | * Created by pengwei08 on 2015/7/20. 7 | */ 8 | public class SystemUtil { 9 | /** 10 | * 获取StackTraceElement对象 11 | * @return 12 | */ 13 | public static StackTraceElement getStackTrace(){ 14 | return Thread.currentThread().getStackTrace()[4]; 15 | } 16 | 17 | 18 | // 基本数据类型 19 | private final static String[] types = {"int", "java.lang.String", "boolean", "char", 20 | "float", "double", "long", "short", "byte"}; 21 | 22 | /** 23 | * 将对象转化为String 24 | * 25 | * @param object 26 | * @return 27 | */ 28 | public static String objectToString(T object) { 29 | if (object == null) { 30 | return "Object{object is null}"; 31 | } 32 | if (object.toString().startsWith(object.getClass().getName() + "@")) { 33 | StringBuilder builder = new StringBuilder(object.getClass().getSimpleName() + "{"); 34 | Field[] fields = object.getClass().getDeclaredFields(); 35 | for (Field field : fields) { 36 | field.setAccessible(true); 37 | boolean flag = false; 38 | for (String type : types) { 39 | if (field.getType().getName().equalsIgnoreCase(type)) { 40 | flag = true; 41 | Object value = null; 42 | try { 43 | value = field.get(object); 44 | } catch (IllegalAccessException e) { 45 | value = e; 46 | }finally { 47 | builder.append(String.format("%s=%s, ", field.getName(), 48 | value == null ? "null" : value.toString())); 49 | break; 50 | } 51 | } 52 | } 53 | if(!flag){ 54 | builder.append(String.format("%s=%s, ", field.getName(), "Object")); 55 | } 56 | } 57 | return builder.replace(builder.length() - 2, builder.length() - 1, "}").toString(); 58 | } else { 59 | return object.toString(); 60 | } 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/notification/NotificationUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.notification; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.Activity; 5 | import android.app.Notification; 6 | import android.app.NotificationManager; 7 | import android.app.PendingIntent; 8 | import android.content.ComponentName; 9 | import android.content.Context; 10 | import android.content.Intent; 11 | import android.os.Bundle; 12 | 13 | public class NotificationUtils { 14 | 15 | /** 16 | * 发送不会重复的通知 17 | * 18 | * @param context 19 | * @param title 标题 20 | * @param message 消息 21 | * @param SmallIconId 图标 22 | * @param activity 要启动的类 23 | * @param extras 传递的参数 24 | */ 25 | @SuppressLint("NewApi") 26 | public static void sendNotification(Context context, String title, 27 | String message, int SmallIconId, Class activity, Bundle extras) { 28 | 29 | Intent mIntent = new Intent(context, activity); 30 | mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 31 | 32 | if (extras != null) { 33 | mIntent.putExtras(extras); 34 | } 35 | 36 | 37 | int requestCode = (int) System.currentTimeMillis(); 38 | 39 | PendingIntent mContentIntent = PendingIntent.getActivity(context, 40 | requestCode, mIntent, 0); 41 | 42 | Notification mNotification = new Notification.Builder(context) 43 | .setContentTitle(title).setSmallIcon(SmallIconId) 44 | .setContentIntent(mContentIntent).setContentText(message) 45 | .build(); 46 | mNotification.flags |= Notification.FLAG_AUTO_CANCEL; 47 | mNotification.defaults = Notification.DEFAULT_ALL; 48 | 49 | NotificationManager mNotificationManager = (NotificationManager) context 50 | .getSystemService(Context.NOTIFICATION_SERVICE); 51 | 52 | mNotificationManager.notify(requestCode, mNotification); 53 | } 54 | 55 | /** 56 | * 清除所有通知 57 | * 58 | * @param context 59 | */ 60 | public static void cancelNotification(Context context) { 61 | 62 | NotificationManager notificationManager = (NotificationManager) context 63 | .getSystemService(Context.NOTIFICATION_SERVICE); 64 | notificationManager.cancelAll(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/AppDataUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | 4 | import java.io.File; 5 | 6 | import android.content.Context; 7 | import android.os.Environment; 8 | 9 | /** 10 | * 本应用数据清除管理器 11 | * Created by clf on 15/10/17. 12 | */ 13 | public class AppDataUtils { 14 | /** 15 | * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) 16 | * 17 | * @param context 18 | */ 19 | public static void cleanInternalCache(Context context) { 20 | deleteFilesByDirectory(context.getCacheDir()); 21 | } 22 | 23 | 24 | /** 25 | * 获取内部缓存大小 26 | * @param context 27 | * @return 28 | */ 29 | public static long getInternalCacheSize(Context context){ 30 | return getFilesSize(context.getCacheDir()); 31 | } 32 | 33 | 34 | /** 35 | * 外部缓存大小 36 | * @param context 37 | * @return 38 | */ 39 | public static long getExternalCacheSize(Context context){ 40 | return getFilesSize(context.getExternalCacheDir()); 41 | } 42 | 43 | /** 44 | * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) 45 | * 46 | * @param context 47 | */ 48 | public static void cleanDatabases(Context context) { 49 | deleteFilesByDirectory(new File("/data/data/" 50 | + context.getPackageName() + "/databases")); 51 | } 52 | 53 | /** 54 | * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) 55 | * 56 | * @param context 57 | */ 58 | public static void cleanSharedPreference(Context context) { 59 | deleteFilesByDirectory(new File("/data/data/" 60 | + context.getPackageName() + "/shared_prefs")); 61 | } 62 | 63 | /** 64 | * 按名字清除本应用数据库 65 | * 66 | * @param context 67 | * @param dbName 68 | */ 69 | public static void cleanDatabaseByName(Context context, String dbName) { 70 | context.deleteDatabase(dbName); 71 | } 72 | 73 | /** 74 | * 清除/data/data/com.xxx.xxx/files下的内容 75 | * 76 | * @param context 77 | */ 78 | public static void cleanFiles(Context context) { 79 | deleteFilesByDirectory(context.getFilesDir()); 80 | } 81 | 82 | /** 83 | * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) 84 | * 85 | * @param context 86 | */ 87 | public static void cleanExternalCache(Context context) { 88 | if (Environment.getExternalStorageState().equals( 89 | Environment.MEDIA_MOUNTED)) { 90 | deleteFilesByDirectory(context.getExternalCacheDir()); 91 | } 92 | } 93 | 94 | /** 95 | * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 96 | * 97 | * @param filePath 98 | */ 99 | public static void cleanCustomCache(String filePath) { 100 | deleteFilesByDirectory(new File(filePath)); 101 | } 102 | 103 | /** 104 | * 清除本应用所有的数据 105 | * 106 | * @param context 107 | * @param filepath 108 | */ 109 | public static void cleanApplicationData(Context context, String... filepath) { 110 | cleanInternalCache(context); 111 | cleanExternalCache(context); 112 | cleanDatabases(context); 113 | cleanSharedPreference(context); 114 | cleanFiles(context); 115 | for (String filePath : filepath) { 116 | cleanCustomCache(filePath); 117 | } 118 | } 119 | 120 | /** 121 | * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 122 | * 123 | * @param directory 124 | */ 125 | private static void deleteFilesByDirectory(File directory) { 126 | if (directory != null && directory.exists() && directory.isDirectory()) { 127 | for (File item : directory.listFiles()) { 128 | item.delete(); 129 | } 130 | } 131 | } 132 | 133 | 134 | /** 135 | * 获得文件大小和文件夹下所有文件的大小 136 | * 137 | * @param mfile 138 | */ 139 | private static long getFilesSize(File mfile) { 140 | if (mfile != null && mfile.exists()) { 141 | if (mfile.isDirectory()) { 142 | int sum = 0; 143 | for (File item : mfile.listFiles()) { 144 | sum += getFilesSize(item); 145 | } 146 | return sum; 147 | } else { 148 | return mfile.length(); 149 | } 150 | } else { 151 | return 0l; 152 | } 153 | 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/AppUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.ComponentName; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.content.pm.ApplicationInfo; 8 | import android.content.pm.PackageInfo; 9 | import android.content.pm.PackageManager; 10 | import android.content.pm.PackageManager.NameNotFoundException; 11 | import android.content.pm.ResolveInfo; 12 | 13 | import java.util.ArrayList; 14 | import java.util.HashMap; 15 | import java.util.List; 16 | 17 | import xyz.yhsj.yhutils.logutils.LogUtils; 18 | 19 | /** 20 | * APP 工具类
21 | */ 22 | public class AppUtils { 23 | 24 | /** 25 | * 获得APP的名称 26 | * 27 | * @param context 28 | * @return 29 | */ 30 | public static String getAppName(Context context) { 31 | if (context == null) { 32 | return null; 33 | } 34 | try { 35 | PackageManager packageManager = context.getPackageManager(); 36 | PackageInfo packageInfo = packageManager.getPackageInfo( 37 | context.getPackageName(), 0); 38 | int labelRes = packageInfo.applicationInfo.labelRes; 39 | String appName = context.getResources().getString(labelRes); 40 | LogUtils.i("APP名字:" + appName); 41 | return appName; 42 | } catch (NameNotFoundException e) { 43 | e.printStackTrace(); 44 | } 45 | return null; 46 | } 47 | 48 | /** 49 | * need < uses-permission android:name =“android.permission.GET_TASKS” /> 50 | * 判断是否前台运行 51 | */ 52 | public static boolean isRunningForeground(Context context) { 53 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 54 | List taskList = am.getRunningTasks(1); 55 | if (taskList != null && !taskList.isEmpty()) { 56 | ComponentName componentName = taskList.get(0).topActivity; 57 | if (componentName != null && componentName.getPackageName().equals(context.getPackageName())) { 58 | return true; 59 | } 60 | } 61 | return false; 62 | } 63 | 64 | 65 | /** 66 | * 获取应用程序包名 67 | */ 68 | public static String getPackageName(Context context) { 69 | if (context == null) { 70 | LogUtils.e("getPackageName context为空"); 71 | return null; 72 | } 73 | String pkgName = context.getPackageName(); 74 | LogUtils.i("APP包名:" + pkgName); 75 | return pkgName; 76 | } 77 | 78 | 79 | /** 80 | * 启动APK的默认Activity 81 | * 82 | * @param activity 83 | * @param packageName 84 | */ 85 | public static void startApkActivity(final Context activity, 86 | String packageName) throws Exception { 87 | PackageManager pm = activity.getPackageManager(); 88 | PackageInfo pi; 89 | 90 | pi = pm.getPackageInfo(packageName, 0); 91 | Intent intent = new Intent(Intent.ACTION_MAIN, null); 92 | intent.addCategory(Intent.CATEGORY_LAUNCHER); 93 | intent.setPackage(pi.packageName); 94 | 95 | List apps = pm.queryIntentActivities(intent, 0); 96 | 97 | ResolveInfo ri = apps.iterator().next(); 98 | if (ri != null) { 99 | String className = ri.activityInfo.name; 100 | intent.setComponent(new ComponentName(packageName, className)); 101 | activity.startActivity(intent); 102 | } 103 | 104 | } 105 | 106 | /** 107 | * 获取应用程序下所有Activity 108 | * 109 | * @param activity 110 | * @return 111 | */ 112 | public static ArrayList getActivities(Context activity) { 113 | ArrayList result = new ArrayList(); 114 | Intent intent = new Intent(Intent.ACTION_MAIN, null); 115 | intent.setPackage(activity.getPackageName()); 116 | for (ResolveInfo info : activity.getPackageManager() 117 | .queryIntentActivities(intent, 0)) { 118 | result.add(info.activityInfo.name); 119 | } 120 | return result; 121 | } 122 | 123 | /** 124 | * 检查有没有应用程序来接受处理你发出的intent 125 | * 126 | * @param context 127 | * @param action 128 | * @return 129 | */ 130 | public static boolean isIntentAvailable(Context context, String action) { 131 | final PackageManager packageManager = context.getPackageManager(); 132 | final Intent intent = new Intent(action); 133 | List list = packageManager.queryIntentActivities(intent, 134 | PackageManager.MATCH_DEFAULT_ONLY); 135 | return list.size() > 0; 136 | } 137 | 138 | /** 139 | * 获取所有app的安装路径 140 | * 141 | * @param context 142 | * @return ArrayList> package:包名,url:地址 143 | */ 144 | public static ArrayList> getAllInstelAppUrl( 145 | Context context) { 146 | 147 | ArrayList> appInfos = new ArrayList>(); 148 | 149 | PackageManager pm = context.getPackageManager(); 150 | 151 | for (ApplicationInfo app : pm.getInstalledApplications(0)) { 152 | 153 | HashMap appInfo = new HashMap(); 154 | appInfo.put("package", app.packageName); 155 | appInfo.put("url", app.sourceDir); 156 | appInfos.add(appInfo); 157 | LogUtils.d("package: " + app.packageName + ", sourceDir: " 158 | + app.sourceDir); 159 | } 160 | 161 | return appInfos; 162 | } 163 | 164 | /** 165 | * 获取所有可启动app的包名 166 | * 167 | * @param context 168 | * @return ArrayList 包名 169 | */ 170 | public static ArrayList getAllCanStartApp(Context context) { 171 | 172 | ArrayList appInfos = new ArrayList(); 173 | 174 | PackageManager pm = context.getPackageManager(); 175 | 176 | Intent intent = new Intent(Intent.ACTION_MAIN); 177 | intent.addCategory(Intent.CATEGORY_LAUNCHER); 178 | 179 | for (ResolveInfo app : pm.queryIntentActivities(intent, 0)) { 180 | 181 | appInfos.add(app.activityInfo.packageName); 182 | 183 | LogUtils.d("name" + app.activityInfo.name + " package: " 184 | + app.activityInfo.packageName); 185 | } 186 | 187 | return appInfos; 188 | } 189 | 190 | 191 | } 192 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/CpuUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | 9 | /** 10 | * Created by clf on 15/9/22. 11 | */ 12 | public class CpuUtils { 13 | /** 14 | * 获取CPU最大频率(单位KHZ) 15 | * 16 | * @return 17 | */ 18 | public static String getMaxCpuFreq() { 19 | 20 | String result = ""; 21 | 22 | ProcessBuilder cmd; 23 | 24 | try { 25 | 26 | String[] args = { "/system/bin/cat", 27 | 28 | "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" }; 29 | 30 | cmd = new ProcessBuilder(args); 31 | 32 | Process process = cmd.start(); 33 | 34 | InputStream in = process.getInputStream(); 35 | 36 | byte[] re = new byte[24]; 37 | 38 | while (in.read(re) != -1) { 39 | 40 | result = result + new String(re); 41 | 42 | } 43 | 44 | in.close(); 45 | 46 | } catch (IOException ex) { 47 | 48 | ex.printStackTrace(); 49 | 50 | result = "N/A"; 51 | 52 | } 53 | 54 | return result.trim(); 55 | 56 | } 57 | 58 | /** 59 | * 获取CPU最小频率(单位KHZ) 60 | * 61 | * @return 62 | */ 63 | public static String getMinCpuFreq() { 64 | 65 | String result = ""; 66 | 67 | ProcessBuilder cmd; 68 | 69 | try { 70 | 71 | String[] args = { "/system/bin/cat", 72 | 73 | "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" }; 74 | 75 | cmd = new ProcessBuilder(args); 76 | 77 | Process process = cmd.start(); 78 | 79 | InputStream in = process.getInputStream(); 80 | 81 | byte[] re = new byte[24]; 82 | 83 | while (in.read(re) != -1) { 84 | 85 | result = result + new String(re); 86 | 87 | } 88 | 89 | in.close(); 90 | 91 | } catch (IOException ex) { 92 | 93 | ex.printStackTrace(); 94 | 95 | result = "N/A"; 96 | 97 | } 98 | 99 | return result.trim(); 100 | 101 | } 102 | 103 | /** 104 | * 实时获取CPU当前频率(单位KHZ) 105 | * 106 | * @return 107 | */ 108 | public static String getCurCpuFreq() { 109 | 110 | String result = "N/A"; 111 | 112 | try { 113 | 114 | FileReader fr = new FileReader( 115 | 116 | "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); 117 | 118 | BufferedReader br = new BufferedReader(fr); 119 | 120 | String text = br.readLine(); 121 | 122 | result = text.trim(); 123 | 124 | } catch (FileNotFoundException e) { 125 | 126 | e.printStackTrace(); 127 | 128 | } catch (IOException e) { 129 | 130 | e.printStackTrace(); 131 | 132 | } 133 | 134 | return result; 135 | 136 | } 137 | 138 | /** 139 | * 获取CPU名字 140 | * 141 | * @return 142 | */ 143 | public static String getCpuName() { 144 | 145 | try { 146 | 147 | FileReader fr = new FileReader("/proc/cpuinfo"); 148 | 149 | BufferedReader br = new BufferedReader(fr); 150 | 151 | String text = br.readLine(); 152 | 153 | String[] array = text.split(":\\s+", 2); 154 | 155 | for (int i = 0; i < array.length; i++) { 156 | 157 | } 158 | 159 | return array[1]; 160 | 161 | } catch (FileNotFoundException e) { 162 | 163 | e.printStackTrace(); 164 | 165 | } catch (IOException e) { 166 | 167 | e.printStackTrace(); 168 | 169 | } 170 | 171 | return null; 172 | 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/DeviceUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import android.content.Context; 4 | import android.content.pm.PackageInfo; 5 | import android.content.pm.PackageManager; 6 | import android.net.wifi.WifiInfo; 7 | import android.net.wifi.WifiManager; 8 | import android.os.SystemClock; 9 | import android.telephony.TelephonyManager; 10 | import android.text.TextUtils; 11 | 12 | import java.net.InetAddress; 13 | import java.net.NetworkInterface; 14 | import java.net.SocketException; 15 | import java.util.Enumeration; 16 | import java.util.Locale; 17 | 18 | import xyz.yhsj.yhutils.logutils.LogUtils; 19 | 20 | 21 | /** 22 | * 获取手机信息工具类
23 | * 需要"android.permission.READ_PHONE_STATE"权限 24 | */ 25 | public class DeviceUtils { 26 | 27 | 28 | /** 29 | * 获取本机语言 30 | * 31 | * @return 32 | */ 33 | public static String getLanguage() { 34 | Locale locale = Locale.getDefault(); 35 | String languageCode = locale.getLanguage(); 36 | if (TextUtils.isEmpty(languageCode)) { 37 | languageCode = ""; 38 | } 39 | return languageCode; 40 | } 41 | 42 | /** 43 | * 获取国家编号 44 | * 45 | * @return 46 | */ 47 | public static String getCountry() { 48 | Locale locale = Locale.getDefault(); 49 | String countryCode = locale.getCountry(); 50 | if (TextUtils.isEmpty(countryCode)) { 51 | countryCode = ""; 52 | } 53 | return countryCode; 54 | } 55 | 56 | /** 57 | * 获取App包 信息版本号 58 | * 59 | * @param context 60 | * @return 61 | */ 62 | public PackageInfo getAppInfo(Context context) { 63 | PackageManager packageManager = context.getPackageManager(); 64 | PackageInfo packageInfo = null; 65 | try { 66 | packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); 67 | } catch (PackageManager.NameNotFoundException e) { 68 | e.printStackTrace(); 69 | } 70 | return packageInfo; 71 | } 72 | 73 | /** 74 | * 获取手机的IMEI号 75 | */ 76 | public static String getIMEI(Context context) { 77 | if (context == null) { 78 | LogUtils.e("getIMEI context为空"); 79 | } 80 | TelephonyManager telecomManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 81 | String imei = telecomManager.getDeviceId(); 82 | LogUtils.i("IMEI标识:" + imei); 83 | return imei; 84 | } 85 | 86 | /** 87 | * 获取手机IESI号 88 | */ 89 | public static String getIESI(Context context) { 90 | if (context == null) { 91 | LogUtils.e("getIESI context为空"); 92 | } 93 | TelephonyManager telecomManager = (TelephonyManager) context 94 | .getSystemService(Context.TELEPHONY_SERVICE); 95 | String imsi = telecomManager.getSubscriberId(); 96 | LogUtils.i("IESI标识:" + imsi); 97 | return imsi; 98 | } 99 | 100 | /** 101 | * 获取手机号码 102 | */ 103 | public static String getTelNumber(Context context) { 104 | if (context == null) { 105 | LogUtils.e("getTelNumber context为空"); 106 | } 107 | TelephonyManager telecomManager = (TelephonyManager) context 108 | .getSystemService(Context.TELEPHONY_SERVICE); 109 | String numer = telecomManager.getLine1Number(); // 手机号码,有的可得,有的不可得 110 | LogUtils.i("手机号码:" + numer); 111 | return numer; 112 | } 113 | 114 | /** 115 | * 获取设备的系统版本号 116 | */ 117 | public static int getDeviceSDK() { 118 | int sdk = android.os.Build.VERSION.SDK_INT; 119 | LogUtils.i("设备版本:" + sdk); 120 | return sdk; 121 | } 122 | 123 | /** 124 | * 获取手机品牌 125 | */ 126 | public static String getBRAND() { 127 | String brand = android.os.Build.BRAND; 128 | LogUtils.i("手机品牌:" + brand); 129 | return brand; 130 | } 131 | 132 | /** 133 | * 获取设备的型号 134 | */ 135 | public static String getDeviceName() { 136 | String model = android.os.Build.MODEL; 137 | LogUtils.i("设备型号:" + model); 138 | return model; 139 | } 140 | 141 | 142 | /** 143 | * 获取本机IP地址 144 | * 145 | * @return 146 | */ 147 | public static String getLocalIPAddress() { 148 | 149 | try { 150 | for (Enumeration en = NetworkInterface 151 | .getNetworkInterfaces(); en.hasMoreElements(); ) { 152 | NetworkInterface intf = en.nextElement(); 153 | for (Enumeration enumIpAddr = intf 154 | .getInetAddresses(); enumIpAddr.hasMoreElements(); ) { 155 | InetAddress inetAddress = enumIpAddr.nextElement(); 156 | if (!inetAddress.isLoopbackAddress()) { 157 | return inetAddress.getHostAddress().toString(); 158 | } 159 | } 160 | } 161 | } catch (SocketException ex) { 162 | return "0.0.0.0"; 163 | } 164 | return "0.0.0.0"; 165 | } 166 | 167 | /** 168 | * 获取 MAC 地址 169 | * 170 | */ 171 | public static String getMacAddress(Context context) { 172 | //wifi mac地址 173 | WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 174 | WifiInfo info = wifi.getConnectionInfo(); 175 | String mac = info.getMacAddress(); 176 | 177 | return mac; 178 | } 179 | 180 | /** 181 | * 获取 开机时间 182 | */ 183 | public static String getBootTimeString() { 184 | long ut = SystemClock.elapsedRealtime() / 1000; 185 | int h = (int) ((ut / 3600)); 186 | int m = (int) ((ut / 60) % 60); 187 | 188 | return h + ":" + m; 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/LocationUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import android.app.PendingIntent; 4 | import android.app.PendingIntent.CanceledException; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.location.LocationManager; 8 | import android.net.Uri; 9 | import android.os.Build; 10 | import android.provider.Settings; 11 | 12 | public class LocationUtils { 13 | 14 | /** 15 | * 是否允许模拟定位 16 | * 17 | * @param context 18 | * @return 19 | */ 20 | public static boolean allow_mock_location(Context context) { 21 | 22 | boolean isOpen = Settings.Secure.getInt(context.getContentResolver(), 23 | Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0; 24 | return isOpen; 25 | 26 | } 27 | 28 | /** 29 | * 判断GPS是否打开 30 | * 31 | * @return 32 | */ 33 | public static boolean isGpsOPen(Context context) { 34 | LocationManager locationManager = (LocationManager) context 35 | .getSystemService(Context.LOCATION_SERVICE); 36 | // 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快) 37 | boolean isGpsOkay = locationManager 38 | .isProviderEnabled(LocationManager.GPS_PROVIDER); 39 | if (isGpsOkay) { 40 | return true; 41 | } else { 42 | return false; 43 | } 44 | } 45 | 46 | /** 47 | * 强制打开GPS 48 | * 49 | * @param context 50 | */ 51 | public static void forceOpenGPS(Context context) { 52 | // 4.0++ 53 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 54 | Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 55 | intent.putExtra("enabled", true); 56 | context.sendBroadcast(intent); 57 | 58 | String provider = Settings.Secure.getString( 59 | context.getContentResolver(), 60 | Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 61 | if (!provider.contains("gps")) { // if gps is disabled 62 | final Intent poke = new Intent(); 63 | poke.setClassName("com.android.settings", 64 | "com.android.settings.widget.SettingsAppWidgetProvider"); 65 | poke.addCategory(Intent.CATEGORY_ALTERNATIVE); 66 | poke.setData(Uri.parse("3")); 67 | context.sendBroadcast(poke); 68 | } 69 | } else { 70 | Intent GPSIntent = new Intent(); 71 | GPSIntent.setClassName("com.android.settings", 72 | "com.android.settings.widget.SettingsAppWidgetProvider"); 73 | GPSIntent.addCategory("android.intent.category.ALTERNATIVE"); 74 | GPSIntent.setData(Uri.parse("custom:3")); 75 | try { 76 | PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send(); 77 | } catch (CanceledException e) { 78 | } 79 | } 80 | } 81 | 82 | /** 83 | * 跳转到系统设置页面让用户自己打开GPS 84 | * 85 | * @param context 86 | */ 87 | public static void openGpsSetting(Context context) { 88 | try { 89 | context.startActivity(new Intent( 90 | Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 91 | } catch (Exception e) { 92 | context.startActivity(new Intent(Settings.ACTION_SETTINGS)); 93 | } 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/NetWorkUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import xyz.yhsj.yhutils.logutils.LogUtils; 4 | import android.app.Activity; 5 | import android.content.ComponentName; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.net.ConnectivityManager; 9 | import android.net.NetworkInfo; 10 | import android.telephony.TelephonyManager; 11 | 12 | /** 13 | * 网络 工具类
14 | * 需要android.permission.ACCESS_NETWORK_STATE 权限 15 | * 16 | * @author KEZHUANG 17 | * 18 | */ 19 | public class NetWorkUtils { 20 | 21 | /** 22 | * 判断网络是否连接 23 | * 24 | * @param context 25 | * @return 26 | */ 27 | public static boolean isConnected(Context context) { 28 | boolean bisConnFlag = false; 29 | 30 | ConnectivityManager connectivityManager = (ConnectivityManager) context 31 | .getSystemService(Context.CONNECTIVITY_SERVICE); 32 | 33 | NetworkInfo network = connectivityManager.getActiveNetworkInfo(); 34 | if (network != null) { 35 | bisConnFlag = connectivityManager.getActiveNetworkInfo() 36 | .isAvailable(); 37 | } 38 | return bisConnFlag; 39 | } 40 | 41 | /** 42 | * 判断是否是wifi连接 43 | */ 44 | public static boolean isWifi(Context context) { 45 | ConnectivityManager connectivityManager = (ConnectivityManager) context 46 | .getSystemService(Context.CONNECTIVITY_SERVICE); 47 | 48 | if (!isConnected(context)) { 49 | LogUtils.i("当前网络----->不可用"); 50 | return false; 51 | } 52 | boolean isWifi = connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; 53 | if (isWifi) 54 | LogUtils.i("当前网络----->WIFI环境"); 55 | else 56 | LogUtils.i("当前网络----->非WIFI环境"); 57 | 58 | return isWifi; 59 | 60 | } 61 | 62 | /** 63 | * 打开网络设置界面 64 | */ 65 | public static void openSetting(Activity activity) { 66 | Intent intent = null; 67 | // 判断手机系统的版本 即API大于10 就是3.0或以上版本 68 | if (android.os.Build.VERSION.SDK_INT > 10) { 69 | intent = new Intent( 70 | android.provider.Settings.ACTION_WIRELESS_SETTINGS); 71 | } else { 72 | intent = new Intent(); 73 | ComponentName component = new ComponentName("com.android.settings", 74 | "com.android.settings.WirelessSettings"); 75 | intent.setComponent(component); 76 | intent.setAction("android.intent.action.VIEW"); 77 | } 78 | activity.startActivity(intent); 79 | } 80 | 81 | /** 82 | * 获取网络类型名称 83 | * 84 | * @param context 85 | * @return 86 | */ 87 | public static String getNetworkTypeName(Context context) { 88 | if (context != null) { 89 | ConnectivityManager connectMgr = (ConnectivityManager) context 90 | .getSystemService(Context.CONNECTIVITY_SERVICE); 91 | if (connectMgr != null) { 92 | NetworkInfo info = connectMgr.getActiveNetworkInfo(); 93 | if (info != null) { 94 | switch (info.getType()) { 95 | case ConnectivityManager.TYPE_WIFI: 96 | return "WIFI"; 97 | case ConnectivityManager.TYPE_MOBILE: 98 | return getNetworkTypeName(info.getSubtype()); 99 | } 100 | } 101 | } 102 | } 103 | return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN); 104 | } 105 | 106 | private static String getNetworkTypeName(int type) { 107 | switch (type) { 108 | case TelephonyManager.NETWORK_TYPE_GPRS: 109 | return "GPRS"; 110 | case TelephonyManager.NETWORK_TYPE_EDGE: 111 | return "EDGE"; 112 | case TelephonyManager.NETWORK_TYPE_UMTS: 113 | return "UMTS"; 114 | case TelephonyManager.NETWORK_TYPE_HSDPA: 115 | return "HSDPA"; 116 | case TelephonyManager.NETWORK_TYPE_HSUPA: 117 | return "HSUPA"; 118 | case TelephonyManager.NETWORK_TYPE_HSPA: 119 | return "HSPA"; 120 | case TelephonyManager.NETWORK_TYPE_CDMA: 121 | return "CDMA"; 122 | case TelephonyManager.NETWORK_TYPE_EVDO_0: 123 | return "CDMA - EvDo rev. 0"; 124 | case TelephonyManager.NETWORK_TYPE_EVDO_A: 125 | return "CDMA - EvDo rev. A"; 126 | case TelephonyManager.NETWORK_TYPE_EVDO_B: 127 | return "CDMA - EvDo rev. B"; 128 | case TelephonyManager.NETWORK_TYPE_1xRTT: 129 | return "CDMA - 1xRTT"; 130 | case TelephonyManager.NETWORK_TYPE_LTE: 131 | return "LTE"; 132 | case TelephonyManager.NETWORK_TYPE_EHRPD: 133 | return "CDMA - eHRPD"; 134 | case TelephonyManager.NETWORK_TYPE_IDEN: 135 | return "iDEN"; 136 | case TelephonyManager.NETWORK_TYPE_HSPAP: 137 | return "HSPA+"; 138 | default: 139 | return "UNKNOWN"; 140 | } 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/NetWorkUtilsBroadcast.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.IntentFilter; 7 | import android.net.ConnectivityManager; 8 | 9 | /** 10 | * 用于实时监测网络变化的工具类,用广播用,使用时请注意注册广播和设置监听器 11 | * 12 | * Created by LOVE on 2015/5/5 005. 13 | */ 14 | public class NetWorkUtilsBroadcast { 15 | 16 | private static NetWorkUtilsBroadcast netWork_broadcast; 17 | 18 | private NetworkBroadcastReceiver networkBroadcastReceiver; 19 | 20 | private Context context; 21 | 22 | private OnNetChengeListener listener; 23 | 24 | private NetWorkUtilsBroadcast(Context context) { 25 | networkBroadcastReceiver = new NetworkBroadcastReceiver(); 26 | this.context = context; 27 | } 28 | 29 | /** 30 | * 得到单例对象 31 | * 32 | * @param context 33 | * @return 34 | */ 35 | public static synchronized NetWorkUtilsBroadcast getInstance(Context context) { 36 | if (netWork_broadcast == null) { 37 | netWork_broadcast = new NetWorkUtilsBroadcast(context); 38 | } 39 | return netWork_broadcast; 40 | } 41 | 42 | /** 43 | * 注册网络状态监听广播 44 | */ 45 | public void registerNetworkReceiver() { 46 | IntentFilter filter = new IntentFilter( 47 | ConnectivityManager.CONNECTIVITY_ACTION); 48 | context.registerReceiver(networkBroadcastReceiver, filter); 49 | } 50 | 51 | /** 52 | * 解除网络状态广播监听 53 | */ 54 | public void unRegisterNetworkReceiver() { 55 | context.unregisterReceiver(networkBroadcastReceiver); 56 | } 57 | 58 | /** 59 | * 设置网络状态变化监听器 60 | * 61 | * @param listener 62 | */ 63 | public void setListener(OnNetChengeListener listener) { 64 | this.listener = listener; 65 | } 66 | 67 | /** 68 | * 网络状态改变回调接口 69 | */ 70 | public static interface OnNetChengeListener { 71 | void OnNetChenged(String info); 72 | } 73 | 74 | /** 75 | * 网络监听广播 76 | */ 77 | class NetworkBroadcastReceiver extends BroadcastReceiver { 78 | 79 | @Override 80 | public void onReceive(Context context, Intent intent) { 81 | 82 | if (listener != null) { 83 | listener.OnNetChenged(NetWorkUtils.getNetworkTypeName(context)); 84 | } 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/NetWorkUtils_Broadcast.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.IntentFilter; 7 | import android.net.ConnectivityManager; 8 | 9 | /** 10 | * 用于实时监测网络变化的工具类,用广播用,使用时请注意注册广播和设置监听器 11 | * 12 | * Created by LOVE on 2015/5/5 005. 13 | */ 14 | public class NetWorkUtils_Broadcast { 15 | 16 | private static NetWorkUtils_Broadcast netWork_broadcast; 17 | 18 | private NetworkBroadcastReceiver networkBroadcastReceiver; 19 | 20 | private Context context; 21 | 22 | private OnNetChengeListener listener; 23 | 24 | private NetWorkUtils_Broadcast(Context context) { 25 | networkBroadcastReceiver = new NetworkBroadcastReceiver(); 26 | this.context = context; 27 | } 28 | 29 | /** 30 | * 得到单例对象 31 | * 32 | * @param context 33 | * @return 34 | */ 35 | public static synchronized NetWorkUtils_Broadcast getInstance(Context context) { 36 | if (netWork_broadcast == null) { 37 | netWork_broadcast = new NetWorkUtils_Broadcast(context); 38 | } 39 | return netWork_broadcast; 40 | } 41 | 42 | /** 43 | * 注册网络状态监听广播 44 | */ 45 | public void registerNetworkReceiver() { 46 | IntentFilter filter = new IntentFilter( 47 | ConnectivityManager.CONNECTIVITY_ACTION); 48 | context.registerReceiver(networkBroadcastReceiver, filter); 49 | } 50 | 51 | /** 52 | * 解除网络状态广播监听 53 | */ 54 | public void unRegisterNetworkReceiver() { 55 | context.unregisterReceiver(networkBroadcastReceiver); 56 | } 57 | 58 | /** 59 | * 设置网络状态变化监听器 60 | * 61 | * @param listener 62 | */ 63 | public void setListener(OnNetChengeListener listener) { 64 | this.listener = listener; 65 | } 66 | 67 | /** 68 | * 网络状态改变回调接口 69 | */ 70 | public static interface OnNetChengeListener { 71 | void OnNetChenged(String info); 72 | } 73 | 74 | /** 75 | * 网络监听广播 76 | */ 77 | class NetworkBroadcastReceiver extends BroadcastReceiver { 78 | 79 | @Override 80 | public void onReceive(Context context, Intent intent) { 81 | 82 | if (listener != null) { 83 | listener.OnNetChenged(NetWorkUtils.getNetworkTypeName(context)); 84 | } 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/ScreenUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import xyz.yhsj.yhutils.logutils.LogUtils; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.content.res.Configuration; 7 | import android.graphics.Bitmap; 8 | import android.graphics.Rect; 9 | import android.util.DisplayMetrics; 10 | import android.view.View; 11 | import android.view.WindowManager; 12 | 13 | /** 14 | * 屏幕 工具类
15 | * 16 | */ 17 | public class ScreenUtils { 18 | 19 | /** 20 | * 获得屏幕宽度 21 | * 22 | */ 23 | public static int getScreenWidth(Context context) { 24 | WindowManager wm = (WindowManager) context 25 | .getSystemService(Context.WINDOW_SERVICE); 26 | DisplayMetrics outMetrics = new DisplayMetrics(); 27 | wm.getDefaultDisplay().getMetrics(outMetrics); 28 | int width = outMetrics.widthPixels; 29 | LogUtils.i("当前屏幕宽度:" + width); 30 | return width; 31 | } 32 | 33 | /** 34 | * 获得屏幕高度 35 | */ 36 | public static int getScreenHeight(Context context) { 37 | WindowManager wm = (WindowManager) context 38 | .getSystemService(Context.WINDOW_SERVICE); 39 | DisplayMetrics outMetrics = new DisplayMetrics(); 40 | wm.getDefaultDisplay().getMetrics(outMetrics); 41 | int height = outMetrics.heightPixels; 42 | LogUtils.i("当前屏幕高度:" + height); 43 | return height; 44 | } 45 | 46 | /** 47 | * 获得状态栏的高度 48 | */ 49 | public static int getStatusHeight(Context context) { 50 | 51 | int statusHeight = -1; 52 | try { 53 | Class clazz = Class.forName("com.android.internal.R$dimen"); 54 | Object object = clazz.newInstance(); 55 | int height = Integer.parseInt(clazz.getField("status_bar_height") 56 | .get(object).toString()); 57 | statusHeight = context.getResources().getDimensionPixelSize(height); 58 | } catch (Exception e) { 59 | e.printStackTrace(); 60 | } 61 | LogUtils.i("当前状态栏高度:" + statusHeight); 62 | return statusHeight; 63 | } 64 | 65 | /** 66 | * 获取当前屏幕截图,包含状态栏 67 | */ 68 | public static Bitmap snapShotWithStatusBar(Activity activity) { 69 | View view = activity.getWindow().getDecorView(); 70 | view.setDrawingCacheEnabled(true); 71 | view.buildDrawingCache(); 72 | Bitmap bmp = view.getDrawingCache(); 73 | int width = getScreenWidth(activity); 74 | int height = getScreenHeight(activity); 75 | Bitmap bp = null; 76 | bp = Bitmap.createBitmap(bmp, 0, 0, width, height); 77 | view.destroyDrawingCache(); 78 | return bp; 79 | 80 | } 81 | 82 | /** 83 | * 获取当前屏幕截图,不包含状态栏 84 | */ 85 | public static Bitmap snapShotWithoutStatusBar(Activity activity) { 86 | View view = activity.getWindow().getDecorView(); 87 | view.setDrawingCacheEnabled(true); 88 | view.buildDrawingCache(); 89 | Bitmap bmp = view.getDrawingCache(); 90 | Rect frame = new Rect(); 91 | activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); 92 | int statusBarHeight = frame.top; 93 | 94 | int width = getScreenWidth(activity); 95 | int height = getScreenHeight(activity); 96 | Bitmap bp = null; 97 | bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height 98 | - statusBarHeight); 99 | view.destroyDrawingCache(); 100 | return bp; 101 | } 102 | 103 | /** 104 | * 精确获取屏幕尺寸(例如:3.5、4.0、5.0寸屏幕)(貌似不太准) 105 | * 106 | * @param ctx 107 | * @return 108 | */ 109 | public static double getScreenPhysicalSize(Activity activity) { 110 | DisplayMetrics dm = new DisplayMetrics(); 111 | activity.getWindowManager().getDefaultDisplay().getMetrics(dm); 112 | double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) 113 | + Math.pow(dm.heightPixels, 2)); 114 | return diagonalPixels / (160 * dm.density); 115 | } 116 | 117 | /** 118 | * 一般是7寸以上是平板 ,判断是否是平板(官方用法) 119 | * 120 | * @param context 121 | * @return 122 | */ 123 | public static boolean isTablet(Context context) { 124 | return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; 125 | } 126 | 127 | 128 | /** 129 | * 获取屏幕分辨率 130 | * 131 | * @return 132 | */ 133 | public static String getScreenRatio(Context context) { 134 | DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); 135 | return displayMetrics.widthPixels + "X" + displayMetrics.heightPixels; 136 | } 137 | 138 | /** 139 | * 获取屏幕密度 140 | * 141 | * @return 142 | */ 143 | public static String getScreenDensity(Context context) { 144 | DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); 145 | return displayMetrics.densityDpi + "DPI"; 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/phone/ShellUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.phone; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.DataOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStreamReader; 7 | import java.util.List; 8 | 9 | /** 10 | * ShellUtils 11 | *
    12 | * Check root 13 | *
  • {@link ShellUtils#checkRootPermission()}
  • 14 | *
15 | *
    16 | * Execte command 17 | *
  • {@link ShellUtils#execCommand(String, boolean)}
  • 18 | *
  • {@link ShellUtils#execCommand(String, boolean, boolean)}
  • 19 | *
  • {@link ShellUtils#execCommand(List, boolean)}
  • 20 | *
  • {@link ShellUtils#execCommand(List, boolean, boolean)}
  • 21 | *
  • {@link ShellUtils#execCommand(String[], boolean)}
  • 22 | *
  • {@link ShellUtils#execCommand(String[], boolean, boolean)}
  • 23 | *
24 | * 25 | * @author Trinea 2013-5-16 26 | */ 27 | public class ShellUtils { 28 | 29 | public static final String COMMAND_SU = "su"; 30 | public static final String COMMAND_SH = "sh"; 31 | public static final String COMMAND_EXIT = "exit\n"; 32 | public static final String COMMAND_LINE_END = "\n"; 33 | 34 | private ShellUtils() { 35 | throw new AssertionError(); 36 | } 37 | 38 | /** 39 | * check whether has root permission 40 | * 41 | * @return 42 | */ 43 | public static boolean checkRootPermission() { 44 | return execCommand("echo root", true, false).result == 0; 45 | } 46 | 47 | /** 48 | * execute shell command, default return result msg 49 | * 50 | * @param command command 51 | * @param isRoot whether need to run with root 52 | * @return 53 | * @see ShellUtils#execCommand(String[], boolean, boolean) 54 | */ 55 | public static CommandResult execCommand(String command, boolean isRoot) { 56 | return execCommand(new String[] {command}, isRoot, true); 57 | } 58 | 59 | /** 60 | * execute shell commands, default return result msg 61 | * 62 | * @param commands command list 63 | * @param isRoot whether need to run with root 64 | * @return 65 | * @see ShellUtils#execCommand(String[], boolean, boolean) 66 | */ 67 | public static CommandResult execCommand(List commands, boolean isRoot) { 68 | return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, true); 69 | } 70 | 71 | /** 72 | * execute shell commands, default return result msg 73 | * 74 | * @param commands command array 75 | * @param isRoot whether need to run with root 76 | * @return 77 | * @see ShellUtils#execCommand(String[], boolean, boolean) 78 | */ 79 | public static CommandResult execCommand(String[] commands, boolean isRoot) { 80 | return execCommand(commands, isRoot, true); 81 | } 82 | 83 | /** 84 | * execute shell command 85 | * 86 | * @param command command 87 | * @param isRoot whether need to run with root 88 | * @param isNeedResultMsg whether need result msg 89 | * @return 90 | * @see ShellUtils#execCommand(String[], boolean, boolean) 91 | */ 92 | public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) { 93 | return execCommand(new String[] {command}, isRoot, isNeedResultMsg); 94 | } 95 | 96 | /** 97 | * execute shell commands 98 | * 99 | * @param commands command list 100 | * @param isRoot whether need to run with root 101 | * @param isNeedResultMsg whether need result msg 102 | * @return 103 | * @see ShellUtils#execCommand(String[], boolean, boolean) 104 | */ 105 | public static CommandResult execCommand(List commands, boolean isRoot, boolean isNeedResultMsg) { 106 | return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg); 107 | } 108 | 109 | /** 110 | * execute shell commands 111 | * 112 | * @param commands command array 113 | * @param isRoot whether need to run with root 114 | * @param isNeedResultMsg whether need result msg 115 | * @return
    116 | *
  • if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and 117 | * {@link CommandResult#errorMsg} is null.
  • 118 | *
  • if {@link CommandResult#result} is -1, there maybe some excepiton.
  • 119 | *
120 | */ 121 | public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) { 122 | int result = -1; 123 | if (commands == null || commands.length == 0) { 124 | return new CommandResult(result, null, null); 125 | } 126 | 127 | Process process = null; 128 | BufferedReader successResult = null; 129 | BufferedReader errorResult = null; 130 | StringBuilder successMsg = null; 131 | StringBuilder errorMsg = null; 132 | 133 | DataOutputStream os = null; 134 | try { 135 | process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); 136 | os = new DataOutputStream(process.getOutputStream()); 137 | for (String command : commands) { 138 | if (command == null) { 139 | continue; 140 | } 141 | 142 | // donnot use os.writeBytes(commmand), avoid chinese charset error 143 | os.write(command.getBytes()); 144 | os.writeBytes(COMMAND_LINE_END); 145 | os.flush(); 146 | } 147 | os.writeBytes(COMMAND_EXIT); 148 | os.flush(); 149 | 150 | result = process.waitFor(); 151 | // get command result 152 | if (isNeedResultMsg) { 153 | successMsg = new StringBuilder(); 154 | errorMsg = new StringBuilder(); 155 | successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); 156 | errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); 157 | String s; 158 | while ((s = successResult.readLine()) != null) { 159 | successMsg.append(s); 160 | } 161 | while ((s = errorResult.readLine()) != null) { 162 | errorMsg.append(s); 163 | } 164 | } 165 | } catch (IOException e) { 166 | e.printStackTrace(); 167 | } catch (Exception e) { 168 | e.printStackTrace(); 169 | } finally { 170 | try { 171 | if (os != null) { 172 | os.close(); 173 | } 174 | if (successResult != null) { 175 | successResult.close(); 176 | } 177 | if (errorResult != null) { 178 | errorResult.close(); 179 | } 180 | } catch (IOException e) { 181 | e.printStackTrace(); 182 | } 183 | 184 | if (process != null) { 185 | process.destroy(); 186 | } 187 | } 188 | return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null 189 | : errorMsg.toString()); 190 | } 191 | 192 | /** 193 | * result of command 194 | *
    195 | *
  • {@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in 196 | * linux shell
  • 197 | *
  • {@link CommandResult#successMsg} means success message of command result
  • 198 | *
  • {@link CommandResult#errorMsg} means error message of command result
  • 199 | *
200 | * 201 | * @author Trinea 2013-5-16 202 | */ 203 | public static class CommandResult { 204 | 205 | /** result of command **/ 206 | public int result; 207 | /** success message of command result **/ 208 | public String successMsg; 209 | /** error message of command result **/ 210 | public String errorMsg; 211 | 212 | public CommandResult(int result) { 213 | this.result = result; 214 | } 215 | 216 | public CommandResult(int result, String successMsg, String errorMsg) { 217 | this.result = result; 218 | this.successMsg = successMsg; 219 | this.errorMsg = errorMsg; 220 | } 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/AESUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import android.util.Base64; 4 | 5 | import java.io.UnsupportedEncodingException; 6 | import java.security.GeneralSecurityException; 7 | import java.security.MessageDigest; 8 | import java.security.NoSuchAlgorithmException; 9 | 10 | import javax.crypto.Cipher; 11 | import javax.crypto.spec.IvParameterSpec; 12 | import javax.crypto.spec.SecretKeySpec; 13 | 14 | /** 15 | * Desction: 16 | * Author:pengjianbo 17 | * Date:15/11/7 下午7:44 18 | */ 19 | public final class AESUtils { 20 | 21 | //AESCoder-ObjC uses CBC and PKCS7Padding 22 | private static final String AES_MODE = "AES/CBC/PKCS7Padding"; 23 | private static final String CHARSET = "UTF-8"; 24 | 25 | //AESCoder-ObjC uses SHA-256 (and so a 256-bit key) 26 | private static final String HASH_ALGORITHM = "SHA-256"; 27 | 28 | //AESCoder-ObjC uses blank IV (not the best security, but the aim here is compatibility) 29 | private static final byte[] ivBytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 30 | 31 | /** 32 | * Generates SHA256 hash of the password which is used as key 33 | * 34 | * @param password used to generated key 35 | * @return SHA256 of the password 36 | */ 37 | private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { 38 | final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM); 39 | byte[] bytes = password.getBytes("UTF-8"); 40 | digest.update(bytes, 0, bytes.length); 41 | byte[] key = digest.digest(); 42 | 43 | SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); 44 | return secretKeySpec; 45 | } 46 | 47 | 48 | /** 49 | * Encrypt and encode message using 256-bit AES with key generated from password. 50 | * 51 | * 52 | * @param password used to generated key 53 | * @param message the thing you want to encrypt assumed String UTF-8 54 | * @return Base64 encoded CipherText 55 | * @throws GeneralSecurityException if problems occur during encryption 56 | */ 57 | public static String encrypt(final String password, String message) 58 | throws GeneralSecurityException { 59 | 60 | try { 61 | final SecretKeySpec key = generateKey(password); 62 | byte[] cipherText = encrypt(key, ivBytes, message.getBytes(CHARSET)); 63 | //NO_WRAP is important as was getting \n at the end 64 | String encoded = Base64.encodeToString(cipherText, Base64.NO_WRAP); 65 | return encoded; 66 | } catch (UnsupportedEncodingException e) { 67 | throw new GeneralSecurityException(e); 68 | } 69 | } 70 | 71 | 72 | /** 73 | * More flexible AES encrypt that doesn't encode 74 | * @param key AES key typically 128, 192 or 256 bit 75 | * @param iv Initiation Vector 76 | * @param message in bytes (assumed it's already been decoded) 77 | * @return Encrypted cipher text (not encoded) 78 | * @throws GeneralSecurityException if something goes wrong during encryption 79 | */ 80 | public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message) 81 | throws GeneralSecurityException { 82 | final Cipher cipher = Cipher.getInstance(AES_MODE); 83 | IvParameterSpec ivSpec = new IvParameterSpec(iv); 84 | cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); 85 | byte[] cipherText = cipher.doFinal(message); 86 | 87 | return cipherText; 88 | } 89 | 90 | 91 | /** 92 | * Decrypt and decode ciphertext using 256-bit AES with key generated from password 93 | * 94 | * @param password used to generated key 95 | * @param base64EncodedCipherText the encrpyted message encoded with base64 96 | * @return message in Plain text (String UTF-8) 97 | * @throws GeneralSecurityException if there's an issue decrypting 98 | */ 99 | public static String decrypt(final String password, String base64EncodedCipherText) 100 | throws GeneralSecurityException { 101 | 102 | try { 103 | final SecretKeySpec key = generateKey(password); 104 | byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP); 105 | byte[] decryptedBytes = decrypt(key, ivBytes, decodedCipherText); 106 | String message = new String(decryptedBytes, CHARSET); 107 | return message; 108 | } catch (UnsupportedEncodingException e) { 109 | throw new GeneralSecurityException(e); 110 | } 111 | } 112 | 113 | 114 | /** 115 | * More flexible AES decrypt that doesn't encode 116 | * 117 | * @param key AES key typically 128, 192 or 256 bit 118 | * @param iv Initiation Vector 119 | * @param decodedCipherText in bytes (assumed it's already been decoded) 120 | * @return Decrypted message cipher text (not encoded) 121 | * @throws GeneralSecurityException if something goes wrong during encryption 122 | */ 123 | public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText) 124 | throws GeneralSecurityException { 125 | final Cipher cipher = Cipher.getInstance(AES_MODE); 126 | IvParameterSpec ivSpec = new IvParameterSpec(iv); 127 | cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); 128 | byte[] decryptedBytes = cipher.doFinal(decodedCipherText); 129 | 130 | return decryptedBytes; 131 | } 132 | 133 | private AESUtils() { 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/Base64Utils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | /** 6 | * Base64加密
7 | */ 8 | public class Base64Utils { 9 | 10 | private static char[] base64EncodeChars = new char[]{'A', 'B', 'C', 'D', 11 | 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 12 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 13 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 14 | 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', 15 | '4', '5', '6', '7', '8', '9', '+', '/'}; 16 | private static byte[] base64DecodeChars = new byte[]{-1, -1, -1, -1, -1, 17 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 18 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 19 | -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 20 | 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 21 | 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, 22 | -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 23 | 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, 24 | -1, -1}; 25 | 26 | /** 27 | * 加密 28 | * 29 | * @param data 30 | * @return 31 | */ 32 | public static String encode(byte[] data) { 33 | StringBuffer sb = new StringBuffer(); 34 | int len = data.length; 35 | int i = 0; 36 | int b1, b2, b3; 37 | while (i < len) { 38 | b1 = data[i++] & 0xff; 39 | if (i == len) { 40 | sb.append(base64EncodeChars[b1 >>> 2]); 41 | sb.append(base64EncodeChars[(b1 & 0x3) << 4]); 42 | sb.append("=="); 43 | break; 44 | } 45 | b2 = data[i++] & 0xff; 46 | if (i == len) { 47 | sb.append(base64EncodeChars[b1 >>> 2]); 48 | sb.append(base64EncodeChars[((b1 & 0x03) << 4) 49 | | ((b2 & 0xf0) >>> 4)]); 50 | sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); 51 | sb.append("="); 52 | break; 53 | } 54 | b3 = data[i++] & 0xff; 55 | sb.append(base64EncodeChars[b1 >>> 2]); 56 | sb.append(base64EncodeChars[((b1 & 0x03) << 4) 57 | | ((b2 & 0xf0) >>> 4)]); 58 | sb.append(base64EncodeChars[((b2 & 0x0f) << 2) 59 | | ((b3 & 0xc0) >>> 6)]); 60 | sb.append(base64EncodeChars[b3 & 0x3f]); 61 | } 62 | return sb.toString(); 63 | } 64 | 65 | /** 66 | * 解密 67 | * 68 | * @param str 69 | * @return 70 | */ 71 | public static byte[] decode(String str) { 72 | try { 73 | byte[] decodeStr = decodePrivate(str); 74 | return decodeStr; 75 | } catch (UnsupportedEncodingException e) { 76 | e.printStackTrace(); 77 | } 78 | return new byte[]{}; 79 | } 80 | 81 | private static byte[] decodePrivate(String str) 82 | throws UnsupportedEncodingException { 83 | StringBuffer sb = new StringBuffer(); 84 | byte[] data = null; 85 | data = str.getBytes("US-ASCII"); 86 | int len = data.length; 87 | int i = 0; 88 | int b1, b2, b3, b4; 89 | while (i < len) { 90 | 91 | do { 92 | b1 = base64DecodeChars[data[i++]]; 93 | } while (i < len && b1 == -1); 94 | if (b1 == -1) 95 | break; 96 | 97 | do { 98 | b2 = base64DecodeChars[data[i++]]; 99 | } while (i < len && b2 == -1); 100 | if (b2 == -1) 101 | break; 102 | sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4))); 103 | 104 | do { 105 | b3 = data[i++]; 106 | if (b3 == 61) 107 | return sb.toString().getBytes("iso8859-1"); 108 | b3 = base64DecodeChars[b3]; 109 | } while (i < len && b3 == -1); 110 | if (b3 == -1) 111 | break; 112 | sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); 113 | 114 | do { 115 | b4 = data[i++]; 116 | if (b4 == 61) 117 | return sb.toString().getBytes("iso8859-1"); 118 | b4 = base64DecodeChars[b4]; 119 | } while (i < len && b4 == -1); 120 | if (b4 == -1) 121 | break; 122 | sb.append((char) (((b3 & 0x03) << 6) | b4)); 123 | } 124 | return sb.toString().getBytes("iso8859-1"); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/DES3Utils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.SecretKey; 7 | import javax.crypto.spec.SecretKeySpec; 8 | 9 | /** 10 | * Desction: 11 | * Author:pengjianbo 12 | * Date:15/12/9 下午2:26 13 | */ 14 | public class DES3Utils { 15 | //定义加密算法,有DES、DESede(即3DES)、Blowfish 16 | private static final String Algorithm = "DESede"; 17 | 18 | /** 19 | * 加密方法 20 | * 21 | * @param src 源数据的字节数组 22 | * @param password 23 | * @return 24 | */ 25 | public static byte[] encryptMode(byte[] src, String password) { 26 | try { 27 | SecretKey deskey = new SecretKeySpec(build3DesKey(password), Algorithm); //生成密钥 28 | Cipher c1 = Cipher.getInstance(Algorithm); //实例化负责加密/解密的Cipher工具类 29 | c1.init(Cipher.ENCRYPT_MODE, deskey); //初始化为加密模式 30 | return c1.doFinal(src); 31 | } catch (java.security.NoSuchAlgorithmException e1) { 32 | e1.printStackTrace(); 33 | } catch (javax.crypto.NoSuchPaddingException e2) { 34 | e2.printStackTrace(); 35 | } catch (Exception e3) { 36 | e3.printStackTrace(); 37 | } 38 | return null; 39 | } 40 | 41 | /** 42 | * 解密函数 43 | * 44 | * @param src 密文的字节数组 45 | * @param password 46 | * @return 47 | */ 48 | public static byte[] decryptMode(byte[] src, String password) { 49 | try { 50 | SecretKey deskey = new SecretKeySpec(build3DesKey(password), Algorithm); 51 | Cipher c1 = Cipher.getInstance(Algorithm); 52 | c1.init(Cipher.DECRYPT_MODE, deskey); //初始化为解密模式 53 | return c1.doFinal(src); 54 | } catch (java.security.NoSuchAlgorithmException e1) { 55 | e1.printStackTrace(); 56 | } catch (javax.crypto.NoSuchPaddingException e2) { 57 | e2.printStackTrace(); 58 | } catch (Exception e3) { 59 | e3.printStackTrace(); 60 | } 61 | return null; 62 | } 63 | 64 | 65 | /* 66 | * 根据字符串生成密钥字节数组 67 | * @param keyStr 密钥字符串 68 | * @return 69 | * @throws UnsupportedEncodingException 70 | */ 71 | private static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException { 72 | byte[] key = new byte[24]; //声明一个24位的字节数组,默认里面都是0 73 | byte[] temp = keyStr.getBytes("UTF-8"); //将字符串转成字节数组 74 | 75 | /* 76 | * 执行数组拷贝 77 | * System.arraycopy(源数组,从源数组哪里开始拷贝,目标数组,拷贝多少位) 78 | */ 79 | if (key.length > temp.length) { 80 | //如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中 81 | System.arraycopy(temp, 0, key, 0, temp.length); 82 | } else { 83 | //如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中 84 | System.arraycopy(temp, 0, key, 0, key.length); 85 | } 86 | return key; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/DESUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import java.security.SecureRandom; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.SecretKey; 7 | import javax.crypto.SecretKeyFactory; 8 | import javax.crypto.spec.DESKeySpec; 9 | 10 | /** 11 | * Desction:DES对称加/解密 12 | * Author:pengjianbo 13 | * Date:15/12/8 下午10:32 14 | */ 15 | public class DESUtils { 16 | 17 | /** 18 | * 加密 19 | * @param data 20 | * @param password 21 | * @return 22 | */ 23 | public static byte[] encrypt(byte[] data, String password) { 24 | try { 25 | SecureRandom random = new SecureRandom(); 26 | DESKeySpec desKey = new DESKeySpec(password.getBytes()); 27 | //创建一个密匙工厂,然后用它把DESKeySpec转换成 28 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 29 | SecretKey securekey = keyFactory.generateSecret(desKey); 30 | //Cipher对象实际完成加密操作 31 | Cipher cipher = Cipher.getInstance("DES"); 32 | //用密匙初始化Cipher对象 33 | cipher.init(Cipher.ENCRYPT_MODE, securekey, random); 34 | //现在,获取数据并加密 35 | //正式执行加密操作 36 | return cipher.doFinal(data); 37 | } catch (Throwable e) { 38 | e.printStackTrace(); 39 | } 40 | 41 | return null; 42 | } 43 | 44 | /** 45 | * DES 46 | * @param src 47 | * @param password 48 | * @return 49 | */ 50 | public static byte[] decrypt(byte []src, String password) { 51 | try { 52 | // DES算法要求有一个可信任的随机数源 53 | SecureRandom random = new SecureRandom(); 54 | // 创建一个DESKeySpec对象 55 | DESKeySpec desKey = new DESKeySpec(password.getBytes()); 56 | // 创建一个密匙工厂 57 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 58 | // 将DESKeySpec对象转换成SecretKey对象 59 | SecretKey securekey = keyFactory.generateSecret(desKey); 60 | // Cipher对象实际完成解密操作 61 | Cipher cipher = Cipher.getInstance("DES"); 62 | // 用密匙初始化Cipher对象 63 | cipher.init(Cipher.DECRYPT_MODE, securekey, random); 64 | // 真正开始解密操作 65 | return cipher.doFinal(src); 66 | } catch (Throwable e) { 67 | e.printStackTrace(); 68 | } 69 | 70 | return null; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/HexUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import java.nio.charset.Charset; 4 | 5 | /** 6 | * Desction: 7 | * Author:pengjianbo 8 | * Date:15/12/9 上午11:08 9 | */ 10 | public class HexUtils { 11 | public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); 12 | private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 13 | 14 | private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 15 | private final Charset charset; 16 | 17 | public static byte[] decodeHex(char[] data) { 18 | int len = data.length; 19 | 20 | if ((len & 0x1) != 0) { 21 | throw new RuntimeException("Odd number of characters."); 22 | } 23 | 24 | byte[] out = new byte[len >> 1]; 25 | 26 | int i = 0; 27 | for (int j = 0; j < len; i++) { 28 | int f = toDigit(data[j], j) << 4; 29 | j++; 30 | f |= toDigit(data[j], j); 31 | j++; 32 | out[i] = ((byte) (f & 0xFF)); 33 | } 34 | 35 | return out; 36 | } 37 | 38 | public static char[] encodeHex(byte[] data) { 39 | return encodeHex(data, true); 40 | } 41 | 42 | public static char[] encodeHex(byte[] data, boolean toLowerCase) { 43 | return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); 44 | } 45 | 46 | protected static char[] encodeHex(byte[] data, char[] toDigits) { 47 | int l = data.length; 48 | char[] out = new char[l << 1]; 49 | 50 | int i = 0; 51 | for (int j = 0; i < l; i++) { 52 | out[(j++)] = toDigits[((0xF0 & data[i]) >>> 4)]; 53 | out[(j++)] = toDigits[(0xF & data[i])]; 54 | } 55 | return out; 56 | } 57 | 58 | public static String encodeHexString(byte[] data) { 59 | return new String(encodeHex(data)); 60 | } 61 | 62 | protected static int toDigit(char ch, int index) 63 | throws RuntimeException { 64 | int digit = Character.digit(ch, 16); 65 | if (digit == -1) { 66 | throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index); 67 | } 68 | return digit; 69 | } 70 | 71 | public HexUtils() { 72 | this.charset = DEFAULT_CHARSET; 73 | } 74 | 75 | public HexUtils(Charset charset) { 76 | this.charset = charset; 77 | } 78 | 79 | public HexUtils(String charsetName) { 80 | this(Charset.forName(charsetName)); 81 | } 82 | 83 | public byte[] decode(byte[] array) { 84 | return decodeHex(new String(array, getCharset()).toCharArray()); 85 | } 86 | 87 | public Object decode(Object object) { 88 | try { 89 | char[] charArray = (object instanceof String) ? ((String) object).toCharArray() : (char[]) object; 90 | return decodeHex(charArray); 91 | } catch (ClassCastException e) { 92 | throw new RuntimeException(e.getMessage(), e); 93 | } 94 | } 95 | 96 | public byte[] encode(byte[] array) { 97 | return encodeHexString(array).getBytes(getCharset()); 98 | } 99 | 100 | public Object encode(Object object) { 101 | try { 102 | byte[] byteArray = (object instanceof String) ? ((String) object).getBytes(getCharset()) : (byte[]) object; 103 | 104 | return encodeHex(byteArray); 105 | } catch (ClassCastException e) { 106 | throw new RuntimeException(e.getMessage(), e); 107 | } 108 | } 109 | 110 | public Charset getCharset() { 111 | return this.charset; 112 | } 113 | 114 | public String getCharsetName() { 115 | return this.charset.name(); 116 | } 117 | 118 | public String toString() { 119 | return super.toString() + "[charsetName=" + this.charset + "]"; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/MD5Utils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.InputStream; 5 | import java.io.UnsupportedEncodingException; 6 | import java.security.MessageDigest; 7 | import java.security.NoSuchAlgorithmException; 8 | 9 | /** 10 | * 提取文件MD5值 11 | * 12 | */ 13 | public class MD5Utils { 14 | private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', 15 | '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 16 | 17 | private static String toHexString(byte[] b) { 18 | StringBuilder sb = new StringBuilder(b.length * 2); 19 | for (int i = 0; i < b.length; i++) { 20 | sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]); 21 | sb.append(HEX_DIGITS[b[i] & 0x0f]); 22 | } 23 | return sb.toString(); 24 | } 25 | 26 | /** 27 | * 文件加密 28 | * 29 | * @param filename 30 | * @return 31 | */ 32 | public static String md5file(String filename) { 33 | InputStream fis; 34 | byte[] buffer = new byte[1024]; 35 | int numRead = 0; 36 | MessageDigest md5; 37 | try { 38 | fis = new FileInputStream(filename); 39 | md5 = MessageDigest.getInstance("MD5"); 40 | while ((numRead = fis.read(buffer)) > 0) { 41 | md5.update(buffer, 0, numRead); 42 | } 43 | fis.close(); 44 | return toHexString(md5.digest()); 45 | } catch (Exception e) { 46 | System.out.println("error"); 47 | return null; 48 | } 49 | } 50 | 51 | /** 52 | * 字符串加密 53 | * 54 | * @param string 55 | * @return 56 | */ 57 | public static String md5(String string) { 58 | byte[] hash; 59 | try { 60 | hash = MessageDigest.getInstance("MD5").digest( 61 | string.getBytes("UTF-8")); 62 | } catch (NoSuchAlgorithmException e) { 63 | throw new RuntimeException("Huh, MD5 should be supported?", e); 64 | } catch (UnsupportedEncodingException e) { 65 | throw new RuntimeException("Huh, UTF-8 should be supported?", e); 66 | } 67 | 68 | StringBuilder hex = new StringBuilder(hash.length * 2); 69 | for (byte b : hash) { 70 | if ((b & 0xFF) < 0x10) 71 | hex.append("0"); 72 | hex.append(Integer.toHexString(b & 0xFF)); 73 | } 74 | return hex.toString(); 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/secarity/RSAUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.secarity; 2 | 3 | import java.math.BigInteger; 4 | import java.security.Key; 5 | import java.security.KeyFactory; 6 | import java.security.KeyPair; 7 | import java.security.KeyPairGenerator; 8 | import java.security.SecureRandom; 9 | import java.security.interfaces.RSAPrivateKey; 10 | import java.security.interfaces.RSAPublicKey; 11 | import java.security.spec.RSAPrivateKeySpec; 12 | import java.security.spec.RSAPublicKeySpec; 13 | 14 | import javax.crypto.Cipher; 15 | 16 | /** 17 | * Desction:RSA 工具类。提供加密,解密,生成密钥对等方法。 18 | * Author:pengjianbo 19 | * Date:15/9/22 下午7:47 20 | */ 21 | public class RSAUtils { 22 | /** 23 | * 填充方式 24 | */ 25 | public static enum PADDING { 26 | NoPadding, PKCS1Padding 27 | } 28 | 29 | ; 30 | /** 31 | * 算法 32 | */ 33 | public static final String KEY_ALGORITHM = "RSA"; 34 | /** 35 | * 算法/工作模式 36 | */ 37 | public final static String CHIPER_ALGORITHM = "RSA/ECB/"; 38 | /** 39 | * 密钥长度 40 | */ 41 | public static final int KEY_SIZE = 1024; 42 | 43 | /** 44 | * 65537 or 0x010001 45 | */ 46 | public static final byte[] PUBLIC_EXPONENT = {1, 0, 1}; 47 | 48 | /** 49 | * 生成密钥对 50 | * 51 | * @return KeyPair 52 | */ 53 | public static KeyPair generateKeyPair() { 54 | try { 55 | KeyPairGenerator keyPairGen = KeyPairGenerator 56 | .getInstance(KEY_ALGORITHM); 57 | keyPairGen.initialize(KEY_SIZE, new SecureRandom()); 58 | KeyPair keyPair = keyPairGen.genKeyPair(); 59 | return keyPair; 60 | } catch (Exception e) { 61 | throw new RuntimeException("Error when init key pair, errmsg: " + e.getMessage(), e); 62 | } 63 | } 64 | 65 | /** 66 | * 生成公钥 67 | * 68 | * @param modulus 69 | * @param publicExponent 70 | * @return 71 | */ 72 | private static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) { 73 | try { 74 | RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger( 75 | 1, modulus), new BigInteger(1, publicExponent)); 76 | KeyFactory keyFac = KeyFactory.getInstance(KEY_ALGORITHM); 77 | return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); 78 | } catch (Exception e) { 79 | throw new RuntimeException("Error when generate rsaPubblicKey, errmsg: " + e.getMessage(), e); 80 | } 81 | 82 | } 83 | 84 | /** 85 | * 生成私钥 86 | * 87 | * @param modulus 88 | * @param privateExponent 89 | * @return RSAPrivateKey 90 | */ 91 | private static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) { 92 | try { 93 | KeyFactory keyFac = KeyFactory.getInstance(KEY_ALGORITHM); 94 | RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(1, modulus), new BigInteger(1, privateExponent)); 95 | return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec); 96 | } catch (Exception e) { 97 | throw new RuntimeException("Error when generate rsaPrivateKey, errmsg: " 98 | + e.getMessage(), e); 99 | } 100 | } 101 | 102 | /** 103 | * 加密 104 | * 105 | * @param key 加密的密钥 106 | * @param data 待加密的明文数据 107 | * @return 加密后的数据 108 | */ 109 | private static byte[] encrypt(Key key, byte[] data, PADDING padding) { 110 | try { 111 | Cipher cipher = Cipher.getInstance(CHIPER_ALGORITHM + (padding == null ? PADDING.NoPadding : padding)); 112 | cipher.init(Cipher.ENCRYPT_MODE, key); 113 | return cipher.doFinal(data); 114 | } catch (Exception e) { 115 | throw new RuntimeException("Error when encrypt data, errmsg: " + e.getMessage(), e); 116 | } 117 | } 118 | 119 | /** 120 | * 公钥加密 121 | * 122 | * @param publicKey 123 | * @param data 124 | * @return 125 | */ 126 | public static byte[] encryptByPublicKey(byte[] publicKey, byte[] data, PADDING padding) { 127 | // 得到公钥 128 | RSAPublicKey key = generateRSAPublicKey(publicKey, PUBLIC_EXPONENT); 129 | // 加密 130 | return encrypt(key, data, padding); 131 | } 132 | 133 | /** 134 | * 私钥加密 135 | * 136 | * @param publicKey 137 | * @param privateKey 138 | * @param data 139 | * @return 140 | */ 141 | public static byte[] encryptByPrivateKey(byte[] publicKey, byte[] privateKey, byte[] data, PADDING padding) { 142 | // 得到私钥 143 | RSAPrivateKey key = generateRSAPrivateKey(publicKey, privateKey); 144 | // 加密 145 | return encrypt(key, data, padding); 146 | } 147 | 148 | /** 149 | * 解密 150 | * 151 | * @param key 解密的密钥 152 | * @param data 已经加密的数据 153 | * @return 解密后的明文 154 | */ 155 | private static byte[] decrypt(Key key, byte[] data, PADDING padding) { 156 | try { 157 | Cipher cipher = Cipher.getInstance(CHIPER_ALGORITHM + (padding == null ? PADDING.NoPadding : padding)); 158 | cipher.init(Cipher.DECRYPT_MODE, key); 159 | return cipher.doFinal(data); 160 | } catch (Exception e) { 161 | throw new RuntimeException("Error when decrypt data, errmsg: " + e.getMessage(), e); 162 | } 163 | } 164 | 165 | /** 166 | * 公钥解密 167 | * 168 | * @param publicKey 169 | * @param data 170 | * @ret公钥urn 171 | */ 172 | public static byte[] decryptByPublicKey(byte[] publicKey, byte[] data, PADDING padding) { 173 | // 得到公钥 174 | RSAPublicKey key = generateRSAPublicKey(publicKey, PUBLIC_EXPONENT); 175 | // 解密 176 | return decrypt(key, data, padding); 177 | } 178 | 179 | /** 180 | * 私钥解密 181 | * 182 | * @param publicKey 183 | * @param privateKey 184 | * @param data 185 | * @return 186 | */ 187 | public static byte[] decryptByPrivateKey(byte[] publicKey, byte[] privateKey, byte[] data, PADDING padding) { 188 | // 得到私钥 189 | RSAPrivateKey key = generateRSAPrivateKey(publicKey, privateKey); 190 | // 解密 191 | return decrypt(key, data, padding); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/sp/SharePreferenceUtil.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.sp; 2 | 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | import android.content.Context; 7 | import android.content.SharedPreferences; 8 | import android.content.SharedPreferences.Editor; 9 | 10 | /** 11 | * SharedPreferences 工具类 12 | * 13 | */ 14 | public class SharePreferenceUtil { 15 | 16 | private static SharedPreferences sp; 17 | 18 | /** 保存在手机里面的文件名 */ 19 | private final static String SharePreferncesName = "SP_SETTING"; 20 | 21 | /** 22 | * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 23 | * 24 | * @param context 25 | * @param key 26 | * 键值对的key 27 | * @param value 28 | * 键值对的值 29 | * @return 是否保存成功 30 | */ 31 | public static boolean setValue(Context context, String key, Object value) { 32 | if (sp == null) { 33 | sp = context.getSharedPreferences(SharePreferncesName, 34 | Context.MODE_PRIVATE); 35 | } 36 | 37 | Editor edit = sp.edit(); 38 | if (value instanceof String) { 39 | return edit.putString(key, (String) value).commit(); 40 | } else if (value instanceof Boolean) { 41 | return edit.putBoolean(key, (Boolean) value).commit(); 42 | } else if (value instanceof Float) { 43 | return edit.putFloat(key, (Float) value).commit(); 44 | } else if (value instanceof Integer) { 45 | return edit.putInt(key, (Integer) value).commit(); 46 | } else if (value instanceof Long) { 47 | return edit.putLong(key, (Long) value).commit(); 48 | } else if (value instanceof Set) { 49 | new IllegalArgumentException("Value can not be Set object!"); 50 | return false; 51 | } 52 | return false; 53 | } 54 | 55 | /** 56 | * 得到Boolean类型的值 57 | * 58 | * @param context 59 | * @param key 60 | * @param defaultValue 61 | * @return 62 | */ 63 | public static boolean getBoolean(Context context, String key, 64 | boolean defaultValue) { 65 | if (sp == null) { 66 | sp = context.getSharedPreferences(SharePreferncesName, 67 | Context.MODE_PRIVATE); 68 | } 69 | return sp.getBoolean(key, defaultValue); 70 | } 71 | 72 | /** 73 | * 得到String类型的值 74 | * 75 | * @param context 76 | * @param key 77 | * @param defaultValue 78 | * @return 79 | */ 80 | public static String getString(Context context, String key, 81 | String defaultValue) { 82 | if (sp == null) { 83 | sp = context.getSharedPreferences(SharePreferncesName, 84 | Context.MODE_PRIVATE); 85 | } 86 | return sp.getString(key, defaultValue); 87 | } 88 | 89 | /** 90 | * 得到Float类型的值 91 | * 92 | * @param context 93 | * @param key 94 | * @param defaultValue 95 | * @return 96 | */ 97 | public static Float getFloat(Context context, String key, float defaultValue) { 98 | if (sp == null) { 99 | sp = context.getSharedPreferences(SharePreferncesName, 100 | Context.MODE_PRIVATE); 101 | } 102 | return sp.getFloat(key, defaultValue); 103 | } 104 | 105 | /** 106 | * 得到Int类型的值 107 | * 108 | * @param context 109 | * @param key 110 | * @param defaultValue 111 | * @return 112 | */ 113 | public static int getInt(Context context, String key, int defaultValue) { 114 | if (sp == null) { 115 | sp = context.getSharedPreferences(SharePreferncesName, 116 | Context.MODE_PRIVATE); 117 | } 118 | return sp.getInt(key, defaultValue); 119 | } 120 | 121 | /** 122 | * 得到Long类型的值 123 | * 124 | * @param context 125 | * @param key 126 | * @param defaultValue 127 | * @return 128 | */ 129 | public static long getLong(Context context, String key, long defaultValue) { 130 | if (sp == null) { 131 | sp = context.getSharedPreferences(SharePreferncesName, 132 | Context.MODE_PRIVATE); 133 | } 134 | return sp.getLong(key, defaultValue); 135 | } 136 | 137 | /** 138 | * 移除某个key值已经对应的值 139 | * 140 | * @param context 141 | * @param key 142 | */ 143 | public static boolean remove(Context context, String key) { 144 | SharedPreferences sp = context.getSharedPreferences( 145 | SharePreferncesName, Context.MODE_PRIVATE); 146 | Editor editor = sp.edit(); 147 | editor.remove(key); 148 | return editor.commit(); 149 | } 150 | 151 | /** 152 | * 清除所有数据 153 | * 154 | * @param context 155 | * @return 是否成功 156 | */ 157 | public static boolean clear(Context context) { 158 | SharedPreferences sp = context.getSharedPreferences( 159 | SharePreferncesName, Context.MODE_PRIVATE); 160 | Editor editor = sp.edit(); 161 | editor.clear(); 162 | return editor.commit(); 163 | } 164 | 165 | /** 166 | * 查询某个key是否已经存在 167 | * 168 | * @param context 169 | * @param key 170 | * @return 是否存在 171 | */ 172 | public static boolean contains(Context context, String key) { 173 | SharedPreferences sp = context.getSharedPreferences( 174 | SharePreferncesName, Context.MODE_PRIVATE); 175 | boolean result = sp.contains(key); 176 | 177 | return result; 178 | } 179 | 180 | /** 181 | * 返回所有的键值对 182 | * 183 | * @param context 184 | * @return Map 185 | */ 186 | public static Map getAll(Context context) { 187 | SharedPreferences sp = context.getSharedPreferences( 188 | SharePreferncesName, Context.MODE_PRIVATE); 189 | return sp.getAll(); 190 | } 191 | 192 | } 193 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/string/DateUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.string; 2 | 3 | import java.text.DateFormat; 4 | import java.text.ParseException; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | import java.util.GregorianCalendar; 9 | 10 | import xyz.yhsj.yhutils.logutils.LogUtils; 11 | 12 | 13 | public class DateUtils { 14 | 15 | private final static long minute = 60 * 1000;// 1分钟 16 | private final static long hour = 60 * minute;// 1小时 17 | private final static long day = 24 * hour;// 1天 18 | private final static long month = 31 * day;// 月 19 | private final static long year = 12 * month;// 年 20 | 21 | /** 22 | * 日期格式:yyyy-MM-dd HH:mm:ss 23 | **/ 24 | public static final String DF_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; 25 | 26 | /** 27 | * 日期格式:yyyy-MM-dd hh:mm:ss 28 | **/ 29 | public static final String DF_YYYY_MM_DD_h_MM_SS = "yyyy-MM-dd hh:mm:ss"; 30 | 31 | /** 32 | * 日期格式:yyyy-MM-dd HH:mm 33 | **/ 34 | public static final String DF_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; 35 | 36 | /** 37 | * 日期格式:yyyy-MM-dd 38 | **/ 39 | public static final String DF_YYYY_MM_DD = "yyyy-MM-dd"; 40 | 41 | /** 42 | * 日期格式:HH:mm:ss 43 | **/ 44 | public static final String DF_HH_MM_SS = "HH:mm:ss"; 45 | 46 | /** 47 | * 日期格式:HH:mm 48 | **/ 49 | public static final String DF_HH_MM = "HH:mm"; 50 | 51 | /** 52 | * 将日期格式化成友好的字符串:几分钟前、几小时前、几天前、几月前、几年前、刚刚 53 | * 54 | * @param date 55 | * @return 56 | */ 57 | public static String formatFriendly(Date date) { 58 | Calendar now = Calendar.getInstance(); 59 | now.setTime(new Date()); 60 | int nowYear = now.get(Calendar.YEAR); 61 | int nowMonth = now.get(Calendar.MONTH); 62 | int nowWeek = now.get(Calendar.WEEK_OF_MONTH); 63 | int nowDay = now.get(Calendar.DAY_OF_WEEK); 64 | int nowHour = now.get(Calendar.HOUR_OF_DAY); 65 | int nowMinute = now.get(Calendar.MINUTE); 66 | 67 | Calendar ca = Calendar.getInstance(); 68 | if (date != null) 69 | ca.setTime(date); 70 | else 71 | ca.setTime(new Date()); 72 | int year = ca.get(Calendar.YEAR); 73 | int month = ca.get(Calendar.MONTH); 74 | int week = ca.get(Calendar.WEEK_OF_MONTH); 75 | int day = ca.get(Calendar.DAY_OF_WEEK); 76 | int hour = ca.get(Calendar.HOUR_OF_DAY); 77 | int minute = ca.get(Calendar.MINUTE); 78 | if (year != nowYear) { 79 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 80 | //不同年份 81 | return sdf.format(date); 82 | } else { 83 | if (month != nowMonth) { 84 | //不同月份 85 | SimpleDateFormat sdf = new SimpleDateFormat("M月dd日"); 86 | return sdf.format(date); 87 | } else { 88 | if (week != nowWeek) { 89 | //不同周 90 | SimpleDateFormat sdf = new SimpleDateFormat("M月dd日"); 91 | return sdf.format(date); 92 | } else if (day != nowDay) { 93 | if (day + 1 == nowDay) { 94 | return "昨天" + format(date, "HH:mm"); 95 | } 96 | if (day + 2 == nowDay) { 97 | return "前天" + format(date, "HH:mm"); 98 | } 99 | //不同天 100 | SimpleDateFormat sdf = new SimpleDateFormat("M月dd日"); 101 | return sdf.format(date); 102 | } else { 103 | //同一天 104 | int hourGap = nowHour - hour; 105 | if (hourGap == 0)//1小时内 106 | { 107 | if (nowMinute - minute < 1) { 108 | return "刚刚"; 109 | } else { 110 | return (nowMinute - minute) + "分钟前"; 111 | } 112 | } else if (hourGap >= 1 && hourGap <= 12) { 113 | return hourGap + "小时前"; 114 | } else { 115 | SimpleDateFormat sdf = new SimpleDateFormat("今天 HH:mm"); 116 | return sdf.format(date); 117 | } 118 | } 119 | } 120 | } 121 | } 122 | 123 | /** 124 | * 获取当前时间戳 125 | * 126 | * @return 时间戳 127 | */ 128 | public static long getCurrentTime() { 129 | Calendar calendar = Calendar.getInstance(); 130 | return calendar.getTimeInMillis(); 131 | } 132 | 133 | /** 134 | * 格式化12小时制 格式:yyyy-MM-dd hh-mm-ss 135 | * 136 | * @param time 时间 137 | * @return 138 | */ 139 | public static String format12Time(long time) { 140 | return format(time, DF_YYYY_MM_DD_h_MM_SS); 141 | } 142 | 143 | /** 144 | * 格式化24小时制 格式:yyyy-MM-dd HH-MM-ss 145 | * 146 | * @param time 时间 147 | * @return 148 | */ 149 | public static String format24Time(long time) { 150 | return format(time, DF_YYYY_MM_DD_HH_MM_SS); 151 | } 152 | 153 | /** 154 | * 得到当前时间 155 | * 156 | * @return 157 | */ 158 | public static Date getThisTime() { 159 | return new Date(); 160 | } 161 | 162 | /** 163 | * 获取系统当前日期 164 | * 165 | * @return 166 | */ 167 | public static String getThisTime(String formater) { 168 | return format(getCurrentTime(), formater); 169 | } 170 | 171 | /** 172 | * 将日期字符串转成日期 173 | * 174 | * @param strDate 日期字符串 175 | * @param format 格式 176 | * @return 177 | */ 178 | public static Date parseDate(String strDate, String format) { 179 | DateFormat dateFormat = new SimpleDateFormat(format); 180 | Date returnDate = null; 181 | try { 182 | returnDate = dateFormat.parse(strDate); 183 | } catch (ParseException e) { 184 | LogUtils.e("parseDate failed !"); 185 | 186 | } 187 | return returnDate; 188 | 189 | } 190 | 191 | /** 192 | * 验证日期是否比当前日期早 193 | * 194 | * @param target1 比较时间1 195 | * @param target2 比较时间2 196 | * @return true 则代表target1比target2晚或等于target2,否则比target2早 197 | */ 198 | public static boolean compareDate(Date target1, Date target2) { 199 | boolean flag = false; 200 | try { 201 | String target1DateTime = format(target1, DF_YYYY_MM_DD_HH_MM_SS); 202 | String target2DateTime = format(target2, DF_YYYY_MM_DD_HH_MM_SS); 203 | if (target1DateTime.compareTo(target2DateTime) <= 0) { 204 | flag = true; 205 | } 206 | } catch (Exception e1) { 207 | System.out.println("比较失败,原因:" + e1.getMessage()); 208 | } 209 | return flag; 210 | } 211 | 212 | /** 213 | * 得到某个时间点 正数为当前时间之后,负数为当前时间之前 214 | * 215 | * @param year 216 | * @param month 217 | * @param day 218 | * @param hour 219 | * @param minute 220 | * @param second 221 | * @param format 222 | * @return 自定义 223 | */ 224 | public static String getTimePoint(int year, int month, int day, int hour, 225 | int minute, int second, String format) { 226 | Calendar c = Calendar.getInstance(); 227 | 228 | c.add(Calendar.YEAR, year); 229 | c.add(Calendar.MONTH, month); 230 | c.add(Calendar.DAY_OF_MONTH, day); 231 | c.add(Calendar.HOUR_OF_DAY, hour); 232 | c.add(Calendar.MINUTE, minute); 233 | c.add(Calendar.SECOND, second); 234 | 235 | if (format == null) { 236 | return format(c.getTimeInMillis(), DF_YYYY_MM_DD_HH_MM_SS); 237 | } 238 | return format(c.getTimeInMillis(), format); 239 | } 240 | 241 | /** 242 | * 格式化时间,自定义格式 243 | * 244 | * @param time 时间 245 | * @param formater 格式化时间用的标签 246 | * @return 247 | */ 248 | public static String format(long time, String formater) { 249 | SimpleDateFormat sdf = new SimpleDateFormat(formater); 250 | return sdf.format(new Date(time)); 251 | } 252 | 253 | /** 254 | * 将日期以yyyy-MM-dd HH:mm:ss格式化 255 | * 256 | * @param date 日期 257 | * @return 258 | */ 259 | public static String format(Date date, String formater) { 260 | SimpleDateFormat sdf = new SimpleDateFormat(formater); 261 | return sdf.format(date); 262 | } 263 | 264 | /** 265 | * 获取当前年 266 | * 267 | * @return 年 268 | */ 269 | public static String getYear() { 270 | return format(getCurrentTime(), "yyyy"); 271 | } 272 | 273 | /** 274 | * 获取当前月 275 | * 276 | * @return 月 277 | */ 278 | public static String getMonth() { 279 | return format(getCurrentTime(), "MM"); 280 | } 281 | 282 | /** 283 | * 获取当前日 284 | * 285 | * @return 日 286 | */ 287 | public static String getDay() { 288 | return format(getCurrentTime(), "dd"); 289 | } 290 | 291 | /** 292 | * 获取当前小时 293 | * 294 | * @return 小时 295 | */ 296 | public static String getHour() { 297 | return format(getCurrentTime(), "HH"); 298 | } 299 | 300 | /** 301 | * 获取当前小时 302 | * 303 | * @return 小时 304 | */ 305 | public static String getMinute() { 306 | return format(getCurrentTime(), "mm"); 307 | } 308 | 309 | /** 310 | * 获取某天是星期几 311 | * 312 | * @param date 313 | * @return 314 | */ 315 | public static String getMonthDayWeek(Date date) { 316 | Calendar c = Calendar.getInstance(); 317 | c.setTime(date); 318 | int year = c.get(Calendar.YEAR); //获取年 319 | int month = c.get(Calendar.MONTH) + 1; //获取月份,0表示1月份 320 | int day = c.get(Calendar.DAY_OF_MONTH); //获取当前天数 321 | int week = c.get(Calendar.DAY_OF_WEEK); 322 | 323 | String weekStr = null; 324 | 325 | switch (week) { 326 | 327 | case Calendar.SUNDAY: 328 | weekStr = "周日"; 329 | break; 330 | 331 | case Calendar.MONDAY: 332 | weekStr = "周一"; 333 | break; 334 | 335 | case Calendar.TUESDAY: 336 | weekStr = "周二"; 337 | break; 338 | 339 | case Calendar.WEDNESDAY: 340 | weekStr = "周三"; 341 | break; 342 | 343 | case Calendar.THURSDAY: 344 | weekStr = "周四"; 345 | break; 346 | 347 | case Calendar.FRIDAY: 348 | weekStr = "周五"; 349 | break; 350 | 351 | case Calendar.SATURDAY: 352 | weekStr = "周六"; 353 | break; 354 | } 355 | 356 | return month + "月" + day + "日" + "(" + weekStr + ")"; 357 | } 358 | 359 | /** 360 | * 获取年龄值 361 | * 362 | * @param birthday 363 | * @return 364 | */ 365 | public static int getAge(String birthday) { 366 | if (StringUtils.isEmpty(birthday)) return 0; 367 | String yearStr = birthday.substring(0, 4); 368 | int integer = Integer.parseInt(yearStr); 369 | int newYear = new GregorianCalendar().get(Calendar.YEAR); 370 | return newYear - integer; 371 | } 372 | } 373 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/string/DensityUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.string; 2 | 3 | import android.content.Context; 4 | import android.util.TypedValue; 5 | 6 | import xyz.yhsj.yhutils.logutils.LogUtils; 7 | 8 | 9 | /** 10 | * 单位转换 工具类
11 | */ 12 | public class DensityUtils { 13 | 14 | /** 15 | * dp转px 16 | */ 17 | public static int dp2px(Context context, float dpVal) { 18 | int result = (int) TypedValue.applyDimension( 19 | TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources() 20 | .getDisplayMetrics()); 21 | LogUtils.i("dp-->px:" + result); 22 | return result; 23 | } 24 | 25 | /** 26 | * sp转px 27 | */ 28 | public static int sp2px(Context context, float spVal) { 29 | int result = (int) TypedValue.applyDimension( 30 | TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources() 31 | .getDisplayMetrics()); 32 | LogUtils.i("sp-->px:" + result); 33 | return result; 34 | } 35 | 36 | /** 37 | * px转dp 38 | */ 39 | public static int px2dp(Context context, float pxVal) { 40 | final float scale = context.getResources().getDisplayMetrics().density; 41 | int result = (int) (pxVal / scale); 42 | LogUtils.i("px-->dp:" + result); 43 | return result; 44 | } 45 | 46 | /** 47 | * px转sp 48 | */ 49 | public static float px2sp(Context context, float pxVal) { 50 | int result = (int) (pxVal / context.getResources().getDisplayMetrics().scaledDensity); 51 | LogUtils.i("px-->sp:" + result); 52 | return result; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/string/StringUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.string; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.net.URLEncoder; 5 | import java.util.regex.Matcher; 6 | import java.util.regex.Pattern; 7 | 8 | import android.annotation.SuppressLint; 9 | 10 | /** 11 | * @author LOVE 12 | */ 13 | public final class StringUtils { 14 | 15 | /** 16 | * 判断字符串是否为null或"" 17 | * 18 | * @param str 19 | * @return 为空或null返回true,否则返回false 20 | */ 21 | public static boolean isEmpty(String str) { 22 | return (str == null || str.trim().length() == 0); 23 | } 24 | 25 | /** 26 | * 获取字符串长度 27 | */ 28 | public static int length(CharSequence str) { 29 | return str == null ? 0 : str.length(); 30 | } 31 | 32 | 33 | /** 34 | * utf-8编码 35 | */ 36 | public static String utf8Encode(String str) { 37 | if (!isEmpty(str) && str.getBytes().length != str.length()) { 38 | try { 39 | return URLEncoder.encode(str, "UTF-8"); 40 | } catch (UnsupportedEncodingException e) { 41 | throw new RuntimeException("UnsupportedEncodingException occurred. ", e); 42 | } 43 | } 44 | return str; 45 | } 46 | 47 | /** 48 | * 将长字符从截取剩下的用...代替 49 | * 50 | * @param input 51 | * @param count 52 | * @return 53 | */ 54 | public static String cutString(String input, int count) { 55 | return cutString(input, count, null); 56 | } 57 | 58 | /** 59 | * 将长字符从截取剩下的用more代替,more为空则用省略号代替 60 | * 61 | * @param input 62 | * @param count 63 | * @param more 64 | * @return 65 | */ 66 | public static String cutString(String input, int count, String more) { 67 | String resultString = ""; 68 | if (input != null) { 69 | if (more == null) { 70 | more = "..."; 71 | } 72 | if (input.length() > count) { 73 | resultString = input.substring(0, count) + more; 74 | } else { 75 | resultString = input; 76 | } 77 | } 78 | return resultString; 79 | } 80 | 81 | /** 82 | * 获得指定中文长度对应的字符串长度,用于截取显示文字,一个中文等于两个英文 83 | * 84 | * @param count 85 | * @param string 86 | * @return 87 | */ 88 | public static int chinese_2_StringLenth(String string, int count) { 89 | int result = 0; 90 | int displayWidth = count * 2; 91 | if (string != null) { 92 | for (char chr : string.toCharArray()) { 93 | // 中文 94 | if (chr >= 0x4e00 && chr <= 0x9fbb) { 95 | displayWidth -= 2; 96 | } else { 97 | // 英文 98 | displayWidth -= 1; 99 | } 100 | if (displayWidth <= 0) { 101 | break; 102 | } 103 | result++; 104 | } 105 | } 106 | return result; 107 | } 108 | 109 | /** 110 | * 检测字符串中是否包含汉字 111 | * 112 | * @param sequence 113 | * @return 114 | */ 115 | public static boolean checkChinese(String sequence) { 116 | final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]"; 117 | boolean result = false; 118 | Pattern pattern = Pattern.compile(format); 119 | Matcher matcher = pattern.matcher(sequence); 120 | result = matcher.find(); 121 | return result; 122 | } 123 | 124 | /** 125 | * Unicode字符转为汉字 126 | * 127 | * @param ori 128 | * @return 129 | */ 130 | public static String Unicode_2_String(String ori) { 131 | char aChar; 132 | int len = ori.length(); 133 | StringBuffer outBuffer = new StringBuffer(len); 134 | for (int x = 0; x < len; ) { 135 | aChar = ori.charAt(x++); 136 | if (aChar == '\\') { 137 | aChar = ori.charAt(x++); 138 | if (aChar == 'u') { 139 | // Read the xxxx 140 | int value = 0; 141 | for (int i = 0; i < 4; i++) { 142 | aChar = ori.charAt(x++); 143 | switch (aChar) { 144 | case '0': 145 | case '1': 146 | case '2': 147 | case '3': 148 | case '4': 149 | case '5': 150 | case '6': 151 | case '7': 152 | case '8': 153 | case '9': 154 | value = (value << 4) + aChar - '0'; 155 | break; 156 | case 'a': 157 | case 'b': 158 | case 'c': 159 | case 'd': 160 | case 'e': 161 | case 'f': 162 | value = (value << 4) + 10 + aChar - 'a'; 163 | break; 164 | case 'A': 165 | case 'B': 166 | case 'C': 167 | case 'D': 168 | case 'E': 169 | case 'F': 170 | value = (value << 4) + 10 + aChar - 'A'; 171 | break; 172 | default: 173 | throw new IllegalArgumentException( 174 | "Malformed \\uxxxx encoding."); 175 | } 176 | } 177 | outBuffer.append((char) value); 178 | } else { 179 | if (aChar == 't') 180 | aChar = '\t'; 181 | else if (aChar == 'r') 182 | aChar = '\r'; 183 | else if (aChar == 'n') 184 | aChar = '\n'; 185 | else if (aChar == 'f') 186 | aChar = '\f'; 187 | outBuffer.append(aChar); 188 | } 189 | } else 190 | outBuffer.append(aChar); 191 | 192 | } 193 | return outBuffer.toString(); 194 | } 195 | 196 | /** 197 | * 全角转半角 198 | * 199 | * @param s 200 | * @return 201 | */ 202 | public static String full_2_Half(String s) { 203 | if (isEmpty(s)) { 204 | return s; 205 | } 206 | 207 | char[] source = s.toCharArray(); 208 | for (int i = 0; i < source.length; i++) { 209 | if (source[i] == 12288) { 210 | source[i] = ' '; 211 | // } else if (source[i] == 12290) { 212 | // source[i] = '.'; 213 | } else if (source[i] >= 65281 && source[i] <= 65374) { 214 | source[i] = (char) (source[i] - 65248); 215 | } else { 216 | source[i] = source[i]; 217 | } 218 | } 219 | return new String(source); 220 | } 221 | 222 | /** 223 | * 半角转全角 224 | * 225 | * @param s 226 | * @return 227 | */ 228 | public static String half_2_Full(String s) { 229 | if (isEmpty(s)) { 230 | return s; 231 | } 232 | 233 | char[] source = s.toCharArray(); 234 | for (int i = 0; i < source.length; i++) { 235 | if (source[i] == ' ') { 236 | source[i] = (char) 12288; 237 | // } else if (source[i] == '.') { 238 | // source[i] = (char)12290; 239 | } else if (source[i] >= 33 && source[i] <= 126) { 240 | source[i] = (char) (source[i] + 65248); 241 | } else { 242 | source[i] = source[i]; 243 | } 244 | } 245 | return new String(source); 246 | } 247 | 248 | /** 249 | * 数据库字符转义 250 | * 251 | * @param keyWord 252 | * @return 253 | */ 254 | public static String sqliteEscape(String keyWord) { 255 | keyWord = keyWord.replace("/", "//"); 256 | keyWord = keyWord.replace("'", "''"); 257 | keyWord = keyWord.replace("[", "/["); 258 | keyWord = keyWord.replace("]", "/]"); 259 | keyWord = keyWord.replace("%", "/%"); 260 | keyWord = keyWord.replace("&", "/&"); 261 | keyWord = keyWord.replace("_", "/_"); 262 | keyWord = keyWord.replace("(", "/("); 263 | keyWord = keyWord.replace(")", "/)"); 264 | return keyWord; 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /YHUtils/src/main/java/xyz/yhsj/yhutils/tools/ClassUtils.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutils.tools; 2 | 3 | import java.lang.reflect.ParameterizedType; 4 | import java.lang.reflect.Type; 5 | 6 | /** 7 | * 获取泛型 8 | * Created by LOVE on 2015/12/25. 9 | */ 10 | public class ClassUtils { 11 | 12 | public static Class getGenericClass(Class klass) { 13 | Type type = klass.getGenericSuperclass(); 14 | if (type == null || !(type instanceof ParameterizedType)) return null; 15 | ParameterizedType parameterizedType = (ParameterizedType) type; 16 | Type[] types = parameterizedType.getActualTypeArguments(); 17 | if (types == null || types.length == 0) return null; 18 | return (Class) types[0]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /YHUtils/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | yhutils 3 | 4 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.2" 6 | 7 | defaultConfig { 8 | applicationId "xyz.yhsj.yhutilsDemo" 9 | minSdkVersion 14 10 | targetSdkVersion 23 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | compile 'com.android.support:appcompat-v7:23.1.1' 25 | compile 'com.android.support:design:23.1.1' 26 | compile project(':yhutils') 27 | } 28 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Develop\android_SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/java/xyz/yhsj/yhutilsDemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package xyz.yhsj.yhutilsDemo; 2 | 3 | import android.os.Bundle; 4 | import android.support.design.widget.FloatingActionButton; 5 | import android.support.design.widget.Snackbar; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.support.v7.widget.Toolbar; 8 | import android.view.View; 9 | import android.view.Menu; 10 | import android.view.MenuItem; 11 | 12 | public class MainActivity extends AppCompatActivity { 13 | 14 | @Override 15 | protected void onCreate(Bundle savedInstanceState) { 16 | super.onCreate(savedInstanceState); 17 | setContentView(R.layout.activity_main); 18 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 19 | setSupportActionBar(toolbar); 20 | 21 | FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 22 | fab.setOnClickListener(new View.OnClickListener() { 23 | @Override 24 | public void onClick(View view) { 25 | Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 26 | .setAction("Action", null).show(); 27 | } 28 | }); 29 | } 30 | 31 | @Override 32 | public boolean onCreateOptionsMenu(Menu menu) { 33 | // Inflate the menu; this adds items to the action bar if it is present. 34 | getMenuInflater().inflate(R.menu.menu_main, menu); 35 | return true; 36 | } 37 | 38 | @Override 39 | public boolean onOptionsItemSelected(MenuItem item) { 40 | // Handle action bar item clicks here. The action bar will 41 | // automatically handle clicks on the Home/Up button, so long 42 | // as you specify a parent activity in AndroidManifest.xml. 43 | int id = item.getItemId(); 44 | 45 | //noinspection SimplifiableIfStatement 46 | if (id == R.id.action_settings) { 47 | return true; 48 | } 49 | 50 | return super.onOptionsItemSelected(item); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 21 | 22 | 23 | 24 | 25 | 26 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/layout/content_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 5 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yhsj0919/YHUtils/c5a633dd72fd168f0703719252830059f11cf993/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yhsj0919/YHUtils/c5a633dd72fd168f0703719252830059f11cf993/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yhsj0919/YHUtils/c5a633dd72fd168f0703719252830059f11cf993/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yhsj0919/YHUtils/c5a633dd72fd168f0703719252830059f11cf993/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yhsj0919/YHUtils/c5a633dd72fd168f0703719252830059f11cf993/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-v21/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 16dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | YHUtils 3 | Settings 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 15 | 16 |