Android开发辅助工具类

来源:互联网 发布:淘宝750促销模板代码 编辑:程序博客网 时间:2024/06/07 07:01

文章转自http://blog.csdn.net/smartbetter/article/details/52709446

本篇用于分享Android开发辅助工具类,用于快速开发,以便减少做重复的工作,提高开发效率。项目代码长期更新于Github:https://github.com/smartbetter/Android-UtilsLibrary

1.AppUtils(App相关辅助类)

public class AppUtils {    private AppUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 获取应用程序名称     */    public static String getAppName(Context context) {        try {            PackageManager packageManager = context.getPackageManager();            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);            int labelRes = packageInfo.applicationInfo.labelRes;            return context.getResources().getString(labelRes);        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }        return null;    }    /**     * 获取应用程序版本名称信息     */    public static String getVersionName(Context context) {        try {            PackageManager packageManager = context.getPackageManager();            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);            return packageInfo.versionName; // 当前应用的版本名称        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }        return null;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

2.CameraUtils(摄像头相关辅助类)

public class CameraUtils {    private CameraUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 判断摄像头是否可用     */    public static boolean isCameraCanUse() {        boolean canUse = true;        Camera mCamera = null;        try {            mCamera = Camera.open();            // setParameters 是针对魅族MX5 做的。MX5 通过Camera.open() 拿到的Camera            // 对象不为null            Camera.Parameters mParameters = mCamera.getParameters();            mCamera.setParameters(mParameters);        } catch (Exception e) {            canUse = false;        }        if (mCamera != null) {            mCamera.release();        }        return canUse;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

3.DensityUtils(android dp和px之间转换)

public class DensityUtils {    private DensityUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)     */    public static int qip2px(Context context, float dpValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (dpValue * scale + 0.5f);    }    /**     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp     */    public static int px2dip(Context context, float pxValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (pxValue / scale + 0.5f);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

4.FileUtils(文件的基本操作)

主要封装了一些文件操作的基本方法,包括创建、删除、获取文件大小等。

public class FileUtils {    private FileUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 检查是否存在SD卡     */    public static boolean hasSdcard() {        String state = Environment.getExternalStorageState();        if (state.equals(Environment.MEDIA_MOUNTED)) {            return true;        } else {            return false;        }    }    /**     * 创建目录     *     * @param context     * @param dirName 文件夹名称     * @return     */    public static File createFileDir(Context context, String dirName) {        String filePath;        // 如SD卡已存在,则存储;反之存在data目录下        if (hasSdcard()) {            // SD卡路径            filePath = Environment.getExternalStorageDirectory() + File.separator + dirName;        } else {            filePath = context.getCacheDir().getPath() + File.separator + dirName;        }        File destDir = new File(filePath);        if (!destDir.exists()) {            boolean isCreate = destDir.mkdirs();            Log.i("FileUtils", filePath + " has created. " + isCreate);        }        return destDir;    }    /**     * 删除文件(若为目录,则递归删除子目录和文件)     *     * @param file     * @param delThisPath true代表删除参数指定file,false代表保留参数指定file     */    public static void delFile(File file, boolean delThisPath) {        if (!file.exists()) {            return;        }        if (file.isDirectory()) {            File[] subFiles = file.listFiles();            if (subFiles != null) {                int num = subFiles.length;                // 删除子目录和文件                for (int i = 0; i < num; i++) {                    delFile(subFiles[i], true);                }            }        }        if (delThisPath) {            file.delete();        }    }    /**     * 获取文件大小,单位为byte(若为目录,则包括所有子目录和文件)     *     * @param file     * @return     */    public static long getFileSize(File file) {        long size = 0;        if (file.exists()) {            if (file.isDirectory()) {                File[] subFiles = file.listFiles();                if (subFiles != null) {                    int num = subFiles.length;                    for (int i = 0; i < num; i++) {                        size += getFileSize(subFiles[i]);                    }                }            } else {                size += file.length();            }        }        return size;    }    /**     * 保存Bitmap到指定目录     *     * @param dir      目录     * @param fileName 文件名     * @param bitmap     * @throws IOException     */    public static void saveBitmap(File dir, String fileName, Bitmap bitmap) {        if (bitmap == null) {            return;        }        File file = new File(dir, fileName);        try {            file.createNewFile();            FileOutputStream fos = new FileOutputStream(file);            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);            fos.flush();            fos.close();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 判断某目录下文件是否存在     *     * @param dir      目录     * @param fileName 文件名     * @return     */    public static boolean isFileExists(File dir, String fileName) {        return new File(dir, fileName).exists();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127

5.HttpUtils(Http相关辅助类)

public class HttpUtils {    private HttpUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    private static final int TIMEOUT_IN_MILLIONS = 5000;    public interface CallBack {        void onRequestComplete(String result);    }    /**     * 异步的Get请求     *     * @param urlStr     * @param callBack     */    public static void doGetAsyn(final String urlStr, final CallBack callBack) {        new Thread() {            public void run() {                try {                    String result = doGet(urlStr);                    if (callBack != null) {                        callBack.onRequestComplete(result);                    }                } catch (Exception e) {                    e.printStackTrace();                }            }            ;        }.start();    }    /**     * 异步的Post请求     *     * @param urlStr     * @param params     * @param callBack     * @throws Exception     */    public static void doPostAsyn(final String urlStr, final String params,                                  final CallBack callBack) throws Exception {        new Thread() {            public void run() {                try {                    String result = doPost(urlStr, params);                    if (callBack != null) {                        callBack.onRequestComplete(result);                    }                } catch (Exception e) {                    e.printStackTrace();                }            }            ;        }.start();    }    /**     * Get请求,获得返回数据     *     * @param urlStr     * @return     * @throws Exception     */    public static String doGet(String urlStr) {        URL url = null;        HttpURLConnection conn = null;        InputStream is = null;        ByteArrayOutputStream baos = null;        try {            url = new URL(urlStr);            conn = (HttpURLConnection) url.openConnection();            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);            conn.setRequestMethod("GET");            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("connection", "Keep-Alive");            if (conn.getResponseCode() == 200) {                is = conn.getInputStream();                baos = new ByteArrayOutputStream();                int len = -1;                byte[] buf = new byte[128];                while ((len = is.read(buf)) != -1) {                    baos.write(buf, 0, len);                }                baos.flush();                return baos.toString();            } else {                throw new RuntimeException(" responseCode is not 200 ... ");            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (is != null)                    is.close();            } catch (IOException e) {            }            try {                if (baos != null)                    baos.close();            } catch (IOException e) {            }            conn.disconnect();        }        return null;    }    /**     * 向指定 URL 发送POST方法的请求     *     * @param url   发送请求的 URL     * @param param 请求参数,形式:name1=value1&name2=value2     * @return 所代表远程资源的响应结果     * @throws Exception     */    public static String doPost(String url, String param) {        PrintWriter out = null;        BufferedReader in = null;        String result = "";        try {            URL realUrl = new URL(url);            // 打开和URL之间的连接            HttpURLConnection conn = (HttpURLConnection) realUrl                    .openConnection();            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestMethod("POST");            conn.setRequestProperty("Content-Type",                    "application/x-www-form-urlencoded");            conn.setRequestProperty("charset", "utf-8");            conn.setUseCaches(false);            // 发送POST请求必须设置如下两行            conn.setDoOutput(true);            conn.setDoInput(true);            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);            if (param != null && !param.trim().equals("")) {                // 获取URLConnection对象对应的输出流                out = new PrintWriter(conn.getOutputStream());                // 发送请求参数                out.print(param);                // flush输出流的缓冲                out.flush();            }            // 定义BufferedReader输入流来读取URL的响应            in = new BufferedReader(                    new InputStreamReader(conn.getInputStream()));            String line;            while ((line = in.readLine()) != null) {                result += line;            }        } catch (Exception e) {            e.printStackTrace();        }        // 使用finally块来关闭输出流、输入流        finally {            try {                if (out != null) {                    out.close();                }                if (in != null) {                    in.close();                }            } catch (IOException ex) {                ex.printStackTrace();            }        }        return result;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179

6.KeyBoardUtils(软键盘相关辅助类)

public class KeyBoardUtils {    private KeyBoardUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 切换软键盘的状态     * 如当前为收起变为弹出,若当前为弹出变为收起     */    public static void toggleKeybord(EditText edittext) {        InputMethodManager inputMethodManager = (InputMethodManager)                edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);    }    /**     * 强制隐藏输入法键盘     */    public static void hideKeybord(EditText edittext) {        InputMethodManager inputMethodManager = (InputMethodManager)                edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);        if (inputMethodManager.isActive()) {            inputMethodManager.hideSoftInputFromWindow(edittext.getWindowToken(), 0);        }    }    /**     * 强制显示输入法键盘     */    public static void showKeybord(EditText edittext) {        InputMethodManager inputMethodManager = (InputMethodManager)                edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);        inputMethodManager.showSoftInput(edittext, InputMethodManager.SHOW_FORCED);    }    /**     * 输入法是否显示     */    public static boolean isKeybord(EditText edittext) {        boolean bool = false;        InputMethodManager inputMethodManager = (InputMethodManager)                edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);        if (inputMethodManager.isActive()) {            bool = true;        }        return bool;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

7.LogUtils

public class LogUtils {    private LogUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    private static boolean isDebug = false;    public static void i(String tag, String msg) {        if (isDebug) {            Log.i(tag, msg);        }    }    public static void i(Object object, String msg) {        if (isDebug) {            Log.i(object.getClass().getSimpleName(), msg);        }    }    public static void e(String tag, String msg) {        if (isDebug) {            Log.e(tag, msg);        }    }    public static void e(Object object, String msg) {        if (isDebug) {            Log.e(object.getClass().getSimpleName(), msg);        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

8.NetUtils(网络相关)

public class NetUtils {    private NetUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 判断网络是否连接     */    public static boolean isConnected(Context context) {        ConnectivityManager connectivity = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        if (null != connectivity) {            NetworkInfo info = connectivity.getActiveNetworkInfo();            if (null != info && info.isConnected()) {                if (info.getState() == NetworkInfo.State.CONNECTED) {                    return true;                }            }        }        return false;    }    /**     * 是否有网络,需要加上访问网络状态的权限     */    public static boolean hasNetwork(Context context) {        ConnectivityManager con = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo workinfo = con.getActiveNetworkInfo();        if (workinfo == null || !workinfo.isAvailable()) {            return false;        }        return true;    }    /**     * 判断是否是WiFi网络     */    public static boolean isWifiNet(Context context) {        ConnectivityManager con = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo workinfo = con.getActiveNetworkInfo();        return workinfo != null                && workinfo.getType() == ConnectivityManager.TYPE_WIFI;    }    /**     * 打开网络设置界面     */    public static void openSetting(Activity activity) {        //整体        activity.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));        //WIFI:        //activity.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));        //流量:        //activity.startActivity(new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS));    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

9.ScreenUtils(屏幕相关)

public class ScreenUtils {    private ScreenUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 获得屏幕高度     */    public static int getScreenWidth(Context context) {        WindowManager wm = (WindowManager) context                .getSystemService(Context.WINDOW_SERVICE);        DisplayMetrics outMetrics = new DisplayMetrics();        wm.getDefaultDisplay().getMetrics(outMetrics);        return outMetrics.widthPixels;    }    /**     * 获得屏幕宽度     */    public static int getScreenHeight(Context context) {        WindowManager wm = (WindowManager) context                .getSystemService(Context.WINDOW_SERVICE);        DisplayMetrics outMetrics = new DisplayMetrics();        wm.getDefaultDisplay().getMetrics(outMetrics);        return outMetrics.heightPixels;    }    /**     * 获得状态栏的高度     */    public static int getStatusHeight(Context context) {        int statusHeight = -1;        try {            Class<?> clazz = Class.forName("com.android.internal.R$dimen");            Object object = clazz.newInstance();            int height = Integer.parseInt(clazz.getField("status_bar_height")                    .get(object).toString());            statusHeight = context.getResources().getDimensionPixelSize(height);        } catch (Exception e) {            e.printStackTrace();        }        return statusHeight;    }    /**     * 获取当前屏幕截图,包含状态栏     */    public static Bitmap snapShotWithStatusBar(Activity activity) {        View view = activity.getWindow().getDecorView();        view.setDrawingCacheEnabled(true);        view.buildDrawingCache();        Bitmap bmp = view.getDrawingCache();        int width = getScreenWidth(activity);        int height = getScreenHeight(activity);        Bitmap bp = null;        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);        view.destroyDrawingCache();        return bp;    }    /**     * 获取当前屏幕截图,不包含状态栏     */    public static Bitmap snapShotWithoutStatusBar(Activity activity) {        View view = activity.getWindow().getDecorView();        view.setDrawingCacheEnabled(true);        view.buildDrawingCache();        Bitmap bmp = view.getDrawingCache();        Rect frame = new Rect();        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);        int statusBarHeight = frame.top;        int width = getScreenWidth(activity);        int height = getScreenHeight(activity);        Bitmap bp = null;        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height                - statusBarHeight);        view.destroyDrawingCache();        return bp;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

10.SDCardUtils(SD卡相关)

public class SDCardUtils {    private SDCardUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 判断SDCard是否可用     */    public static boolean isSDCardEnable() {        return Environment.getExternalStorageState().equals(                Environment.MEDIA_MOUNTED);    }    /**     * 获取SD卡路径     */    public static String getSDCardPath() {        return Environment.getExternalStorageDirectory().getAbsolutePath()                + File.separator;    }    /**     * 获取SD卡的剩余容量(byte)     */    public static long getSDCardAllSize() {        if (isSDCardEnable()) {            StatFs stat = new StatFs(getSDCardPath());            // 获取空闲的数据块的数量            long availableBlocks = (long) stat.getAvailableBlocks() - 4;            // 获取单个数据块的大小(byte)            long freeBlocks = stat.getAvailableBlocks();            return freeBlocks * availableBlocks;        }        return 0;    }    /**     * 获取指定路径所在空间的剩余可用容量字节数(byte)     * @param filePath     * @return 容量字节 SDCard可用空间,内部存储可用空间     */    public static long getFreeBytes(String filePath) {        // 如果是sd卡的下的路径,则获取sd卡可用容量        if (filePath.startsWith(getSDCardPath())) {            filePath = getSDCardPath();        } else {// 如果是内部存储的路径,则获取内存存储的可用容量            filePath = Environment.getDataDirectory().getAbsolutePath();        }        StatFs stat = new StatFs(filePath);        long availableBlocks = (long) stat.getAvailableBlocks() - 4;        return stat.getBlockSize() * availableBlocks;    }    /**     * 获取系统存储路径     */    public static String getRootDirectoryPath() {        return Environment.getRootDirectory().getAbsolutePath();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

11.SPUtils

public class SPUtils {    private SPUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 保存文件名     */    public static final String FILE_NAME = "config";    /**     * 保存数据的方法,根据类型调用不同的保存方法     */    public static void put(Context context, String key, Object object) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        if (object instanceof String) {            editor.putString(key, (String) object);        } else if (object instanceof Integer) {            editor.putInt(key, (Integer) object);        } else if (object instanceof Boolean) {            editor.putBoolean(key, (Boolean) object);        } else if (object instanceof Float) {            editor.putFloat(key, (Float) object);        } else if (object instanceof Long) {            editor.putLong(key, (Long) object);        } else {            editor.putString(key, object.toString());        }        SharedPreferencesCompat.apply(editor); //commit同步的,apply异步的    }    /**     * 获取数据的方法,根据默认值得到数据的类型,然后调用对应方法获取值     */    public static Object get(Context context, String key, Object defaultObject) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                Context.MODE_PRIVATE);        if (defaultObject instanceof String) {            return sp.getString(key, (String) defaultObject);        } else if (defaultObject instanceof Integer) {            return sp.getInt(key, (Integer) defaultObject);        } else if (defaultObject instanceof Boolean) {            return sp.getBoolean(key, (Boolean) defaultObject);        } else if (defaultObject instanceof Float) {            return sp.getFloat(key, (Float) defaultObject);        } else if (defaultObject instanceof Long) {            return sp.getLong(key, (Long) defaultObject);        }        return null;    }    /**     * 移除某个key对应的值     */    public static void remove(Context context, String key) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        editor.remove(key);        SharedPreferencesCompat.apply(editor);    }    /**     * 清除所有数据     */    public static void clear(Context context) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        editor.clear();        SharedPreferencesCompat.apply(editor);    }    /**     * 查询某个key是否已经存在     */    public static boolean contains(Context context, String key) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                Context.MODE_PRIVATE);        return sp.contains(key);    }    /**     * 返回所有的键值对     */    public static Map<String, ?> getAll(Context context) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                Context.MODE_PRIVATE);        return sp.getAll();    }    /**     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类(适配)     */    private static class SharedPreferencesCompat {        private static final Method sApplyMethod = findApplyMethod();        /**         * 反射查找apply的方法         */        @SuppressWarnings({"unchecked", "rawtypes"})        private static Method findApplyMethod() {            try {                Class clz = SharedPreferences.Editor.class;                return clz.getMethod("apply");            } catch (NoSuchMethodException e) {            }            return null;        }        /**         * 如果找到则使用apply执行,否则使用commit         */        public static void apply(SharedPreferences.Editor editor) {            try {                if (sApplyMethod != null) {                    sApplyMethod.invoke(editor);                    return;                }            } catch (IllegalArgumentException e) {            } catch (IllegalAccessException e) {            } catch (InvocationTargetException e) {            }            editor.commit();        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134

12.ToastUtils

public class ToastUtils {    private ToastUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 短时间显示Toast     */    public static void showShort(Context context, CharSequence message) {        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();    }    /**     * 长时间显示Toast     */    public static void showLong(Context context, CharSequence message) {        Toast.makeText(context, message, Toast.LENGTH_LONG).show();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

13.ViewUtils

public class ViewUtils {    private ViewUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 把自身从父View中移除     */    public static void removeSelfFromParent(View view) {        if (view != null) {            ViewParent parent = view.getParent();            if (parent != null && parent instanceof ViewGroup) {                ViewGroup group = (ViewGroup) parent;                group.removeView(view);            }        }    }    /**     * 判断触点是否落在该View上     */    public static boolean isTouchInView(MotionEvent ev, View v) {        int[] vLoc = new int[2];        v.getLocationOnScreen(vLoc);        float motionX = ev.getRawX();        float motionY = ev.getRawY();        return motionX >= vLoc[0] && motionX <= (vLoc[0] + v.getWidth())                && motionY >= vLoc[1] && motionY <= (vLoc[1] + v.getHeight());    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

除了以上常用工具类,还提供了对一些常用开源框架的辅助工具类,如下:

14.GlideUtils(Glide框架相关)

/** * 用Glide框架加载图片的时候根据图片尺寸让ImageView自适应 * Created by gc on 2016/11/6. */public class GlideUtils {    private GlideUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 加载图片     * @param view     * @param url     * @param targetWidth     */    public static void loadImage(ImageView view, String url, final int targetWidth) {        Glide.with(view.getContext())                .load(url)                .into(new ImageViewTarget<GlideDrawable>(view) {                    @Override                    protected void setResource(GlideDrawable resource) {                        autoFit(view, targetWidth, resource.getIntrinsicWidth(), resource.getIntrinsicHeight());                        view.setImageDrawable(resource);                    }                });    }    public static void autoFit(ImageView imageView, int targetWidth, int photoWidth, int photoHeight) {        float ratio = (targetWidth + 0f) / photoWidth;        ViewGroup.LayoutParams params = imageView.getLayoutParams();        if (params == null) {            params = new ViewGroup.LayoutParams(targetWidth, (int) (photoHeight * ratio));        } else {            params.width = targetWidth;            params.height = (int) (photoHeight * ratio);        }        imageView.setLayoutParams(params);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

15.GsonUtils

public class GsonUtils {    private GsonUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 把一个map变成json字符串     *     * @param map     * @return     */    public static String parseMapToJson(Map<?, ?> map) {        try {            Gson gson = new Gson();            return gson.toJson(map);        } catch (Exception e) {        }        return null;    }    /**     * 把一个json字符串变成对象     *     * @param json     * @param cls     * @return     */    public static <T> T parseJsonToBean(String json, Class<T> cls) {        Gson gson = new Gson();        T t = null;        try {            t = gson.fromJson(json, cls);        } catch (Exception e) {        }        return t;    }    /**     * 把json字符串变成map     *     * @param json     * @return     */    public static HashMap<String, Object> parseJsonToMap(String json) {        Gson gson = new Gson();        Type type = new TypeToken<HashMap<String, Object>>() {        }.getType();        HashMap<String, Object> map = null;        try {            map = gson.fromJson(json, type);        } catch (Exception e) {        }        return map;    }    /**     * 把json字符串变成集合     * params: new TypeToken<List<yourbean>>(){}.getType(),     *     * @param json     * @param type new TypeToken<List<yourbean>>(){}.getType()     * @return     */    public static List<?> parseJsonToList(String json, Type type) {        Gson gson = new Gson();        List<?> list = gson.fromJson(json, type);        return list;    }    /**     * 获取json串中某个字段的值,注意,只能获取同一层级的value     *     * @param json     * @param key     * @return     */    public static String getFieldValue(String json, String key) {        if (TextUtils.isEmpty(json))            return null;        if (!json.contains(key))            return "";        JSONObject jsonObject = null;        String value = null;        try {            jsonObject = new JSONObject(json);            value = jsonObject.getString(key);        } catch (JSONException e) {            e.printStackTrace();        }        return value;    }}
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 江门二手房信息 江门恩平温泉度假村 江门工程造价信息网 江门到湛江要多久 江门舞蹈培训 新会特产 江水平装修队 江阳 江阳区 泸州江阳区 泸州市江阳区邮编 江阴论坛 江阴市 江阴暨阳 江阴人才网 江阴玻璃桥 江阴银行 江阴玻璃 江阴人才 江阴二手房 江阴教育网 江阴飞马 江阴教育 江阴房价 江阴华西村 江阴邮编 江阴要塞 江阴地铁 江苏江阴 江阴景点 江阴旅游 江阴飞马城 江阴海战 江阴属于 无锡到江阴 江阴商品房 江阴新桥 江阴招聘 江阴人力 江阴中医院 江阴高铁