├── assets
└── TUtils.jar
├── ic_launcher-web.png
├── libs
└── android-support-v4.jar
├── lint.xml
├── res
└── values
│ └── strings.xml
├── src
└── com
│ └── boy
│ └── tutils
│ ├── ButtonClickUtils.java
│ ├── DataUtils.java
│ ├── ActivityUtils.java
│ ├── TimerCheck.java
│ ├── ToastUtils.java
│ ├── BundleUtils.java
│ ├── AppManager.java
│ ├── CleanCacheUtils.java
│ ├── PreferencesUtils.java
│ ├── TimeUtils.java
│ ├── JsonUtils.java
│ ├── ParcelUtils.java
│ ├── SecurityUtil.java
│ ├── FileUtils.java
│ ├── ImageUtils.java
│ ├── WifiUtils.java
│ └── DeviceUtils.java
├── .classpath
├── AndroidManifest.xml
├── project.properties
├── proguard-project.txt
├── .project
└── README.md
/assets/TUtils.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pengbs/TUtils/HEAD/assets/TUtils.jar
--------------------------------------------------------------------------------
/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pengbs/TUtils/HEAD/ic_launcher-web.png
--------------------------------------------------------------------------------
/libs/android-support-v4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pengbs/TUtils/HEAD/libs/android-support-v4.jar
--------------------------------------------------------------------------------
/lint.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | PUtils
5 | Hello world!
6 | Settings
7 |
8 |
9 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/ButtonClickUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | public class ButtonClickUtils {
4 | private static long lastClickTime;
5 | public static boolean isFastDoubleClick() {
6 | long time = System.currentTimeMillis();
7 | long timeD = time - lastClickTime;
8 | if ( 0 < timeD && timeD < 500) {
9 | return true;
10 | }
11 | lastClickTime = time;
12 | return false;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
10 |
11 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-22
15 |
--------------------------------------------------------------------------------
/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | TUtils
4 |
5 |
6 |
7 |
8 |
9 | com.android.ide.eclipse.adt.ResourceManagerBuilder
10 |
11 |
12 |
13 |
14 | com.android.ide.eclipse.adt.PreCompilerBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 | com.android.ide.eclipse.adt.ApkBuilder
25 |
26 |
27 |
28 |
29 |
30 | com.android.ide.eclipse.adt.AndroidNature
31 | org.eclipse.jdt.core.javanature
32 |
33 |
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TUtils
2 | 自己整理的android中一些常用的工具类,android develop utils
3 | jar包在assets目录下,有需要的可以直接下载使用;
4 |
5 |
6 | **ActivityUtils**:activity快捷跳转,bundle可选;
7 | **AppManager**:应用程序所有activity管理类,可以获取到当前activity,指定activity,在基类BaseActivity的onCreate()中加入```AppManager.getAppManager().addActivity(this);```即可将activity加入,在程序结束时调用```AppManager.getAppManager().AppExit();```即可关闭所有activity,完全退出程序;
8 | **BundleUtils**:快捷获取activity之间传递的数据;
9 | **ButtonClickUtils**:FastDoubleClick检测;
10 | **CleanCacheUtils**:应用程序数据清理,可以一键清除所有,也可以只清除数据库、SharedPreference、file;
11 | **DataUtils**:String、List、Map等非空判断,大小获取;
12 | **DeviceUtils**:一些通用的方法,例如获取设备信息、单位转换等;
13 | **FileUtils**:文件处理,例如文件复制、删除、重命名、大小获取和单位转换;
14 | **ImageUtils**:bitmap相关,图片高质量压缩、缩放、获取图片旋转角度、旋转图片等;
15 | **JsonUtils**:根据key快速获取value;
16 | **PreferencesUtils**:SharedPreference快捷存取数据;
17 | **SecurityUtil**:MD5加密解密、3DES加密解密;
18 | **TimeUtils**:时间和date相关;
19 | **ToastUtils**:toast相关,可以防止toast重复显示;
20 | **WifiUtils**:wifi相关,创建wifi热点、连接wifi、关闭wifi等;
21 | **ParcelableUtils**:序列化存取工具类;
22 |
23 | 以后我还会持续收集和整理,欢迎pull request,一起维护增强!
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/DataUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | public class DataUtils {
7 |
8 | /**
9 | * @param sourceList
10 | * @return 获取list大小
11 | */
12 | public static int getSize(List sourceList) {
13 | return sourceList == null ? 0 : sourceList.size();
14 | }
15 |
16 | /**
17 | * @param sourceMap
18 | * @return 获取Map大小
19 | */
20 | public static int getSize(Map sourceMap) {
21 | return sourceMap == null ? 0 : sourceMap.size();
22 | }
23 |
24 | /**
25 | * @param sourceList
26 | * @return if list is null or its size is 0, return true, else return false.
27 | */
28 | public static boolean isEmpty(List sourceList) {
29 | return (sourceList == null || sourceList.size() == 0);
30 | }
31 |
32 | /**
33 | * @param sourceMap
34 | * @return if map is null or its size is 0, return true, else return false.
35 | */
36 | public static boolean isEmpty(Map sourceMap) {
37 | return (sourceMap == null || sourceMap.size() == 0);
38 | }
39 |
40 | /**
41 | * is null or its length is 0 or is "null"
42 | *
43 | * @param str
44 | */
45 | public static boolean isEmpty(String str) {
46 | return (str == null || str.length() == 0 || "null".equals(str) || str
47 | .trim().length() == 0);
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/ActivityUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 |
7 | public class ActivityUtils {
8 |
9 | /**
10 | * 通过Class跳转界面
11 | * @param cls
12 | */
13 | public static void startActivity(Activity activity, Class> cls) {
14 | if (activity == null || cls == null) {
15 | return;
16 | }
17 | startActivity(activity, cls, null);
18 | }
19 |
20 | /**
21 | * 含有Bundle通过Class跳转界面
22 | * @param cls
23 | */
24 | public static void startActivity(Activity activity, Class> cls, Bundle bundle) {
25 | if (activity == null || cls == null) {
26 | return;
27 | }
28 | Intent intent = new Intent();
29 | intent.setClass(activity, cls);
30 | if (bundle != null) {
31 | intent.putExtras(bundle);
32 | }
33 | activity.startActivity(intent);
34 | }
35 |
36 | /** 含有Bundle通过Class带result跳转界面 **/
37 | protected void startActivityForResult(Activity activity, Class> cls, Bundle bundle, int requestCode) {
38 | if (activity == null || cls == null) {
39 | return;
40 | }
41 | Intent intent = new Intent();
42 | intent.setClass(activity, cls);
43 | if (bundle != null) {
44 | intent.putExtras(bundle);
45 | }
46 | activity.startActivityForResult(intent, requestCode);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/TimerCheck.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | public abstract class TimerCheck {
4 | private int mCount = 0;
5 | private int mTimeOutCount = 1;
6 | private int mSleepTime = 1000; // 1s
7 | private boolean mExitFlag = false;
8 | private Thread mThread = null;
9 |
10 | /**
11 | * Do not process UI work in this.
12 | */
13 | public abstract void doTimerCheckWork();
14 |
15 | public abstract void doTimeOutWork();
16 |
17 | public TimerCheck() {
18 | mThread = new Thread(new Runnable() {
19 |
20 | @Override
21 | public void run() {
22 | // TODO Auto-generated method stub
23 | while (!mExitFlag) {
24 | mCount++;
25 | if (mCount < mTimeOutCount) {
26 | doTimerCheckWork();
27 | try {
28 | Thread.sleep(mSleepTime);
29 | }
30 | catch (InterruptedException e) {
31 | // TODO Auto-generated catch block
32 | e.printStackTrace();
33 | exit();
34 | }
35 | }
36 | else {
37 | doTimeOutWork();
38 | }
39 | }
40 | }
41 | });
42 | }
43 |
44 | /**
45 | * start
46 | *
47 | * @param times
48 | * How many times will check?
49 | * @param sleepTime
50 | * ms, Every check sleep time.
51 | */
52 | public void start(int timeOutCount, int sleepTime) {
53 | mTimeOutCount = timeOutCount;
54 | mSleepTime = sleepTime;
55 |
56 | mThread.start();
57 | }
58 |
59 | public void exit() {
60 | mExitFlag = true;
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/ToastUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import android.content.Context;
4 | import android.os.Looper;
5 | import android.widget.Toast;
6 |
7 | public class ToastUtils {
8 |
9 | private static Toast mToast;
10 | public static void showShortToast(Context context, int resId) {
11 | show(context, context.getResources().getText(resId), Toast.LENGTH_SHORT);
12 | }
13 |
14 | public static void showShortToast(Context context, CharSequence text) {
15 | show(context, text, Toast.LENGTH_SHORT);
16 | }
17 |
18 | public static void showLongToast(Context context, int resId) {
19 | show(context, context.getResources().getText(resId), Toast.LENGTH_LONG);
20 | }
21 |
22 | public static void showLongToast(Context context, CharSequence text) {
23 | show(context, text, Toast.LENGTH_LONG);
24 | }
25 |
26 | public static void show(Context context, CharSequence text, int duration) {
27 | if (mToast == null) {
28 | mToast = Toast.makeText(context, text, duration);
29 | }else {
30 | mToast.setText(text);
31 | mToast.setDuration(duration);
32 | }
33 | mToast.show();
34 | }
35 |
36 | public static void cancel(){
37 | if (mToast != null) {
38 | mToast.cancel();
39 | mToast = null;
40 | }
41 | }
42 |
43 | public static void showShortToast(Context context, int resId, Object... args) {
44 | show(context, String.format(context.getResources().getString(resId), args), Toast.LENGTH_SHORT);
45 | }
46 |
47 | public static void showShortToast(Context context, String format, Object... args) {
48 | show(context, String.format(format, args), Toast.LENGTH_SHORT);
49 | }
50 |
51 | public static void showLongToast(Context context, int resId, Object... args) {
52 | show(context, String.format(context.getResources().getString(resId), args), Toast.LENGTH_LONG);
53 | }
54 |
55 | public static void showLongToast(Context context, String format, Object... args) {
56 | show(context, String.format(format, args), Toast.LENGTH_LONG);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/BundleUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 |
6 | import android.os.Bundle;
7 | import android.os.Parcelable;
8 | import android.text.TextUtils;
9 |
10 | public class BundleUtils {
11 |
12 | public static String getString(Bundle bundle, String key) {
13 | return getString(bundle, key, "");
14 | }
15 |
16 | private static String getString(Bundle bundle, String key, String df) {
17 | if (df == null) {
18 | df = "";
19 | }
20 | return getValue(bundle, key, df);
21 | }
22 |
23 | public static boolean getBoolean(Bundle bundle, String key, boolean df) {
24 | return getValue(bundle, key, df);
25 | }
26 |
27 | public static int getInt(Bundle bundle, String key) {
28 | return getInt(bundle, key, 0);
29 | }
30 |
31 | public static int getInt(Bundle bundle, String key, int df) {
32 | return getValue(bundle, key, df);
33 | }
34 |
35 | public static double getDouble(Bundle bundle, String key) {
36 | return getDouble(bundle, key, 0.0);
37 | }
38 |
39 | public static double getDouble(Bundle bundle, String key, double df) {
40 | return getValue(bundle, key, df);
41 | }
42 | public static long getLong(Bundle bundle, String key) {
43 | return getLong(bundle, key, 0);
44 | }
45 |
46 | public static long getLong(Bundle bundle, String key, long df) {
47 | return getValue(bundle, key, df);
48 | }
49 |
50 | public static Parcelable getParcelable(Bundle bundle, String key) {
51 | return getValue(bundle, key, null);
52 | }
53 | public static Serializable getSerializable(Bundle bundle, String key) {
54 | return getValue(bundle, key, null);
55 | }
56 |
57 | public static ArrayList getArrayList(Bundle bundle, String key) {
58 | return getValue(bundle, key, null);
59 | }
60 |
61 | @SuppressWarnings("unchecked")
62 | public static T getValue(Bundle bundle, String key, T df) {
63 | if (bundle == null || TextUtils.isEmpty(key)) {
64 | return df;
65 | }
66 |
67 | if (df == null) {
68 | return df;
69 | }
70 |
71 | if (!bundle.containsKey(key)) {
72 | return df;
73 | }
74 | T value = df;
75 | Object obj = bundle.get(key);
76 | if (obj != null && value.getClass().isAssignableFrom(obj.getClass())) {
77 | value = (T) obj;
78 | }
79 | return value;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/AppManager.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.util.Stack;
4 |
5 | import android.app.Activity;
6 |
7 | /**
8 | * 应用程序Activity管理类:用于Activity管理和应用程序退出
9 | */
10 | public class AppManager {
11 |
12 | private static Stack activityStack;
13 | private static AppManager instance;
14 |
15 | private AppManager(){}
16 | /**
17 | * 单一实例
18 | */
19 | public static AppManager getAppManager(){
20 | if(instance==null){
21 | instance=new AppManager();
22 | }
23 | return instance;
24 | }
25 | /**
26 | * 添加Activity到堆栈
27 | */
28 | public void addActivity(Activity activity){
29 | if(activityStack==null){
30 | activityStack=new Stack();
31 | }
32 | activityStack.add(activity);
33 | }
34 | /**
35 | * 获取当前Activity(堆栈中最后一个压入的)
36 | */
37 | public Activity currentActivity(){
38 | Activity activity=activityStack.lastElement();
39 | return activity;
40 | }
41 | /**
42 | * 结束当前Activity(堆栈中最后一个压入的)
43 | */
44 | public void finishActivity(){
45 | Activity activity=activityStack.lastElement();
46 | finishActivity(activity);
47 | }
48 | /**
49 | * 结束指定的Activity
50 | */
51 | public void finishActivity(Activity activity){
52 | if(activity!=null){
53 | activityStack.remove(activity);
54 | activity.finish();
55 | activity=null;
56 | }
57 | }
58 | /**
59 | * 结束指定类名的Activity
60 | */
61 | public void finishActivity(Class> cls){
62 | for (Activity activity : activityStack) {
63 | if(activity.getClass().equals(cls) ){
64 | finishActivity(activity);
65 | }
66 | }
67 | }
68 |
69 | /**
70 | * 获取指定类名activity
71 | */
72 | public Activity getActivity(Class> cls){
73 | for (Activity activity : activityStack) {
74 | if(activity.getClass().equals(cls) ){
75 | return activity;
76 | }
77 | }
78 | return null;
79 | }
80 |
81 | /**
82 | * 退出应用程序
83 | */
84 | public void AppExit() {
85 | try {
86 | finishAllActivity();
87 | // 杀死该应用进程
88 | android.os.Process.killProcess(android.os.Process.myPid());
89 | System.exit(0);
90 | } catch (Exception e) {
91 |
92 | }
93 | }
94 |
95 | /**
96 | * 结束所有Activity
97 | */
98 | public void finishAllActivity(){
99 | for (int i = 0, size = activityStack.size(); i < size; i++){
100 | if (null != activityStack.get(i)){
101 | activityStack.get(i).finish();
102 | }
103 | }
104 | activityStack.clear();
105 | }
106 | }
--------------------------------------------------------------------------------
/src/com/boy/tutils/CleanCacheUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.io.File;
4 | import android.content.Context;
5 | import android.os.Environment;
6 |
7 | /**
8 | * 本应用数据清除管理器
9 | */
10 | public class CleanCacheUtils {
11 | /**
12 | * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
13 | *
14 | * @param context
15 | */
16 |
17 | static private int fileSize = 0;
18 |
19 |
20 | /**
21 | * 清除本应用所有的数据
22 | *
23 | * @param context
24 | * @param filepath
25 | */
26 | public static String cleanApplicationData(Context context,
27 | String... filepath) {
28 |
29 | fileSize = 0;
30 | cleanInternalCache(context);
31 | cleanExternalCache(context);
32 | cleanDatabases(context);
33 | cleanFiles(context);
34 | for (String filePath : filepath) {
35 | cleanCustomCache(filePath);
36 | }
37 | double dFileSize = (double) fileSize / (1024 * 1024);
38 | java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
39 | return df.format(dFileSize);
40 | }
41 |
42 | public static void cleanInternalCache(Context context) {
43 | deleteFilesByDirectory(context.getCacheDir());
44 | }
45 |
46 | /**
47 | * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases)
48 | *
49 | * @param context
50 | */
51 | public static void cleanDatabases(Context context) {
52 | deleteFilesByDirectory(new File("/data/data/"
53 | + context.getPackageName() + "/databases"));
54 | }
55 |
56 | /**
57 | * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
58 | *
59 | * @param context
60 | */
61 | public static void cleanSharedPreference(Context context) {
62 | deleteFilesByDirectory(new File("/data/data/"
63 | + context.getPackageName() + "/shared_prefs"));
64 | }
65 |
66 | /**
67 | * 按名字清除本应用数据库
68 | *
69 | * @param context
70 | * @param dbName
71 | */
72 | public static void cleanDatabaseByName(Context context, String dbName) {
73 | context.deleteDatabase(dbName);
74 | }
75 |
76 | /**
77 | * 清除/data/data/com.xxx.xxx/files下的内容
78 | *
79 | * @param context
80 | */
81 | public static void cleanFiles(Context context) {
82 | deleteFilesByDirectory(context.getFilesDir());
83 | }
84 |
85 | /**
86 | * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
87 | *
88 | * @param context
89 | */
90 | public static void cleanExternalCache(Context context) {
91 | if (Environment.getExternalStorageState().equals(
92 | Environment.MEDIA_MOUNTED)) {
93 | deleteFilesByDirectory(context.getExternalCacheDir());
94 | }
95 | }
96 |
97 | /**
98 | * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除
99 | *
100 | * @param filePath
101 | */
102 | public static void cleanCustomCache(String filePath) {
103 | deleteFilesByDirectory(new File(filePath));
104 | }
105 |
106 | /**
107 | * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理
108 | *
109 | * @param directory
110 | */
111 | private static void deleteFilesByDirectory(File directory) {
112 | if (directory != null && directory.exists() && directory.isDirectory()) {
113 | for (File item : directory.listFiles()) {
114 | if (item.getName().startsWith("."))
115 | continue;
116 | fileSize += item.length();
117 | item.delete();
118 | }
119 | }
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/PreferencesUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | /**
7 | * modify form Trinea
8 | * @author Trinea
9 | *
10 | */
11 | public class PreferencesUtils {
12 | public static String PREFERENCE_NAME = "TUtils";
13 |
14 | public static boolean putString(Context context, String key, String value) {
15 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
16 | SharedPreferences.Editor editor = settings.edit();
17 | editor.putString(key, value);
18 | return editor.commit();
19 | }
20 |
21 | public static String getString(Context context, String key) {
22 | return getString(context, key, null);
23 | }
24 |
25 | public static String getString(Context context, String key, String defaultValue) {
26 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
27 | return settings.getString(key, defaultValue);
28 | }
29 |
30 | public static boolean putInt(Context context, String key, int value) {
31 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
32 | SharedPreferences.Editor editor = settings.edit();
33 | editor.putInt(key, value);
34 | return editor.commit();
35 | }
36 |
37 | public static int getInt(Context context, String key) {
38 | return getInt(context, key, -1);
39 | }
40 |
41 | public static int getInt(Context context, String key, int defaultValue) {
42 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
43 | return settings.getInt(key, defaultValue);
44 | }
45 |
46 | public static boolean putLong(Context context, String key, long value) {
47 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
48 | SharedPreferences.Editor editor = settings.edit();
49 | editor.putLong(key, value);
50 | return editor.commit();
51 | }
52 |
53 | public static long getLong(Context context, String key) {
54 | return getLong(context, key, -1);
55 | }
56 |
57 | public static long getLong(Context context, String key, long defaultValue) {
58 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
59 | return settings.getLong(key, defaultValue);
60 | }
61 |
62 | public static boolean putFloat(Context context, String key, float value) {
63 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
64 | SharedPreferences.Editor editor = settings.edit();
65 | editor.putFloat(key, value);
66 | return editor.commit();
67 | }
68 |
69 | public static float getFloat(Context context, String key) {
70 | return getFloat(context, key, -1);
71 | }
72 |
73 | public static float getFloat(Context context, String key, float defaultValue) {
74 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
75 | return settings.getFloat(key, defaultValue);
76 | }
77 |
78 | public static boolean putBoolean(Context context, String key, boolean value) {
79 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
80 | SharedPreferences.Editor editor = settings.edit();
81 | editor.putBoolean(key, value);
82 | return editor.commit();
83 | }
84 |
85 | public static boolean getBoolean(Context context, String key) {
86 | return getBoolean(context, key, false);
87 | }
88 |
89 | public static boolean getBoolean(Context context, String key, boolean defaultValue) {
90 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
91 | return settings.getBoolean(key, defaultValue);
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/TimeUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.text.ParseException;
4 | import java.text.SimpleDateFormat;
5 | import java.util.Calendar;
6 | import java.util.Date;
7 |
8 | public class TimeUtils {
9 |
10 | /**
11 | * 返回指定转换格式当前系统时间
12 | */
13 | public static String getDataTime(String format) {
14 | SimpleDateFormat df = new SimpleDateFormat(format);
15 | return df.format(new Date());
16 | }
17 |
18 | /**
19 | * 将时间戳转为代表"距现在多久之前"的字符串
20 | *
21 | * @param timeStr
22 | * 时间戳
23 | * @return
24 | */
25 | public static String getStandardDate(long t) {
26 |
27 | StringBuffer sb = new StringBuffer();
28 |
29 | long time = System.currentTimeMillis() - (t * 1000);
30 | long mill = (long) Math.ceil(time / 1000);// 秒前
31 |
32 | long minute = (long) Math.ceil(time / 60 / 1000);// 分钟前
33 |
34 | long hour = (long) Math.ceil(time / 60 / 60 / 1000);// 小时
35 |
36 | long day = (long) Math.ceil(time / 24 / 60 / 60 / 1000);// 天前
37 |
38 | if (day - 1 > 0) {
39 | if (day > 7) {
40 | sb.append(getDateToString(t*1000, "yyyy/MM/dd"));
41 | }else {
42 | sb.append(day + "天前");
43 | }
44 | } else if (hour - 1 > 0) {
45 | if (hour >= 24) {
46 | sb.append("1天前");
47 | } else {
48 | sb.append(hour + "小时前");
49 | }
50 | } else if (minute - 1 > 0) {
51 | if (minute >= 60) {
52 | sb.append("1小时前");
53 | } else {
54 | sb.append(minute + "分钟前");
55 | }
56 | } else if (mill - 1 > 0) {
57 | if (mill >= 60) {
58 | sb.append("1分钟前");
59 | } else {
60 | sb.append(mill + "秒前");
61 | }
62 | } else {
63 | sb.append("刚刚");
64 | }
65 | return sb.toString();
66 | }
67 |
68 | /**
69 | * 日期格式字符串转换成时间戳
70 | *
71 | * @param date
72 | * 字符串日期
73 | * @param format
74 | * 如:yyyy-MM-dd HH:mm:ss
75 | * @return
76 | */
77 | public static long date2TimeStamp(String date_str, String format) {
78 | try {
79 | SimpleDateFormat sdf = new SimpleDateFormat(format);
80 | return sdf.parse(date_str).getTime();
81 | } catch (Exception e) {
82 | e.printStackTrace();
83 | }
84 | return 0;
85 | }
86 |
87 | /**
88 | * @param time
89 | * 时间戳
90 | * @param strFormat
91 | * 转换时间格式
92 | * @return 返回自定义格式时间
93 | */
94 | public static String getDateToString(long time, String strFormat) {
95 | Date d = new Date(time);
96 | SimpleDateFormat sf = new SimpleDateFormat(strFormat);
97 | return sf.format(d);
98 | }
99 |
100 | /**
101 | * @param pTime 字符串格式日期
102 | * @return
103 | * 判断指定日期为星期几
104 | */
105 | public static String getWeek(String pTime, String format) {
106 |
107 | String strWeek = "";
108 | SimpleDateFormat sdf = new SimpleDateFormat(format);
109 | Calendar c = Calendar.getInstance();
110 | try {
111 | c.setTime(sdf.parse(pTime));
112 | } catch (ParseException e) {
113 | e.printStackTrace();
114 | }
115 | int day = c.get(Calendar.DAY_OF_WEEK) - 1;
116 | switch (day) {
117 | case 0:
118 | strWeek = "周日";
119 | break;
120 | case 1:
121 | strWeek = "周一";
122 | break;
123 | case 2:
124 | strWeek = "周二";
125 | break;
126 | case 3:
127 | strWeek = "周三";
128 | break;
129 | case 4:
130 | strWeek = "周四";
131 | break;
132 | case 5:
133 | strWeek = "周五";
134 | break;
135 | case 6:
136 | strWeek = "周六";
137 | break;
138 | }
139 | return strWeek;
140 | }
141 |
142 | /**
143 | * @param pTime
144 | * @param format
145 | * @return
146 | * 判断当前字符串日期是否为今天
147 | */
148 | public static boolean isToday(String pTime, String format){
149 | SimpleDateFormat sdf = new SimpleDateFormat(format);
150 | String nowTime = sdf.format(new Date());
151 | try {
152 | if(sdf.parse(pTime).compareTo(sdf.parse(nowTime)) == 0){
153 | return true;
154 | }
155 | } catch (ParseException e) {
156 | e.printStackTrace();
157 | }
158 | return false;
159 | }
160 |
161 | /**
162 | * 根据年 月 获取对应的月份 天数
163 | * */
164 | public static int getDaysByYearMonth(int year, int month) {
165 | Calendar a = Calendar.getInstance();
166 | a.set(Calendar.YEAR, year);
167 | a.set(Calendar.MONTH, month - 1);
168 | a.set(Calendar.DATE, 1);
169 | a.roll(Calendar.DATE, -1);
170 | int maxDate = a.get(Calendar.DATE);
171 | return maxDate;
172 | }
173 |
174 | /**
175 | * 获取当前时间为每年第几周
176 | *
177 | * @param date
178 | * @return
179 | */
180 | public static int getWeekOfYear(Date date) {
181 | Calendar c = Calendar.getInstance();
182 | c.setFirstDayOfWeek(Calendar.MONDAY);
183 | c.setTime(date);
184 | int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
185 | week = week == 0 ? 52 : week;
186 | return week > 0 ? week : 1;
187 | }
188 |
189 | }
190 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/JsonUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import org.json.JSONArray;
4 | import org.json.JSONException;
5 | import org.json.JSONObject;
6 |
7 | import android.text.TextUtils;
8 |
9 | public class JsonUtils {
10 |
11 | public static String getString(JSONObject data, String key) {
12 | String ret = "";
13 | if (data.has(key) && !data.isNull(key)) {
14 | try {
15 | ret = data.getString(key);
16 | if (!TextUtils.isEmpty(ret)) {
17 | ret = "";
18 | }
19 | } catch (JSONException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return ret;
24 | }
25 |
26 | public static String getString(String jsonData, String key) {
27 | if (TextUtils.isEmpty(jsonData)) {
28 | return "";
29 | }
30 |
31 | try {
32 | JSONObject jsonObject = new JSONObject(jsonData);
33 | return getString(jsonObject, key);
34 | } catch (JSONException e) {
35 | e.printStackTrace();
36 | return "";
37 | }
38 | }
39 |
40 | public static long getLong(JSONObject data, String key) {
41 | long ret = 0;
42 | if (data.has(key) && !data.isNull(key)) {
43 | try {
44 | ret = data.getLong(key);
45 | } catch (JSONException e) {
46 | e.printStackTrace();
47 | }
48 | }
49 | return ret;
50 | }
51 |
52 | public static long getLong(String jsonData, String key) {
53 | if (TextUtils.isEmpty(jsonData)) {
54 | return 0;
55 | }
56 |
57 | try {
58 | JSONObject jsonObject = new JSONObject(jsonData);
59 | return getLong(jsonObject, key);
60 | } catch (JSONException e) {
61 | e.printStackTrace();
62 | return 0;
63 | }
64 | }
65 |
66 | public static int getInt(JSONObject data, String key) {
67 | int ret = 0;
68 | if (data.has(key) && !data.isNull(key)) {
69 | try {
70 | ret = data.getInt(key);
71 | } catch (JSONException e) {
72 | e.printStackTrace();
73 | }
74 | }
75 | return ret;
76 | }
77 |
78 | public static int getInt(String jsonData, String key) {
79 | if (TextUtils.isEmpty(jsonData)) {
80 | return 0;
81 | }
82 |
83 | try {
84 | JSONObject jsonObject = new JSONObject(jsonData);
85 | return getInt(jsonObject, key);
86 | } catch (JSONException e) {
87 | e.printStackTrace();
88 | return 0;
89 | }
90 | }
91 |
92 | public static boolean getBoolean(JSONObject data, String key) {
93 | boolean ret = false;
94 | if (data.has(key) && !data.isNull(key)) {
95 | try {
96 | ret = data.getBoolean(key);
97 | } catch (JSONException e) {
98 | e.printStackTrace();
99 | }
100 | }
101 | return ret;
102 | }
103 |
104 | public static boolean getBoolean(String jsonData, String key) {
105 | if (TextUtils.isEmpty(jsonData)) {
106 | return false;
107 | }
108 |
109 | try {
110 | JSONObject jsonObject = new JSONObject(jsonData);
111 | return getBoolean(jsonObject, key);
112 | } catch (JSONException e) {
113 | e.printStackTrace();
114 | return false;
115 | }
116 | }
117 |
118 | public static double getDouble(JSONObject data, String key) {
119 | double ret = 0;
120 | if (data.has(key) && !data.isNull(key)) {
121 | try {
122 | ret = data.getDouble(key);
123 | } catch (JSONException e) {
124 | e.printStackTrace();
125 | }
126 | }
127 | return ret;
128 | }
129 |
130 | public static double getDouble(String jsonData, String key) {
131 | if (TextUtils.isEmpty(jsonData)) {
132 | return 0;
133 | }
134 |
135 | try {
136 | JSONObject jsonObject = new JSONObject(jsonData);
137 | return getDouble(jsonObject, key);
138 | } catch (JSONException e) {
139 | e.printStackTrace();
140 | return 0;
141 | }
142 | }
143 |
144 | public static JSONArray getJSONArray(String jsonData, String key) {
145 | if (TextUtils.isEmpty(jsonData)) {
146 | return null;
147 | }
148 |
149 | try {
150 | JSONObject jsonObject = new JSONObject(jsonData);
151 | return getJSONArray(jsonObject, key);
152 | } catch (JSONException e) {
153 | e.printStackTrace();
154 | return null;
155 | }
156 | }
157 |
158 | public static JSONArray getJSONArray(JSONObject jsonObject, String key) {
159 | if (jsonObject == null || TextUtils.isEmpty(key)) {
160 | return null;
161 | }
162 |
163 | try {
164 | return jsonObject.getJSONArray(key);
165 | } catch (JSONException e) {
166 | e.printStackTrace();
167 | return null;
168 | }
169 | }
170 |
171 | public static JSONObject getJSONObject(JSONObject jsonObject, String key) {
172 | if (jsonObject == null || TextUtils.isEmpty(key)) {
173 | return null;
174 | }
175 |
176 | try {
177 | return jsonObject.getJSONObject(key);
178 | } catch (JSONException e) {
179 | e.printStackTrace();
180 | return null;
181 | }
182 | }
183 |
184 | public static JSONObject getJSONObject(String jsonData, String key) {
185 | if (TextUtils.isEmpty(jsonData)) {
186 | return null;
187 | }
188 |
189 | try {
190 | JSONObject jsonObject = new JSONObject(jsonData);
191 | return getJSONObject(jsonObject, key);
192 | } catch (JSONException e) {
193 | e.printStackTrace();
194 | return null;
195 | }
196 | }
197 |
198 | }
199 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/ParcelUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.sql.Date;
4 | import java.util.ArrayList;
5 | import java.util.HashMap;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 | import android.os.Parcel;
10 | import android.os.Parcelable;
11 |
12 | public class ParcelUtils {
13 | public static final int EXIST_SEPARATOR = 1;
14 | public static final int NON_SEPARATOR = 0;
15 |
16 | public ParcelUtils() {
17 | }
18 |
19 | public static void writeToParcel(Parcel out, String obj) {
20 | if(obj != null) {
21 | out.writeInt(1);
22 | out.writeString(obj);
23 | } else {
24 | out.writeInt(0);
25 | }
26 |
27 | }
28 |
29 | public static void writeToParcel(Parcel out, Long obj) {
30 | if(obj != null) {
31 | out.writeInt(1);
32 | out.writeLong(obj.longValue());
33 | } else {
34 | out.writeInt(0);
35 | }
36 |
37 | }
38 |
39 | public static void writeToParcel(Parcel out, Integer obj) {
40 | if(obj != null) {
41 | out.writeInt(1);
42 | out.writeInt(obj.intValue());
43 | } else {
44 | out.writeInt(0);
45 | }
46 |
47 | }
48 |
49 | public static void writeToParcel(Parcel out, Float obj) {
50 | if(obj != null) {
51 | out.writeInt(1);
52 | out.writeFloat(obj.floatValue());
53 | } else {
54 | out.writeInt(0);
55 | }
56 |
57 | }
58 |
59 | public static void writeToParcel(Parcel out, Map obj) {
60 | if(obj != null) {
61 | out.writeInt(1);
62 | out.writeMap(obj);
63 | } else {
64 | out.writeInt(0);
65 | }
66 |
67 | }
68 |
69 | public static void writeToParcel(Parcel out, Date obj) {
70 | if(obj != null) {
71 | out.writeInt(1);
72 | out.writeLong(obj.getTime());
73 | } else {
74 | out.writeInt(0);
75 | }
76 |
77 | }
78 |
79 | public static Float readFloatFromParcel(Parcel in) {
80 | int flag = in.readInt();
81 | return flag == 1?Float.valueOf(in.readFloat()):null;
82 | }
83 |
84 | public static Date readDateFromParcel(Parcel in) {
85 | int flag = in.readInt();
86 | return flag == 1?new Date(in.readLong()):null;
87 | }
88 |
89 | public static Integer readIntFromParcel(Parcel in) {
90 | int flag = in.readInt();
91 | return flag == 1?Integer.valueOf(in.readInt()):null;
92 | }
93 |
94 | public static Long readLongFromParcel(Parcel in) {
95 | int flag = in.readInt();
96 | return flag == 1?Long.valueOf(in.readLong()):null;
97 | }
98 |
99 | public static String readFromParcel(Parcel in) {
100 | int flag = in.readInt();
101 | return flag == 1?in.readString():null;
102 | }
103 |
104 | public static Map readMapFromParcel(Parcel in) {
105 | int flag = in.readInt();
106 | return flag == 1?in.readHashMap(HashMap.class.getClassLoader()):null;
107 | }
108 |
109 | public static T readFromParcel(Parcel in, Class cls) {
110 | int flag = in.readInt();
111 | return (T) (flag == 1?in.readParcelable(cls.getClassLoader()):null);
112 | }
113 |
114 | public static void writeToParcel(Parcel out, T model) {
115 | if(model != null) {
116 | out.writeInt(1);
117 | out.writeParcelable(model, 0);
118 | } else {
119 | out.writeInt(0);
120 | }
121 |
122 | }
123 |
124 | public static > void writeToParcel(Parcel out, T model) {
125 | if(model != null) {
126 | out.writeInt(1);
127 | out.writeList(model);
128 | } else {
129 | out.writeInt(0);
130 | }
131 |
132 | }
133 |
134 | public static ArrayList readListFromParcel(Parcel in, Class cls) {
135 | int flag = in.readInt();
136 | return flag == 1?in.readArrayList(cls.getClassLoader()):null;
137 | }
138 |
139 | public static void writeListToParcel(Parcel out, List> collection) {
140 | if(collection != null) {
141 | out.writeInt(1);
142 | out.writeList(collection);
143 | } else {
144 | out.writeInt(0);
145 | }
146 |
147 | }
148 |
149 | public static T bytesToParcelable(byte[] data, Class cls) {
150 | if(data != null && data.length != 0) {
151 | Parcel in = Parcel.obtain();
152 | in.unmarshall(data, 0, data.length);
153 | in.setDataPosition(0);
154 | Parcelable t = readFromParcel(in, cls);
155 | in.recycle();
156 | return (T) t;
157 | } else {
158 | return null;
159 | }
160 | }
161 |
162 | public static byte[] parcelableToByte(Parcelable model) {
163 | if(model == null) {
164 | return null;
165 | } else {
166 | Parcel parcel = Parcel.obtain();
167 | writeToParcel(parcel, model);
168 | return parcel.marshall();
169 | }
170 | }
171 |
172 | public static List bytesToParcelableList(byte[] data, Class cls) {
173 | if(data != null && data.length != 0) {
174 | Parcel in = Parcel.obtain();
175 | in.unmarshall(data, 0, data.length);
176 | in.setDataPosition(0);
177 | ArrayList t = readListFromParcel(in, cls);
178 | in.recycle();
179 | return t;
180 | } else {
181 | return null;
182 | }
183 | }
184 |
185 | public static byte[] parcelableListToByte(List extends Parcelable> list) {
186 | if(list == null) {
187 | return null;
188 | } else {
189 | Parcel parcel = Parcel.obtain();
190 | writeListToParcel(parcel, list);
191 | return parcel.marshall();
192 | }
193 | }
194 | }
195 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/SecurityUtil.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import android.util.Base64;
4 |
5 | import java.io.UnsupportedEncodingException;
6 | import java.security.MessageDigest;
7 | import java.security.NoSuchAlgorithmException;
8 |
9 | import javax.crypto.Cipher;
10 | import javax.crypto.SecretKey;
11 | import javax.crypto.spec.IvParameterSpec;
12 | import javax.crypto.spec.SecretKeySpec;
13 |
14 | public class SecurityUtil {
15 | private static String MD5_APPEND = "";
16 | /**
17 | * 密钥算法
18 | * */
19 | public static final String TRIPLEDES_ALGORITHM = "DESede";
20 |
21 | /**
22 | * 加密/解密算法/工作模式/填充方式
23 | * */
24 | public static final String TRIPLEDES_CIPHER_ALGORITHM = "DESede/CBC/PKCS5Padding";
25 |
26 | /**
27 |
28 | */
29 | private static String TRIPLEDES__IV = "";
30 |
31 | /**
32 |
33 | */
34 | private static String TRIPLEDES__KEY = "";
35 |
36 | /**
37 |
38 | */
39 | private static final String CHARSETNAME = "UTF-8";
40 |
41 | /**
42 | * MD5加密
43 | *
44 | * @param parameter
45 |
46 | * @return
47 | */
48 |
49 |
50 | static{
51 | StringBuilder a = new StringBuilder();
52 | StringBuilder b = new StringBuilder();
53 | StringBuilder c = new StringBuilder();
54 |
55 | a.append("a");
56 | b.append("o");
57 | c.append("4");
58 | b.append("$");
59 | b.append("q");
60 | c.append("0");
61 | c.append("3");
62 | b.append("i");
63 | b.append("t");
64 | a.append("c");
65 | a.append("i");
66 | b.append("h");
67 | a.append("t");
68 | a.append(")");
69 | b.append("1");
70 | b.append("2");
71 | a.append("_");
72 | b.append("3");
73 | a.append("(");
74 | b.append("%");
75 | a.append("&");
76 | c.append("7");
77 | b.append("4");
78 | a.append("%");
79 | b.append("9");
80 | b.append("0");
81 | c.append("2");
82 | b.append("~");
83 | a.append("*");
84 | b.append("@");
85 | b.append("#");
86 | a.append("r");
87 | a.append("t");
88 | b.append("5");
89 | b.append("6");
90 | a.append("y");
91 | b.append("7");
92 | b.append("8");
93 | c.append("5");
94 | a.append("^");
95 | c.append("6");
96 | b.append("e");
97 | b.append("c");
98 | a.append("s");
99 | b.append("h");
100 | a.append("m");
101 | c.append("1");
102 | b.append("a");
103 |
104 | MD5_APPEND = a.toString();
105 | TRIPLEDES__KEY = b.toString();
106 | TRIPLEDES__IV = c.toString();
107 | }
108 |
109 |
110 | public static String md5(String parameter) {
111 | byte[] hash;
112 | try {
113 | hash = MessageDigest.getInstance("MD5").digest((parameter + MD5_APPEND).getBytes("UTF-8"));
114 | } catch (NoSuchAlgorithmException e) {
115 | throw new RuntimeException("Huh, MD5 should be supported?", e);
116 | } catch (UnsupportedEncodingException e) {
117 | throw new RuntimeException("Huh, UTF-8 should be supported?", e);
118 | }
119 |
120 | StringBuilder hex = new StringBuilder(hash.length * 2);
121 | for (byte b : hash) {
122 | if ((b & 0xFF) < 0x10)
123 | hex.append("0");
124 | hex.append(Integer.toHexString(b & 0xFF));
125 | }
126 |
127 | return hex.toString();
128 | }
129 |
130 | public static String md5(String parameter,String strAppend) {
131 | byte[] hash;
132 | try {
133 | hash = MessageDigest.getInstance("MD5").digest((parameter + strAppend).getBytes("UTF-8"));
134 | } catch (NoSuchAlgorithmException e) {
135 | throw new RuntimeException("Huh, MD5 should be supported?", e);
136 | } catch (UnsupportedEncodingException e) {
137 | throw new RuntimeException("Huh, UTF-8 should be supported?", e);
138 | }
139 |
140 | StringBuilder hex = new StringBuilder(hash.length * 2);
141 | for (byte b : hash) {
142 | if ((b & 0xFF) < 0x10)
143 | hex.append("0");
144 | hex.append(Integer.toHexString(b & 0xFF));
145 | }
146 |
147 | return hex.toString();
148 | }
149 |
150 |
151 | /**
152 | * 3DES加密
153 | *
154 | * @param clearText
155 | * 明文
156 | * @return
157 | * @throws Exception
158 | */
159 | public static String encrypt(byte[] clearText) {
160 | try {
161 | SecretKey deskey = new SecretKeySpec(TRIPLEDES__KEY.getBytes(CHARSETNAME), TRIPLEDES_ALGORITHM);
162 | Cipher c1 = Cipher.getInstance(TRIPLEDES_CIPHER_ALGORITHM);
163 | IvParameterSpec ips = new IvParameterSpec(TRIPLEDES__IV.getBytes(CHARSETNAME));
164 | c1.init(Cipher.ENCRYPT_MODE, deskey, ips);
165 | return Base64.encodeToString(c1.doFinal(clearText), Base64.NO_WRAP);
166 | } catch (Exception e) {
167 | }
168 | return null;
169 | }
170 |
171 | /**
172 | * 3DES加密
173 | * @param clearText
174 | * @param TRIPLEDES__KEY
175 | * @return
176 | */
177 | public static String encrypt(byte[] clearText,String TRIPLEDES__KEY) {
178 | try {
179 | SecretKey deskey = new SecretKeySpec(TRIPLEDES__KEY.getBytes(CHARSETNAME), TRIPLEDES_ALGORITHM);
180 | Cipher c1 = Cipher.getInstance(TRIPLEDES_CIPHER_ALGORITHM);
181 | IvParameterSpec ips = new IvParameterSpec(TRIPLEDES__IV.getBytes(CHARSETNAME));
182 | c1.init(Cipher.ENCRYPT_MODE, deskey, ips);
183 | return Base64.encodeToString(c1.doFinal(clearText), Base64.NO_WRAP);
184 | } catch (Exception e) {
185 | }
186 | return null;
187 | }
188 |
189 |
190 | /**
191 | * 3DES加密
192 | * @param clearText
193 | * @param TRIPLEDES__KEY
194 | * @param TRIPLEDES__IV
195 | * @return
196 | */
197 | public static String encrypt(byte[] clearText,String TRIPLEDES__KEY,String TRIPLEDES__IV) {
198 | try {
199 | SecretKey deskey = new SecretKeySpec(TRIPLEDES__KEY.getBytes(CHARSETNAME), TRIPLEDES_ALGORITHM);
200 | Cipher c1 = Cipher.getInstance(TRIPLEDES_CIPHER_ALGORITHM);
201 | IvParameterSpec ips = new IvParameterSpec(TRIPLEDES__IV.getBytes(CHARSETNAME));
202 | c1.init(Cipher.ENCRYPT_MODE, deskey, ips);
203 | return Base64.encodeToString(c1.doFinal(clearText), Base64.NO_WRAP);
204 | } catch (Exception e) {
205 | e.printStackTrace();
206 | }
207 | return null;
208 | }
209 |
210 |
211 | /**
212 | * 3DES解密
213 | *
214 | * @param cipherText
215 | * 密文
216 | * @return
217 | * @throws Exception
218 | */
219 | public static byte[] decrypt(byte[] cipherText) {
220 | try {
221 | SecretKey deskey = new SecretKeySpec(TRIPLEDES__KEY.getBytes(CHARSETNAME), TRIPLEDES_ALGORITHM);
222 | Cipher c1 = Cipher.getInstance(TRIPLEDES_CIPHER_ALGORITHM);
223 | IvParameterSpec ips = new IvParameterSpec(TRIPLEDES__IV.getBytes(CHARSETNAME));
224 | c1.init(Cipher.DECRYPT_MODE, deskey, ips);
225 | return c1.doFinal(cipherText);
226 | } catch (Exception e) {
227 | e.printStackTrace();
228 | }
229 | return null;
230 | }
231 |
232 | /**
233 | * 3DES解密
234 | *
235 | * @param cipherText
236 | * 密文
237 | * @return
238 | * @throws Exception
239 | */
240 | public static byte[] decrypt(byte[] cipherText,String TRIPLEDES__KEY,String TRIPLEDES__IV) {
241 | try {
242 | SecretKey deskey = new SecretKeySpec(TRIPLEDES__KEY.getBytes(CHARSETNAME), TRIPLEDES_ALGORITHM);
243 | Cipher c1 = Cipher.getInstance(TRIPLEDES_CIPHER_ALGORITHM);
244 | IvParameterSpec ips = new IvParameterSpec(TRIPLEDES__IV.getBytes(CHARSETNAME));
245 | c1.init(Cipher.DECRYPT_MODE, deskey, ips);
246 | return c1.doFinal(Base64.decode(cipherText, Base64.NO_WRAP));
247 | } catch (Exception e) {
248 | e.printStackTrace();
249 | }
250 | return null;
251 | }
252 | }
--------------------------------------------------------------------------------
/src/com/boy/tutils/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.io.ByteArrayOutputStream;
4 | import java.io.File;
5 | import java.io.FileInputStream;
6 | import java.io.FileNotFoundException;
7 | import java.io.FileOutputStream;
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.text.NumberFormat;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | import android.os.Environment;
15 | import android.text.TextUtils;
16 |
17 | public class FileUtils {
18 | private static final int M1024 = 1024;
19 | private static final int M8192 = 8192;
20 | private static final int M5 = 5;
21 | public static String SDPATH = Environment.getExternalStorageDirectory()
22 | + "/formats/";
23 |
24 | /**
25 | * 获取文件名称
26 | *
27 | * @param filePath
28 | * @return
29 | */
30 | public static String getFileName(String filePath) {
31 | if (TextUtils.isEmpty(filePath)) {
32 | return filePath;
33 | }
34 |
35 | int filePosi = filePath.lastIndexOf(File.separator);
36 | return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
37 | }
38 |
39 | /**
40 | * 获取文件夹名称
41 | *
42 | * @param filePath
43 | * @return
44 | */
45 | public static String getFolderName(String filePath) {
46 |
47 | if (TextUtils.isEmpty(filePath)) {
48 | return filePath;
49 | }
50 |
51 | int filePosi = filePath.lastIndexOf(File.separator);
52 | return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
53 | }
54 |
55 | /**
56 | * 创建文件夹
57 | *
58 | * @param filePath
59 | * @return
60 | */
61 | public static boolean makeDirs(String filePath) {
62 | String folderName = getFolderName(filePath);
63 | if (TextUtils.isEmpty(folderName)) {
64 | return false;
65 | }
66 |
67 | File folder = new File(folderName);
68 | return (folder.exists() && folder.isDirectory()) ? true : folder
69 | .mkdirs();
70 | }
71 |
72 | /**
73 | * 文件是否存在
74 | *
75 | * @param filePath
76 | * @return
77 | */
78 | public static boolean isFileExist(String filePath) {
79 | if (TextUtils.isEmpty(filePath)) {
80 | return false;
81 | }
82 |
83 | File file = new File(filePath);
84 | return (file.exists() && file.isFile());
85 | }
86 |
87 | /**
88 | * Indicates if this file represents a directory on the underlying file
89 | * system.
90 | *
91 | * @param directoryPath
92 | * @return
93 | */
94 | public static boolean isFolderExist(String directoryPath) {
95 | if (TextUtils.isEmpty(directoryPath)) {
96 | return false;
97 | }
98 |
99 | File dire = new File(directoryPath);
100 | return (dire.exists() && dire.isDirectory());
101 | }
102 |
103 | /**
104 | * 删除文件
105 | *
106 | * @param path
107 | * @return
108 | */
109 | public static boolean deleteFile(String path) {
110 | if (TextUtils.isEmpty(path)) {
111 | return true;
112 | }
113 |
114 | File file = new File(path);
115 | if (!file.exists()) {
116 | return true;
117 | }
118 | if (file.isFile()) {
119 | return file.delete();
120 | }
121 | if (!file.isDirectory()) {
122 | return false;
123 | }
124 | for (File f : file.listFiles()) {
125 | if (f.isFile()) {
126 | f.delete();
127 | } else if (f.isDirectory()) {
128 | deleteFile(f.getAbsolutePath());
129 | }
130 | }
131 | return file.delete();
132 | }
133 |
134 | /**
135 | * 创建不能被系统图库等扫描出来的文件夹
136 | *
137 | * @param strPath
138 | */
139 | public static void createNoMediaFile(String strPath) {
140 | File fHide = new File(strPath, ".nomedia");
141 | if (!fHide.exists()) {
142 | try {
143 | fHide.createNewFile();
144 | } catch (IOException e) {
145 |
146 | }
147 | }
148 | }
149 |
150 | /*
151 | * 文件转换为字符数组
152 | */
153 | public static byte[] getBytes(String filePath) {
154 | byte[] buffer = null;
155 | try {
156 | File file = new File(filePath);
157 | FileInputStream fis = new FileInputStream(file);
158 | ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
159 | byte[] b = new byte[1024];
160 | int n;
161 | while ((n = fis.read(b)) != -1) {
162 | bos.write(b, 0, n);
163 | }
164 | fis.close();
165 | bos.close();
166 | buffer = bos.toByteArray();
167 | } catch (FileNotFoundException e) {
168 | e.printStackTrace();
169 | } catch (IOException e) {
170 | e.printStackTrace();
171 | }
172 | return buffer;
173 | }
174 |
175 | /**
176 | * 获取文件大小
177 | *
178 | * @param fileName
179 | * @return
180 | */
181 | public static long getFileSize(String fileName) {
182 | if (TextUtils.isEmpty(fileName)) {
183 | return 0;
184 | }
185 | File file = new File(fileName);
186 | if (!file.exists()) {
187 | return 0;
188 | }
189 | long size = 0;
190 | if (file.isDirectory()) {
191 | long subSize = 0;
192 | File[] subFiles = file.listFiles();
193 | if (subFiles != null && subFiles.length != 0) {
194 | for (File subFile : subFiles) {
195 | subSize += getFileSize(subFile.getAbsolutePath());
196 | }
197 | }
198 | size += subSize;
199 | } else {
200 | size = file.length();
201 | }
202 | return size;
203 | }
204 |
205 | public static String formatFileSize(long size) {
206 | String result = "";
207 | if (size >= M1024 * M1024 * M1024) {
208 | // 保留一位小数
209 | NumberFormat nf = NumberFormat.getInstance();
210 | nf.setMaximumFractionDigits(1);
211 | result = nf
212 | .format((double) size / (double) (M1024 * M1024 * M1024))
213 | + "GB";
214 | } else if (size >= M1024 * M1024) {
215 | NumberFormat nf = NumberFormat.getInstance();
216 | nf.setMaximumFractionDigits(1);
217 | result = nf.format((double) size / (double) (M1024 * M1024)) + "MB";
218 | } else if (size >= M1024) {
219 | size /= M1024;
220 | result = String.valueOf(size) + "KB";
221 | } else {
222 | result = String.valueOf(size) + "Byt";
223 | }
224 | return result;
225 | }
226 |
227 | /**
228 | * 重命名文件
229 | *
230 | * @param srcFile
231 | * @param newName
232 | * @return
233 | */
234 | public static File renameFile(File srcFile, String newName) {
235 | if (srcFile == null || TextUtils.isEmpty(newName)) {
236 | return null;
237 | }
238 | File renamedFile = new File(srcFile.getParentFile(), newName);
239 | return srcFile.renameTo(renamedFile) ? renamedFile : null;
240 | }
241 |
242 | /**
243 | * 复制单个文件
244 | *
245 | * @param oldPath
246 | * String 原文件路径 如:c:/fqf.txt
247 | * @param newPath
248 | * String 复制后路径 如:f:/fqf.txt
249 | * @return boolean
250 | */
251 | public static boolean copyFile(String oldPath, String newPath) {
252 | boolean ret = false;
253 | InputStream inStream = null;
254 | FileOutputStream fs = null;
255 |
256 | try {
257 | int byteread = 0;
258 | File oldfile = new File(oldPath);
259 | if (oldfile.exists()) { // 文件存在时
260 | // 判断目的目录是否存在
261 | File newFile = new File(newPath);
262 | if (!newFile.getParentFile().exists()) {
263 | newFile.getParentFile().mkdirs();
264 | }
265 | if (oldfile.getPath().equals(newFile.getPath())) {
266 | // 是同一个文件
267 | return true;
268 | }
269 | inStream = new FileInputStream(oldPath); // 读入原文件
270 | fs = new FileOutputStream(newPath);
271 | byte[] buffer = new byte[M8192];
272 | while ((byteread = inStream.read(buffer)) != -1) {
273 | fs.write(buffer, 0, byteread);
274 | }
275 | ret = true;
276 | }
277 | } catch (Exception e) {
278 | e.printStackTrace();
279 | } finally {
280 | if (inStream != null) {
281 | try {
282 | inStream.close();
283 | } catch (IOException e) {
284 | e.printStackTrace();
285 | }
286 | }
287 | if (fs != null) {
288 | try {
289 | fs.close();
290 | } catch (IOException e) {
291 | e.printStackTrace();
292 | }
293 | }
294 | }
295 | return ret;
296 | }
297 |
298 | /**
299 | * 复制整个文件夹内容
300 | *
301 | * @param oldPath
302 | * String 原文件路径 如:c:/fqf
303 | * @param newPath
304 | * String 复制后路径 如:f:/fqf/ff
305 | * @return boolean
306 | */
307 | public static boolean copyFolder(String oldPath, String newPath) {
308 | boolean ret = true;
309 | try {
310 | (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
311 | File a = new File(oldPath);
312 | String[] file = a.list();
313 | File temp = null;
314 | for (int i = 0; i < file.length; i++) {
315 | if (oldPath.endsWith(File.separator)) {
316 | temp = new File(oldPath + file[i]);
317 | } else {
318 | temp = new File(oldPath + File.separator + file[i]);
319 | }
320 |
321 | if (temp.isFile()) {
322 | FileInputStream input = new FileInputStream(temp);
323 | FileOutputStream output = new FileOutputStream(newPath
324 | + "/" + (temp.getName()).toString());
325 | byte[] b = new byte[M1024 * M5];
326 | int len;
327 | while ((len = input.read(b)) != -1) {
328 | output.write(b, 0, len);
329 | }
330 | output.flush();
331 | output.close();
332 | input.close();
333 | }
334 | if (temp.isDirectory()) {
335 | // 如果是子文件夹
336 | ret = copyFolder(oldPath + "/" + file[i], newPath + "/"
337 | + file[i]);
338 | }
339 | }
340 | } catch (Exception e) {
341 | e.printStackTrace();
342 | ret = false;
343 | }
344 | return ret;
345 | }
346 |
347 | /***
348 | * 获取文件扩展名
349 | *
350 | * @param filename
351 | * @return 返回文件扩展名
352 | */
353 | public static String getExtensionName(String filename) {
354 | if ((filename != null) && (filename.length() > 0)) {
355 | int dot = filename.lastIndexOf('.');
356 | if ((dot > -1) && (dot < (filename.length() - 1))) {
357 | return filename.substring(dot + 1);
358 | }
359 | }
360 | return filename;
361 | }
362 |
363 | /**
364 | * 获取一个文件夹下的所有文件
365 | *
366 | * @param root
367 | * @return
368 | */
369 | public static List listPathFiles(String root) {
370 | List allDir = new ArrayList();
371 | SecurityManager checker = new SecurityManager();
372 | File path = new File(root);
373 | checker.checkRead(root);
374 | File[] files = path.listFiles();
375 | for (File f : files) {
376 | if (f.isFile())
377 | allDir.add(f);
378 | else
379 | listPath(f.getAbsolutePath());
380 | }
381 | return allDir;
382 | }
383 |
384 | /**
385 | * 列出root目录下所有子目录
386 | *
387 | * @param path
388 | * @return 绝对路径
389 | */
390 | public static List listPath(String root) {
391 | List allDir = new ArrayList();
392 | SecurityManager checker = new SecurityManager();
393 | File path = new File(root);
394 | checker.checkRead(root);
395 | // 过滤掉以.开始的文件夹
396 | if (path.isDirectory()) {
397 | for (File f : path.listFiles()) {
398 | if (f.isDirectory() && !f.getName().startsWith(".")) {
399 | allDir.add(f.getAbsolutePath());
400 | }
401 | }
402 | }
403 | return allDir;
404 | }
405 | }
406 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/ImageUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.io.BufferedInputStream;
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.FileOutputStream;
8 | import java.io.IOException;
9 | import java.io.OutputStream;
10 |
11 | import android.annotation.SuppressLint;
12 | import android.content.Context;
13 | import android.content.Intent;
14 | import android.graphics.Bitmap;
15 | import android.graphics.BitmapFactory;
16 | import android.graphics.Matrix;
17 | import android.graphics.Bitmap.CompressFormat;
18 | import android.graphics.drawable.BitmapDrawable;
19 | import android.graphics.drawable.Drawable;
20 | import android.media.ExifInterface;
21 | import android.net.Uri;
22 | import android.os.Build.VERSION;
23 | import android.renderscript.Allocation;
24 | import android.renderscript.Element;
25 | import android.renderscript.RenderScript;
26 | import android.renderscript.ScriptIntrinsicBlur;
27 | import android.text.TextUtils;
28 |
29 | public class ImageUtils {
30 |
31 | /**
32 | * convert Bitmap to byte array
33 | */
34 | public static byte[] bitmapToByte(Bitmap b) {
35 | if (b == null) {
36 | return null;
37 | }
38 |
39 | ByteArrayOutputStream o = new ByteArrayOutputStream();
40 | b.compress(Bitmap.CompressFormat.PNG, 100, o);
41 | return o.toByteArray();
42 | }
43 |
44 | /**
45 | * convert byte array to Bitmap
46 | *
47 | * @param b
48 | * @return
49 | */
50 | public static Bitmap byteToBitmap(byte[] b) {
51 | return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);
52 | }
53 |
54 | /**
55 | * convert Drawable to Bitmap
56 | *
57 | * @param d
58 | * @return
59 | */
60 | public static Bitmap drawableToBitmap(Drawable d) {
61 | return d == null ? null : ((BitmapDrawable)d).getBitmap();
62 | }
63 |
64 | /**
65 | * convert Bitmap to Drawable
66 | *
67 | * @param b
68 | * @return
69 | */
70 | public static Drawable bitmapToDrawable(Bitmap b) {
71 | return b == null ? null : new BitmapDrawable(b);
72 | }
73 |
74 | /**
75 | * convert Drawable to byte array
76 | *
77 | * @param d
78 | * @return
79 | */
80 | public static byte[] drawableToByte(Drawable d) {
81 | return bitmapToByte(drawableToBitmap(d));
82 | }
83 |
84 | /**
85 | * convert byte array to Drawable
86 | *
87 | * @param b
88 | * @return
89 | */
90 | public static Drawable byteToDrawable(byte[] b) {
91 | return bitmapToDrawable(byteToBitmap(b));
92 | }
93 |
94 | /**
95 | * 压缩图片
96 | * @param pa
97 | * @param width
98 | * @param height
99 | * @return
100 | * @throws IOException
101 | */
102 | public static Bitmap revitionImageSize(String path, int width, int height) throws IOException {
103 | BufferedInputStream in = new BufferedInputStream(new FileInputStream(
104 | new File(path)));
105 | BitmapFactory.Options options = new BitmapFactory.Options();
106 | options.inJustDecodeBounds = true;
107 | BitmapFactory.decodeStream(in, null, options);
108 | in.close();
109 | int i = 0;
110 | Bitmap bitmap = null;
111 | while (true) {
112 | if ((options.outWidth >> i <= width)
113 | && (options.outHeight >> i <= height)) {
114 | in = new BufferedInputStream(
115 | new FileInputStream(new File(path)));
116 | options.inSampleSize = (int) Math.pow(2.0D, i);
117 | options.inJustDecodeBounds = false;
118 | bitmap = BitmapFactory.decodeStream(in, null, options);
119 | break;
120 | }
121 | i += 1;
122 | }
123 | return bitmap;
124 | }
125 |
126 | /***
127 | * 等比例压缩图片
128 | *
129 | * @param bitmap
130 | * @param screenWidth
131 | * @param screenHight
132 | * @return
133 | */
134 | public static Bitmap getScaleBitmap(Bitmap bitmap, int screenWidth, int screenHight) {
135 | int w = bitmap.getWidth();
136 | int h = bitmap.getHeight();
137 | Matrix matrix = new Matrix();
138 | float scale = (float) screenWidth / w;
139 | float scale2 = (float) screenHight / h;
140 | scale = scale < scale2 ? scale : scale2;
141 |
142 | // 保证图片不变形.
143 | matrix.postScale(scale, scale);
144 | // w,h是原图的属性.
145 | return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
146 | }
147 |
148 | /**
149 | * scale image
150 | */
151 | public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) {
152 | if (org == null) {
153 | return null;
154 | }
155 | Matrix matrix = new Matrix();
156 | matrix.postScale(scaleWidth, scaleHeight);
157 | return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
158 | }
159 |
160 |
161 | /**
162 | * 模糊处理
163 | * @param sentBitmap
164 | * @param radius
165 | * @return
166 | */
167 | @SuppressLint("NewApi")
168 | public static Bitmap fastblur(Context mContext, Bitmap sentBitmap, int radius) {
169 |
170 | Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
171 |
172 | if (radius < 1 || mContext == null) {
173 | return (null);
174 | }
175 | if (VERSION.SDK_INT > 16) {
176 | RenderScript rs = RenderScript.create(mContext);
177 | Allocation allIn = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE,
178 | Allocation.USAGE_SCRIPT);
179 | Allocation allOut = Allocation.createTyped(rs, allIn.getType());
180 | ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
181 | blurScript.setRadius(radius);
182 | blurScript.setInput(allIn);
183 | blurScript.forEach(allOut);
184 | allOut.copyTo(bitmap);
185 | rs.destroy();
186 | return bitmap;
187 | }
188 |
189 | int w = bitmap.getWidth();
190 | int h = bitmap.getHeight();
191 |
192 | int[] pix = new int[w * h];
193 | bitmap.getPixels(pix, 0, w, 0, 0, w, h);
194 |
195 | int wm = w - 1;
196 | int hm = h - 1;
197 | int wh = w * h;
198 | int div = radius + radius + 1;
199 |
200 | int r[] = new int[wh];
201 | int g[] = new int[wh];
202 | int b[] = new int[wh];
203 | int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
204 | int vmin[] = new int[Math.max(w, h)];
205 |
206 | int divsum = (div + 1) >> 1;
207 | divsum *= divsum;
208 | int dv[] = new int[256 * divsum];
209 | for (i = 0; i < 256 * divsum; i++) {
210 | dv[i] = (i / divsum);
211 | }
212 |
213 | yw = yi = 0;
214 |
215 | int[][] stack = new int[div][3];
216 | int stackpointer;
217 | int stackstart;
218 | int[] sir;
219 | int rbs;
220 | int r1 = radius + 1;
221 | int routsum, goutsum, boutsum;
222 | int rinsum, ginsum, binsum;
223 |
224 | for (y = 0; y < h; y++) {
225 | rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
226 | for (i = -radius; i <= radius; i++) {
227 | p = pix[yi + Math.min(wm, Math.max(i, 0))];
228 | sir = stack[i + radius];
229 | sir[0] = (p & 0xff0000) >> 16;
230 | sir[1] = (p & 0x00ff00) >> 8;
231 | sir[2] = (p & 0x0000ff);
232 | rbs = r1 - Math.abs(i);
233 | rsum += sir[0] * rbs;
234 | gsum += sir[1] * rbs;
235 | bsum += sir[2] * rbs;
236 | if (i > 0) {
237 | rinsum += sir[0];
238 | ginsum += sir[1];
239 | binsum += sir[2];
240 | } else {
241 | routsum += sir[0];
242 | goutsum += sir[1];
243 | boutsum += sir[2];
244 | }
245 | }
246 | stackpointer = radius;
247 |
248 | for (x = 0; x < w; x++) {
249 |
250 | r[yi] = dv[rsum];
251 | g[yi] = dv[gsum];
252 | b[yi] = dv[bsum];
253 |
254 | rsum -= routsum;
255 | gsum -= goutsum;
256 | bsum -= boutsum;
257 |
258 | stackstart = stackpointer - radius + div;
259 | sir = stack[stackstart % div];
260 |
261 | routsum -= sir[0];
262 | goutsum -= sir[1];
263 | boutsum -= sir[2];
264 |
265 | if (y == 0) {
266 | vmin[x] = Math.min(x + radius + 1, wm);
267 | }
268 | p = pix[yw + vmin[x]];
269 |
270 | sir[0] = (p & 0xff0000) >> 16;
271 | sir[1] = (p & 0x00ff00) >> 8;
272 | sir[2] = (p & 0x0000ff);
273 |
274 | rinsum += sir[0];
275 | ginsum += sir[1];
276 | binsum += sir[2];
277 |
278 | rsum += rinsum;
279 | gsum += ginsum;
280 | bsum += binsum;
281 |
282 | stackpointer = (stackpointer + 1) % div;
283 | sir = stack[(stackpointer) % div];
284 |
285 | routsum += sir[0];
286 | goutsum += sir[1];
287 | boutsum += sir[2];
288 |
289 | rinsum -= sir[0];
290 | ginsum -= sir[1];
291 | binsum -= sir[2];
292 |
293 | yi++;
294 | }
295 | yw += w;
296 | }
297 | for (x = 0; x < w; x++) {
298 | rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
299 | yp = -radius * w;
300 | for (i = -radius; i <= radius; i++) {
301 | yi = Math.max(0, yp) + x;
302 |
303 | sir = stack[i + radius];
304 |
305 | sir[0] = r[yi];
306 | sir[1] = g[yi];
307 | sir[2] = b[yi];
308 |
309 | rbs = r1 - Math.abs(i);
310 |
311 | rsum += r[yi] * rbs;
312 | gsum += g[yi] * rbs;
313 | bsum += b[yi] * rbs;
314 |
315 | if (i > 0) {
316 | rinsum += sir[0];
317 | ginsum += sir[1];
318 | binsum += sir[2];
319 | } else {
320 | routsum += sir[0];
321 | goutsum += sir[1];
322 | boutsum += sir[2];
323 | }
324 |
325 | if (i < hm) {
326 | yp += w;
327 | }
328 | }
329 | yi = x;
330 | stackpointer = radius;
331 | for (y = 0; y < h; y++) {
332 | pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
333 |
334 | rsum -= routsum;
335 | gsum -= goutsum;
336 | bsum -= boutsum;
337 |
338 | stackstart = stackpointer - radius + div;
339 | sir = stack[stackstart % div];
340 |
341 | routsum -= sir[0];
342 | goutsum -= sir[1];
343 | boutsum -= sir[2];
344 |
345 | if (x == 0) {
346 | vmin[y] = Math.min(y + r1, hm) * w;
347 | }
348 | p = x + vmin[y];
349 |
350 | sir[0] = r[p];
351 | sir[1] = g[p];
352 | sir[2] = b[p];
353 |
354 | rinsum += sir[0];
355 | ginsum += sir[1];
356 | binsum += sir[2];
357 |
358 | rsum += rinsum;
359 | gsum += ginsum;
360 | bsum += binsum;
361 |
362 | stackpointer = (stackpointer + 1) % div;
363 | sir = stack[stackpointer];
364 |
365 | routsum += sir[0];
366 | goutsum += sir[1];
367 | boutsum += sir[2];
368 |
369 | rinsum -= sir[0];
370 | ginsum -= sir[1];
371 | binsum -= sir[2];
372 |
373 | yi += w;
374 | }
375 | }
376 |
377 | bitmap.setPixels(pix, 0, w, 0, 0, w, h);
378 | return (bitmap);
379 | }
380 |
381 | /**
382 | * 获取本地图片旋转角度
383 | * @param path
384 | * @return
385 | */
386 | public static int getBitmapDegree(String path) {
387 | int degree = 0;
388 | try {
389 | // 从指定路径下读取图片,并获取其EXIF信息
390 | ExifInterface exifInterface = new ExifInterface(path);
391 | // 获取图片的旋转信息
392 | int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
393 | ExifInterface.ORIENTATION_NORMAL);
394 | switch (orientation) {
395 | case ExifInterface.ORIENTATION_ROTATE_90:
396 | degree = 90;
397 | break;
398 | case ExifInterface.ORIENTATION_ROTATE_180:
399 | degree = 180;
400 | break;
401 | case ExifInterface.ORIENTATION_ROTATE_270:
402 | degree = 270;
403 | break;
404 | }
405 | } catch (IOException e) {
406 | e.printStackTrace();
407 | }
408 | return degree;
409 | }
410 |
411 | /**
412 | * 旋转图片
413 | * @param bm
414 | * @param degree
415 | * @return
416 | */
417 | public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
418 | Bitmap returnBm = null;
419 |
420 | // 根据旋转角度,生成旋转矩阵
421 | Matrix matrix = new Matrix();
422 | matrix.postRotate(degree);
423 | try {
424 | // 将原始图片按照旋转矩阵进行旋转,并得到新的图片
425 | returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
426 | } catch (OutOfMemoryError e) {
427 | }
428 | if (returnBm == null) {
429 | returnBm = bm;
430 | }
431 | if (bm != returnBm) {
432 | bm.recycle();
433 | }
434 | return returnBm;
435 | }
436 |
437 | /**
438 | * 保存bitmap到本地
439 | * @param bmp
440 | * @return
441 | */
442 | public static boolean saveBitmap2file(Bitmap bmp, String filePath, int quality) {
443 | if (TextUtils.isEmpty(filePath)) {
444 | return false;
445 | }
446 | CompressFormat format = Bitmap.CompressFormat.JPEG;
447 | OutputStream stream = null;
448 | try {
449 | File file = new File(filePath);
450 | if(file != null && !file.exists())
451 | file.mkdirs();
452 |
453 | stream = new FileOutputStream(file);
454 | return bmp.compress(format, quality, stream);
455 | } catch (Exception e) {
456 |
457 | }finally{
458 | try {
459 | stream.close();
460 | if (bmp != null && !bmp.isRecycled()) {
461 | bmp.recycle();
462 | bmp = null;
463 | }
464 | } catch (IOException e) {
465 | e.printStackTrace();
466 | }
467 | }
468 | return false;
469 | }
470 |
471 | /**
472 | * 让Gallery上能马上看到该图片
473 | */
474 | public static void scanPhoto(Context ctx, String strFilePath) {
475 | Intent mediaScanIntent = new Intent(
476 | Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
477 | File file = new File(strFilePath);
478 | Uri contentUri = Uri.fromFile(file);
479 | mediaScanIntent.setData(contentUri);
480 | ctx.sendBroadcast(mediaScanIntent);
481 | }
482 |
483 | }
484 |
--------------------------------------------------------------------------------
/src/com/boy/tutils/WifiUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.io.IOException;
4 | import java.lang.reflect.Field;
5 | import java.lang.reflect.InvocationTargetException;
6 | import java.lang.reflect.Method;
7 | import java.net.InetAddress;
8 | import java.net.InterfaceAddress;
9 | import java.net.NetworkInterface;
10 | import java.net.SocketException;
11 | import java.util.Enumeration;
12 | import java.util.List;
13 | import org.apache.http.conn.util.InetAddressUtils;
14 | import android.annotation.SuppressLint;
15 | import android.content.Context;
16 | import android.net.ConnectivityManager;
17 | import android.net.DhcpInfo;
18 | import android.net.NetworkInfo;
19 | import android.net.wifi.ScanResult;
20 | import android.net.wifi.WifiConfiguration;
21 | import android.net.wifi.WifiInfo;
22 | import android.net.wifi.WifiManager;
23 | import android.os.Handler;
24 | import android.os.Message;
25 | import android.telephony.TelephonyManager;
26 |
27 | /**
28 | * Wifi 工具类
29 | *
30 | * 封装了Wifi的基础操作方法,方便获取Wifi连接信息以及操作Wifi
31 | */
32 |
33 | public class WifiUtils {
34 | public final int ApCreateApSuccess = 3; // 创建热点成功
35 | private Context mContext;
36 | private WifiManager mWifiManager;
37 |
38 | public WifiUtils(Context context) {
39 | this.mContext = context.getApplicationContext();
40 | mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
41 | }
42 |
43 | public static enum WifiCipherType {
44 | WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
45 | }
46 |
47 | /**
48 | * 创建热点
49 | * @param ssid
50 | * @param passwd
51 | * @param handler
52 | */
53 | public void startWifiAp(String ssid, String passwd, final Handler handler) {
54 | if (mWifiManager.isWifiEnabled()) {
55 | mWifiManager.setWifiEnabled(false);
56 | }
57 |
58 | startAp(ssid, passwd);
59 |
60 | TimerCheck timerCheck = new TimerCheck() {
61 | @Override
62 | public void doTimerCheckWork() {
63 | if (isWifiApEnabled()) {
64 | Message msg = handler.obtainMessage(ApCreateApSuccess);
65 | handler.sendMessage(msg);
66 | this.exit();
67 | }
68 | }
69 |
70 | @Override
71 | public void doTimeOutWork() {
72 | this.exit();
73 | }
74 | };
75 | timerCheck.start(10, 1000);
76 | }
77 |
78 | private void startAp(String ssid, String passwd) {
79 | Method method1 = null;
80 | try {
81 | method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
82 | WifiConfiguration.class, boolean.class);
83 | WifiConfiguration netConfig = new WifiConfiguration();
84 | netConfig.SSID = ssid;
85 | //netConfig.preSharedKey = passwd;
86 |
87 | netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
88 | netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
89 | netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
90 | netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
91 | netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
92 | netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
93 | netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
94 | netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
95 |
96 | method1.invoke(mWifiManager, netConfig, true);
97 | }
98 | catch (IllegalArgumentException e) {
99 | e.printStackTrace();
100 | }
101 | catch (IllegalAccessException e) {
102 | e.printStackTrace();
103 | }catch (InvocationTargetException e) {
104 | e.getCause().printStackTrace();
105 | }catch (SecurityException e) {
106 | e.printStackTrace();
107 | }catch (NoSuchMethodException e) {
108 | e.printStackTrace();
109 | }
110 | }
111 |
112 | public void closeWifiAp() {
113 | if (isWifiApEnabled()) {
114 | try {
115 | Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
116 | method.setAccessible(true);
117 |
118 | WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
119 |
120 | Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled",
121 | WifiConfiguration.class, boolean.class);
122 | method2.invoke(mWifiManager, config, false);
123 | }
124 | catch (NoSuchMethodException e) {
125 | e.printStackTrace();
126 | }
127 | catch (IllegalArgumentException e) {
128 | e.printStackTrace();
129 | }
130 | catch (IllegalAccessException e) {
131 | e.printStackTrace();
132 | }
133 | catch (InvocationTargetException e) {
134 | e.printStackTrace();
135 | }
136 | }
137 | }
138 |
139 | public boolean isWifiApEnabled() {
140 | try {
141 | Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
142 | method.setAccessible(true);
143 | return (Boolean) method.invoke(mWifiManager);
144 | }catch (NoSuchMethodException e) {
145 | e.printStackTrace();
146 | }catch (Exception e) {
147 | e.printStackTrace();
148 | }
149 | return false;
150 | }
151 |
152 | public int getWifiApStateInt() {
153 | try {
154 | int i = ((Integer) mWifiManager.getClass().getMethod("getWifiApState", new Class[0])
155 | .invoke(mWifiManager, new Object[0])).intValue();
156 | return i;
157 | }catch (Exception localException) {
158 | }
159 | return 4;
160 | }
161 |
162 | /**
163 | * 判断是否连接上wifi
164 | *
165 | * @return boolean值(isConnect),对应已连接(true)和未连接(false)
166 | */
167 | public boolean isWifiConnect() {
168 | NetworkInfo mNetworkInfo = ((ConnectivityManager) mContext
169 | .getSystemService(Context.CONNECTIVITY_SERVICE))
170 | .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
171 | return mNetworkInfo.isConnected();
172 | }
173 |
174 | public boolean isWifiEnabled() {
175 | return mWifiManager.isWifiEnabled();
176 | }
177 |
178 | public void OpenWifi() {
179 | if (!mWifiManager.isWifiEnabled())
180 | mWifiManager.setWifiEnabled(true);
181 | }
182 |
183 | public void closeWifi() {
184 | mWifiManager.setWifiEnabled(false);
185 | }
186 |
187 | public void addNetwork(WifiConfiguration paramWifiConfiguration) {
188 | int i = mWifiManager.addNetwork(paramWifiConfiguration);
189 | mWifiManager.enableNetwork(i, true);
190 | }
191 |
192 | public void removeNetwork(int netId) {
193 | if (mWifiManager != null) {
194 | mWifiManager.removeNetwork(netId);
195 | mWifiManager.saveConfiguration();
196 | }
197 | }
198 |
199 | /**
200 | * Function: 连接Wifi热点
201 | *
202 | * @date 2015年2月14日 上午11:17
203 | * @change hillfly
204 | * @version 1.0
205 | * @param SSID
206 | * @param Password
207 | * @param Type
208 | *
209 | * 没密码: {@linkplain WifiCipherType#WIFICIPHER_NOPASS}
210 | * WEP加密: {@linkplain WifiCipherType#WIFICIPHER_WEP}
211 | * WPA加密: {@linkplain WifiCipherType#WIFICIPHER_WPA}
212 | * @return true:连接成功;false:连接失败
213 | */
214 | public boolean connectWifi(String SSID, String Password, WifiCipherType Type) {
215 | if (!isWifiEnabled()) {
216 | return false;
217 | }
218 | // 开启wifi需要一段时间,要等到wifi状态变成WIFI_STATE_ENABLED
219 | while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
220 | try {
221 | // 避免程序不停循环
222 | Thread.currentThread();
223 | Thread.sleep(500);
224 | }catch (InterruptedException ie) {
225 | }
226 | }
227 |
228 | WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type);
229 | if (wifiConfig == null) {
230 | return false;
231 | }
232 |
233 | WifiConfiguration tempConfig = isExsits(SSID);
234 |
235 | if (tempConfig != null) {
236 | mWifiManager.removeNetwork(tempConfig.networkId);
237 | }
238 |
239 | int netID = mWifiManager.addNetwork(wifiConfig);
240 | mWifiManager.disconnect();
241 | // 设置为true,使其他的连接断开
242 | boolean bRet = mWifiManager.enableNetwork(netID, true);
243 | mWifiManager.reconnect();
244 | return bRet;
245 | }
246 |
247 | public void disconnectWifi(int paramInt) {
248 | mWifiManager.disableNetwork(paramInt);
249 | }
250 |
251 | public void startScan() {
252 | mWifiManager.startScan();
253 | }
254 |
255 | private WifiConfiguration createWifiInfo(String SSID, String Password,
256 | WifiCipherType Type) {
257 | WifiConfiguration config = new WifiConfiguration();
258 | config.allowedAuthAlgorithms.clear();
259 | config.allowedGroupCiphers.clear();
260 | config.allowedKeyManagement.clear();
261 | config.allowedPairwiseCiphers.clear();
262 | config.allowedProtocols.clear();
263 | config.SSID = "\"" + SSID + "\"";
264 | if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
265 | config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
266 | }else if (Type == WifiCipherType.WIFICIPHER_WEP) {
267 | config.preSharedKey = "\"" + Password + "\"";
268 | config.hiddenSSID = true;
269 | config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
270 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
271 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
272 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
273 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
274 | config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
275 | config.wepTxKeyIndex = 0;
276 | }else if (Type == WifiCipherType.WIFICIPHER_WPA) {
277 | config.preSharedKey = "\"" + Password + "\"";
278 | config.hiddenSSID = true;
279 | config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
280 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
281 | config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
282 | config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
283 | config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
284 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
285 | config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
286 | } else {
287 | return null;
288 | }
289 | return config;
290 | }
291 |
292 | public String getApSSID() {
293 | try {
294 | Method localMethod = mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]);
295 | if (localMethod == null)
296 | return null;
297 | Object localObject1 = localMethod.invoke(mWifiManager, new Object[0]);
298 | if (localObject1 == null)
299 | return null;
300 | WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
301 | if (localWifiConfiguration.SSID != null)
302 | return localWifiConfiguration.SSID;
303 | Field localField1 = WifiConfiguration.class.getDeclaredField("mWifiApProfile");
304 | if (localField1 == null)
305 | return null;
306 | localField1.setAccessible(true);
307 | Object localObject2 = localField1.get(localWifiConfiguration);
308 | localField1.setAccessible(false);
309 | if (localObject2 == null)
310 | return null;
311 | Field localField2 = localObject2.getClass().getDeclaredField("SSID");
312 | localField2.setAccessible(true);
313 | Object localObject3 = localField2.get(localObject2);
314 | if (localObject3 == null)
315 | return null;
316 | localField2.setAccessible(false);
317 | String str = (String) localObject3;
318 | return str;
319 | }
320 | catch (Exception localException) {
321 | }
322 | return null;
323 | }
324 |
325 | public String getBSSID() {
326 | WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
327 | return mWifiInfo.getBSSID();
328 | }
329 |
330 | public String getSSID() {
331 | WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
332 | return mWifiInfo.getSSID();
333 | }
334 |
335 | public String getLocalIPAddress() {
336 | WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
337 | return intToIp(wifiInfo.getIpAddress());
338 | }
339 |
340 | public InetAddress getBroadcastAddr() throws IOException {
341 | DhcpInfo dhcp = mWifiManager.getDhcpInfo();
342 | // handle null somehow
343 | int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
344 | byte[] quads = new byte[4];
345 | for (int k = 0; k < 4; k++)
346 | quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
347 | return InetAddress.getByAddress(quads);
348 | }
349 |
350 | public String getServerIPAddress() {
351 | DhcpInfo mDhcpInfo = mWifiManager.getDhcpInfo();
352 | return intToIp(mDhcpInfo.gateway);
353 | }
354 |
355 | @SuppressLint("NewApi")
356 | public String getBroadcastAddress() {
357 | System.setProperty("java.net.preferIPv4Stack", "true");
358 | try {
359 | for (Enumeration niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
360 | .hasMoreElements();) {
361 | NetworkInterface ni = niEnum.nextElement();
362 | if (!ni.isLoopback()) {
363 | for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
364 | if (interfaceAddress.getBroadcast() != null) {
365 | return interfaceAddress.getBroadcast().toString().substring(1);
366 | }
367 | }
368 | }
369 | }
370 | }
371 | catch (SocketException e) {
372 | e.printStackTrace();
373 | }
374 |
375 | return null;
376 | }
377 |
378 | public String getMacAddress() {
379 | WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
380 | if (mWifiInfo == null)
381 | return "NULL";
382 | return mWifiInfo.getMacAddress();
383 | }
384 |
385 | public int getNetworkId() {
386 | WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
387 | if (mWifiInfo == null)
388 | return 0;
389 | return mWifiInfo.getNetworkId();
390 | }
391 |
392 | public WifiInfo getWifiInfo() {
393 | return mWifiManager.getConnectionInfo();
394 | }
395 |
396 | public List getScanResults() {
397 | return mWifiManager.getScanResults();
398 | }
399 |
400 | // 查看以前是否也配置过这个网络
401 | private WifiConfiguration isExsits(String SSID) {
402 | List existingConfigs = mWifiManager.getConfiguredNetworks();
403 | for (WifiConfiguration existingConfig : existingConfigs) {
404 | if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
405 | return existingConfig;
406 | }
407 | }
408 | return null;
409 | }
410 |
411 | private String intToIp(int i) {
412 | return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
413 | + ((i >> 24) & 0xFF);
414 | }
415 |
416 | public String getIMEI(){
417 | TelephonyManager mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
418 | return mTelephonyManager.getDeviceId();
419 | }
420 | }
--------------------------------------------------------------------------------
/src/com/boy/tutils/DeviceUtils.java:
--------------------------------------------------------------------------------
1 | package com.boy.tutils;
2 |
3 | import java.io.File;
4 | import java.lang.reflect.Constructor;
5 | import java.lang.reflect.Field;
6 | import java.lang.reflect.Method;
7 | import java.util.List;
8 | import java.util.UUID;
9 |
10 | import android.app.Activity;
11 | import android.app.ActivityManager;
12 | import android.app.ActivityManager.RunningTaskInfo;
13 | import android.content.ActivityNotFoundException;
14 | import android.content.ComponentName;
15 | import android.content.Context;
16 | import android.content.Intent;
17 | import android.content.pm.ApplicationInfo;
18 | import android.content.pm.PackageInfo;
19 | import android.content.pm.PackageManager;
20 | import android.content.pm.ResolveInfo;
21 | import android.content.pm.PackageManager.NameNotFoundException;
22 | import android.content.res.Resources;
23 | import android.graphics.Paint;
24 | import android.graphics.drawable.Drawable;
25 | import android.net.ConnectivityManager;
26 | import android.net.NetworkInfo;
27 | import android.net.Uri;
28 | import android.os.Build;
29 | import android.os.Environment;
30 | import android.telephony.TelephonyManager;
31 | import android.text.TextUtils;
32 | import android.util.DisplayMetrics;
33 | import android.util.TypedValue;
34 | import android.view.View;
35 | import android.view.inputmethod.InputMethodManager;
36 |
37 | public class DeviceUtils {
38 |
39 | private static final String ASSET_MANAGER_PATH = "android.content.res.AssetManager";
40 | private static final String PACKAGE_PARSER_PATH = "android.content.pm.PackageParser";
41 |
42 | /**
43 | * dp转px
44 | */
45 | public static int dip2px(Context mContext, float dpValue) {
46 | final float scale = mContext.getResources().getDisplayMetrics().density;
47 | return (int) (dpValue * scale + 0.5f);
48 | }
49 |
50 | /**
51 | * px转dp
52 | */
53 | public static int px2dip(Context mContext, float pxValue) {
54 | final float scale = mContext.getResources().getDisplayMetrics().density;
55 | return (int) (pxValue / scale + 0.5f);
56 | }
57 |
58 | /**
59 | * sp转px
60 | */
61 | public static int sp2px(Context mContext, int sp) {
62 | final float scale = mContext.getResources().getDisplayMetrics().scaledDensity;
63 | return (int) (sp * scale + 0.5f);
64 | }
65 |
66 | /**
67 | * 取屏幕宽度
68 | *
69 | * @return
70 | */
71 | public static int getScreenWidth(Context mContext) {
72 | DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
73 | return dm.widthPixels;
74 | }
75 |
76 | /**
77 | * 取屏幕高度
78 | *
79 | * @return
80 | */
81 | public static int getScreenHeight(Context mContext) {
82 | DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
83 | return dm.heightPixels - getStatusBarHeight(mContext);
84 | }
85 |
86 | /**
87 | * 取屏幕高度包含状态栏高度
88 | *
89 | * @return
90 | */
91 | public static int getScreenHeightWithStatusBar(Context mContext) {
92 | DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
93 | return dm.heightPixels;
94 | }
95 |
96 | /**
97 | * 取导航栏高度
98 | *
99 | * @return
100 | */
101 | public static int getNavigationBarHeight(Context mContext) {
102 | int result = 0;
103 | int resourceId = mContext.getResources().getIdentifier(
104 | "navigation_bar_height", "dimen", "android");
105 | if (resourceId > 0) {
106 | result = mContext.getResources().getDimensionPixelSize(resourceId);
107 | }
108 | return result;
109 | }
110 |
111 | /**
112 | * 取状态栏高度
113 | *
114 | * @return
115 | */
116 | public static int getStatusBarHeight(Context mContext) {
117 | int result = 0;
118 | int resourceId = mContext.getResources().getIdentifier(
119 | "status_bar_height", "dimen", "android");
120 | if (resourceId > 0) {
121 | result = mContext.getResources().getDimensionPixelSize(resourceId);
122 | }
123 | return result;
124 | }
125 |
126 | public static int getActionBarHeight(Context mContext) {
127 | int actionBarHeight = 0;
128 |
129 | final TypedValue tv = new TypedValue();
130 | if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize,
131 | tv, true)) {
132 | actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
133 | mContext.getResources().getDisplayMetrics());
134 | }
135 | return actionBarHeight;
136 | }
137 |
138 | /** 关闭键盘 **/
139 | public static void hideSoftInput(View paramEditText, Context context) {
140 | ((InputMethodManager) context
141 | .getSystemService(Context.INPUT_METHOD_SERVICE))
142 | .hideSoftInputFromWindow(paramEditText.getWindowToken(), 0);
143 | }
144 |
145 | public static boolean hasCamera(Context mContext) {
146 | Boolean _hasCamera = null;
147 | if (_hasCamera == null) {
148 | PackageManager pckMgr = mContext.getPackageManager();
149 | boolean flag = pckMgr
150 | .hasSystemFeature("android.hardware.camera.front");
151 | boolean flag1 = pckMgr.hasSystemFeature("android.hardware.camera");
152 | boolean flag2;
153 | if (flag || flag1)
154 | flag2 = true;
155 | else
156 | flag2 = false;
157 | _hasCamera = Boolean.valueOf(flag2);
158 | }
159 | return _hasCamera.booleanValue();
160 | }
161 |
162 | public static void gotoMarket(Context context, String pck) {
163 | if (!isHaveMarket(context)) {
164 | return;
165 | }
166 | Intent intent = new Intent();
167 | intent.setAction(Intent.ACTION_VIEW);
168 | intent.setData(Uri.parse("market://details?id=" + pck));
169 | if (intent.resolveActivity(context.getPackageManager()) != null) {
170 | context.startActivity(intent);
171 | }
172 | }
173 |
174 | public static boolean isHaveMarket(Context context) {
175 | Intent intent = new Intent();
176 | intent.setAction("android.intent.action.MAIN");
177 | intent.addCategory("android.intent.category.APP_MARKET");
178 | PackageManager pm = context.getPackageManager();
179 | List infos = pm.queryIntentActivities(intent, 0);
180 | return infos.size() > 0;
181 | }
182 |
183 | public static void openAppInMarket(Context context) {
184 | if (context != null) {
185 | String pckName = context.getPackageName();
186 | try {
187 | gotoMarket(context, pckName);
188 | } catch (Exception ex) {
189 | try {
190 | String otherMarketUri = "http://market.android.com/details?id="
191 | + pckName;
192 | Intent intent = new Intent(Intent.ACTION_VIEW,
193 | Uri.parse(otherMarketUri));
194 | context.startActivity(intent);
195 | } catch (Exception e) {
196 |
197 | }
198 | }
199 | }
200 | }
201 |
202 | public static boolean gotoGoogleMarket(Activity activity, String pck) {
203 | try {
204 | Intent intent = new Intent();
205 | intent.setPackage("com.android.vending");
206 | intent.setAction(Intent.ACTION_VIEW);
207 | intent.setData(Uri.parse("market://details?id=" + pck));
208 | activity.startActivity(intent);
209 | return true;
210 | } catch (Exception e) {
211 | e.printStackTrace();
212 | return false;
213 | }
214 | }
215 |
216 | /**
217 | * 是否有sd卡
218 | *
219 | * @return
220 | */
221 | public static boolean isSdcardReady() {
222 | return Environment.MEDIA_MOUNTED.equals(Environment
223 | .getExternalStorageState());
224 | }
225 |
226 | public static PackageInfo getPackageInfo(Context context, String pckName) {
227 | try {
228 | return context.getPackageManager().getPackageInfo(pckName, 0);
229 | } catch (NameNotFoundException e) {
230 | }
231 | return null;
232 | }
233 |
234 | /**
235 | * 取APP版本号
236 | *
237 | * @return
238 | */
239 | public static int getVersionCode(Context context) {
240 | int versionCode = 0;
241 | try {
242 | versionCode = context.getPackageManager().getPackageInfo(
243 | context.getPackageName(), 0).versionCode;
244 | } catch (PackageManager.NameNotFoundException ex) {
245 | versionCode = 0;
246 | }
247 | return versionCode;
248 | }
249 |
250 | /**
251 | * 取APP版本名
252 | *
253 | * @return
254 | */
255 | public static String getVersionName(Context context) {
256 | String name = "";
257 | try {
258 | name = context.getPackageManager().getPackageInfo(
259 | context.getPackageName(), 0).versionName;
260 | } catch (PackageManager.NameNotFoundException ex) {
261 | name = "";
262 | }
263 | return name;
264 | }
265 |
266 | public static String getIMEI(Context context) {
267 | TelephonyManager tel = (TelephonyManager) context
268 | .getSystemService(Context.TELEPHONY_SERVICE);
269 | return tel.getDeviceId();
270 | }
271 |
272 | /**
273 | * 获取设备唯一标识
274 | * @param context
275 | * @return
276 | */
277 | public static String getUUID(Context context) {
278 | final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
279 |
280 | final String tmDevice, tmSerial, androidId;
281 | tmDevice = "" + tm.getDeviceId();
282 | tmSerial = "" + tm.getSimSerialNumber();
283 | androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
284 |
285 | UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
286 | String uniqueId = deviceUuid.toString();
287 |
288 | return uniqueId;
289 | }
290 |
291 | /**
292 | * 获取系统版本
293 | * @return
294 | */
295 | public static int getAndroidSystemVersion() {
296 | return android.os.Build.VERSION.SDK_INT;
297 | }
298 |
299 | /**
300 | * 获取手机名称
301 | *
302 | * @return
303 | */
304 | public static String getPhoneType() {
305 | return android.os.Build.MODEL;
306 | }
307 |
308 | /**
309 | * 安装apk
310 | *
311 | * @param context
312 | * @param file
313 | */
314 | public static void installAPK(Context context, File file) {
315 | if (file == null || !file.exists())
316 | return;
317 | Intent intent = new Intent();
318 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
319 | intent.setAction(Intent.ACTION_VIEW);
320 | intent.setDataAndType(Uri.fromFile(file),
321 | "application/vnd.android.package-archive");
322 | context.startActivity(intent);
323 | }
324 |
325 | /**
326 | * 卸载应用
327 | *
328 | * @param context
329 | * @param packageName
330 | */
331 | public static void uninstallApk(Context context, String packageName) {
332 | PackageInfo info = getPackageInfo(context, packageName);
333 | if (info != null) {
334 | Uri packageURI = Uri.parse("package:" + packageName);
335 | Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
336 | packageURI);
337 | context.startActivity(uninstallIntent);
338 | }
339 | }
340 |
341 | /**
342 | * 打开拨号盘
343 | *
344 | * @param context
345 | * @param number
346 | */
347 | public static void openDial(Context context, String number) {
348 | Uri uri = Uri.parse("tel:" + number);
349 | Intent it = new Intent(Intent.ACTION_DIAL, uri);
350 | context.startActivity(it);
351 | }
352 |
353 | /**
354 | * 发送短信
355 | *
356 | * @param context
357 | * @param smsBody
358 | * @param tel
359 | */
360 | public static void openSMS(Context context, String smsBody, String tel) {
361 | Uri uri = Uri.parse("smsto:" + tel);
362 | Intent it = new Intent(Intent.ACTION_SENDTO, uri);
363 | it.putExtra("sms_body", smsBody);
364 | context.startActivity(it);
365 | }
366 |
367 | /**
368 | * 发送邮件
369 | *
370 | * @param context
371 | * @param subject
372 | * 主题
373 | * @param content
374 | * 内容
375 | * @param emails
376 | * 邮件地址
377 | */
378 | public static void sendEmail(Context context, String subject,
379 | String content, String... emails) {
380 | try {
381 | Intent intent = new Intent(Intent.ACTION_SEND);
382 | // 模拟器
383 | // intent.setType("text/plain");
384 | intent.setType("message/rfc822"); // 真机
385 | intent.putExtra(android.content.Intent.EXTRA_EMAIL, emails);
386 | intent.putExtra(Intent.EXTRA_SUBJECT, subject);
387 | intent.putExtra(Intent.EXTRA_TEXT, content);
388 | context.startActivity(intent);
389 | } catch (ActivityNotFoundException e) {
390 | e.printStackTrace();
391 | }
392 | }
393 |
394 | /**
395 | * 是否有网络
396 | *
397 | * @return
398 | */
399 | public static boolean isNetWorkAvilable(Context context) {
400 | ConnectivityManager connectivityManager = (ConnectivityManager) context
401 | .getSystemService(Context.CONNECTIVITY_SERVICE);
402 | NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
403 | if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
404 | return false;
405 | } else {
406 | return true;
407 | }
408 | }
409 |
410 | /**
411 | * 获取当前网络类型
412 | *
413 | * @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
414 | */
415 | public static int getNetworkType(Context context) {
416 | int netType = 0;
417 | ConnectivityManager connectivityManager = (ConnectivityManager) context
418 | .getSystemService(Context.CONNECTIVITY_SERVICE);
419 | NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
420 | if (networkInfo == null) {
421 | return netType;
422 | }
423 | int nType = networkInfo.getType();
424 | if (nType == ConnectivityManager.TYPE_MOBILE) {
425 | String extraInfo = networkInfo.getExtraInfo();
426 | if (!TextUtils.isEmpty(extraInfo)) {
427 | if (extraInfo.toLowerCase().equals("cmnet")) {
428 | netType = 3;
429 | } else {
430 | netType = 2;
431 | }
432 | }
433 | } else if (nType == ConnectivityManager.TYPE_WIFI) {
434 | netType = 1;
435 | }
436 | return netType;
437 | }
438 |
439 | /**
440 | * 判断应用是否在前台
441 | *
442 | * @param context
443 | * @return
444 | */
445 | public static boolean isApplicationInBackground(Context context) {
446 | ActivityManager am = (ActivityManager) context
447 | .getSystemService(Context.ACTIVITY_SERVICE);
448 | List taskList = am.getRunningTasks(1);
449 | if (taskList != null && !taskList.isEmpty()) {
450 | ComponentName topActivity = taskList.get(0).topActivity;
451 | if (topActivity != null
452 | && !topActivity.getPackageName().equals(
453 | context.getPackageName())) {
454 | return true;
455 | }
456 | }
457 | return false;
458 | }
459 |
460 | /**
461 | * 根据包名获取appIcon
462 | * @param context
463 | * @param packageName
464 | * @return
465 | */
466 | public static Drawable loadIconFromPackageName(Context context, String packageName) {
467 | if (context == null) {
468 | return null;
469 | }
470 | Drawable icon = null;
471 | final PackageManager pm = context.getPackageManager();
472 | if (pm != null) {
473 | try {
474 | icon = pm.getApplicationIcon(packageName);
475 | } catch (NameNotFoundException e) {
476 | e.printStackTrace();
477 | icon = null;
478 | }
479 | }
480 | return icon;
481 | }
482 |
483 | /**
484 | * 根据apk路径获取appIcon
485 | * @param context
486 | * @param packageName
487 | * @return
488 | */
489 | public static Drawable loadIconFromAPK(Context context, String apkFullPath) {
490 | if (context == null || apkFullPath == null || apkFullPath.equals("")) {
491 | return null;
492 | }
493 | File apkFile = new File(apkFullPath);
494 | if (!apkFile.exists()) {
495 | return null;
496 | }
497 | Drawable icon = null;
498 |
499 | try {
500 | Class pkgParserCls = Class.forName(PACKAGE_PARSER_PATH);
501 | Class[] typeArgs = new Class[1];
502 | typeArgs[0] = String.class;
503 | Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
504 | Object[] valueArgs = new Object[1];
505 | valueArgs[0] = apkFullPath;
506 | Object pkgParser = pkgParserCt.newInstance(valueArgs);
507 |
508 | typeArgs = new Class[4];
509 | typeArgs[0] = File.class;
510 | typeArgs[1] = String.class;
511 | typeArgs[2] = DisplayMetrics.class;
512 | typeArgs[3] = Integer.TYPE;
513 | Method mPkgParserParsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage",
514 | typeArgs);
515 |
516 | DisplayMetrics metrics = new DisplayMetrics();
517 | metrics.setToDefaults();
518 | valueArgs = new Object[4];
519 | valueArgs[0] = apkFile;
520 | valueArgs[1] = apkFullPath;
521 | valueArgs[2] = metrics;
522 | valueArgs[3] = 0;
523 | Object pkgParserPkg = mPkgParserParsePackageMtd.invoke(pkgParser, valueArgs);
524 |
525 | Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");
526 | ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);
527 | Class assetMagCls = Class.forName(ASSET_MANAGER_PATH);
528 | Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);
529 | Object assetMag = assetMagCt.newInstance((Object[]) null);
530 | typeArgs = new Class[1];
531 | typeArgs[0] = String.class;
532 | Method mMssetMagaddAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath",
533 | typeArgs);
534 | valueArgs = new Object[1];
535 | valueArgs[0] = apkFullPath;
536 | mMssetMagaddAssetPathMtd.invoke(assetMag, valueArgs);
537 |
538 | Resources res = context.getResources();
539 | typeArgs = new Class[3];
540 | typeArgs[0] = assetMag.getClass();
541 | typeArgs[1] = res.getDisplayMetrics().getClass();
542 | typeArgs[2] = res.getConfiguration().getClass();
543 | Constructor resCt = Resources.class.getConstructor(typeArgs);
544 | valueArgs = new Object[3];
545 | valueArgs[0] = assetMag;
546 | valueArgs[1] = res.getDisplayMetrics();
547 | valueArgs[2] = res.getConfiguration();
548 | res = (Resources) resCt.newInstance(valueArgs);
549 |
550 | icon = res.getDrawable(info.icon);
551 | } catch (Exception e) {
552 | e.printStackTrace();
553 | return null;
554 | }
555 | return icon;
556 | }
557 |
558 | /**
559 | * 从apk文件获取包名
560 | * @param context
561 | * @param apkFile
562 | * @return
563 | */
564 | public static String getPackageNameFromApk(Context context, File apkFile) {
565 | if (context == null || apkFile == null || !apkFile.exists()) {
566 | return null;
567 | }
568 | PackageManager pm = context.getPackageManager();
569 | PackageInfo pi = pm.getPackageArchiveInfo(apkFile.getAbsolutePath(),
570 | PackageManager.GET_ACTIVITIES);
571 | if (pi != null) {
572 | return pi.packageName;
573 | }
574 | return null;
575 | }
576 |
577 | /**
578 | * 设置硬件加速
579 | *
580 | * @param view
581 | * @param accelerate
582 | */
583 | public static void setHardwareAccelerated(View view, int mode) {
584 | if (Build.VERSION.SDK_INT < 11) {
585 | return;
586 | }
587 | Method sAcceleratedMethod = null;
588 | try {
589 | if (null == sAcceleratedMethod) {
590 | sAcceleratedMethod = View.class.getMethod("setLayerType", new Class[] {
591 | Integer.TYPE, Paint.class });
592 | }
593 | sAcceleratedMethod.invoke(view, new Object[] { Integer.valueOf(mode), null });
594 | } catch (Throwable e) {
595 | }
596 | }
597 |
598 | }
599 |
--------------------------------------------------------------------------------