Android开发中常用的工具类整理

来源:互联网 发布:氟锑酸 知乎 编辑:程序博客网 时间:2024/05/23 17:44

这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识、前端、后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过!

日志

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
package net.wujingchao.android.utility
 
import android.util.Log;
 
public final class L {
 
    private final static int LEVEL = 5;
 
    private final static String DEFAULT_TAG = "L";
 
    private L() {
        throw new UnsupportedOperationException("L cannot instantiated!");
    }
 
    public static void v(String tag,String msg) {
        if(LEVEL >= 5)Log.v(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
    }
 
    public static void d(String tag,String msg) {
        if(LEVEL >= 4)Log.d(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
    }
 
    public static void i(String tag,String msg) {
        if(LEVEL >= 3)Log.i(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
    }
 
    public static void w(String tag,String msg) {
        if(LEVEL >= 2)Log.w(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
    }
 
    public static void e(String tag,String msg) {
        if(LEVEL >= 1)Log.e(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
    }
}

Toast

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package net.wujingchao.android.utility
 
import android.content.Context;
import android.widget.Toast;
 
public class T {
 
    private final static boolean isShow = true;
 
    private T(){
        throw new UnsupportedOperationException("T cannot be instantiated");
    }
 
    public static void showShort(Context context,CharSequence text) {
        if(isShow)Toast.makeText(context,text,Toast.LENGTH_SHORT).show();
    }
 
    public static void showLong(Context context,CharSequence text) {
        if(isShow)Toast.makeText(context,text,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
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
package net.wujingchao.android.utility
 
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
public class NetworkUtil {
     
    private NetworkUtil() {
        throw new UnsupportedOperationException("NetworkUtil 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;
    }
 
    /**
     * 判断是否是wifi连接
     */
    public static boolean isWifi(Context context){
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == nullreturn false;
        return connectivity.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
 
    }
 
    /**
     * 打开网络设置界面
     */
    public static void openSetting(Activity activity) {
        Intent intent = new Intent("/");
        ComponentName componentName = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
        intent.setComponent(componentName);
        intent.setAction("android.intent.action.VIEW");
        activity.startActivityForResult(intent, 0);
    }
 
    /**
     * 使用SSL不信任的证书
     */
    public static  void useUntrustedCertificate() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }
        };
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        catch (Exception e) {
           e.printStackTrace();
        }
    }
}

像素单位转换

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
package net.wujingchao.android.utility
 
import android.content.Context;
import android.util.TypedValue;
 
    public class DensityUtil {
 
    private DensityUtil() {
        throw new UnsupportedOperationException("DensityUtil cannot be instantiated");
    }
 
    public int dip2px(Context context,int dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue*scale + 0.5f);
    }
 
    public int px2dip(Context context,float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue/scale + 0.5f);
    }
 
    public static float px2sp(Context context, float pxValue){
        return (pxValue / context.getResources().getDisplayMetrics().scaledDensity);
    }
 
    public static int sp2px(Context context, int spValue){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spValue, context.getResources().getDisplayMetrics());
    }
}

屏幕

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
package net.wujingchao.android.utility
 
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
 
public class ScreenUtil {
 
    private ScreenUtil()
    {
        throw new UnsupportedOperationException("ScreenUtil 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;
    }
}

App相关

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
package net.wujingchao.android.utility
 
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
 
public class AppUtil {
 
    private AppUtil() {
        throw new UnsupportedOperationException("AppUtil cannot instantiated");
    }
 
    /**
     * 获取app版本名
     */
    public static String getAppVersionName(Context context){
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(),0);
            return pi.versionName;
        catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     * 获取应用程序版本名称信息
     */
    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;
    }
 
    /**
     * 获取app版本号
     */
    public static int getAppVersionCode(Context context){
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(),0);
            return pi.versionCode;
        catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

键盘

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
package net.wujingchao.android.utility
 
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
 
public class KeyBoardUtil{
 
    private KeyBoardUtil(){
        throw new UnsupportedOperationException("KeyBoardUtil cannot be instantiated");
    }
 
    /**
     * 打卡软键盘
     */
    public static void openKeybord(EditText mEditText, Context mContext){
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    /**
     * 关闭软键盘
     */
    public static void closeKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }
}

文件上传下载

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
180
181
182
package net.wujingchao.android.utility
 
import android.content.Context;
import android.os.Environment;
 
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File; 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream; 
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.UUID;
 
import com.mixiaofan.App;
 
public class DownloadUtil {
 
     private static final int TIME_OUT = 30*1000; //超时时间
 
     private static final String CHARSET = "utf-8"//设置编码
 
     private DownloadUtil() {
        throw new UnsupportedOperationException("DownloadUtil cannot be instantiated");
     }
 
    /**
     * @param file  上传文件
     * @param RequestURL 上传文件URL
     * @return 服务器返回的信息,如果出错则返回为null
     */
     public static String uploadFile(File file,String RequestURL) {
         String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
         String PREFIX = "--" , LINE_END = "\r\n";
         String CONTENT_TYPE = "multipart/form-data"//内容类型
         try {
             URL url = new URL(RequestURL);
             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
             conn.setReadTimeout(TIME_OUT);
             conn.setConnectTimeout(TIME_OUT);
             conn.setDoInput(true); //允许输入流
             conn.setDoOutput(true); //允许输出流
             conn.setUseCaches(false); //不允许使用缓存 
             conn.setRequestMethod("POST"); //请求方式 
             conn.setRequestProperty("Charset", CHARSET);
             conn.setRequestProperty("Cookie""PHPSESSID=" + App.getSessionId());
             //设置编码 
             conn.setRequestProperty("connection""keep-alive"); 
             conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
             if(file!=null) { 
                     /** * 当文件不为空,把文件包装并且上传 */
                     OutputStream outputSteam=conn.getOutputStream();
                     DataOutputStream dos = new DataOutputStream(outputSteam);
                     StringBuffer sb = new StringBuffer();
                     sb.append(PREFIX);
                     sb.append(BOUNDARY); sb.append(LINE_END);
                     /**
                     * 这里重点注意:
                     * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                     * filename是文件的名字,包含后缀名的 比如:abc.png
                     */
                     sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
                     sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                     sb.append(LINE_END);
                     dos.write(sb.toString().getBytes());
                     InputStream is = new FileInputStream(file);
                     byte[] bytes = new byte[1024];
                     int len;
                     while((len=is.read(bytes))!=-1)
                     {
                        dos.write(bytes, 0, len);
                     }
                     is.close();
                     dos.write(LINE_END.getBytes());
                     byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                     dos.write(end_data);
                     dos.flush();
                     /**
                     * 获取响应码 200=成功
                     * 当响应成功,获取响应的流
                     */
                     ByteArrayOutputStream bos = new ByteArrayOutputStream();
                     InputStream resultStream = conn.getInputStream();
                     len = -1;
                     byte [] buffer = new byte[1024*8];
                     while((len = resultStream.read(buffer)) != -1) {
                         bos.write(buffer,0,len);
                     }
                     resultStream.close();
                     bos.flush();
                     bos.close();
                     String info = new String(bos.toByteArray());
                     int res = conn.getResponseCode();
                     if(res==200){
                        return info;
                     }else {
                         return null;
                     }
                }
               catch (MalformedURLException e) {
                    e.printStackTrace();
               catch (ProtocolException e) {
                    e.printStackTrace();
               catch (FileNotFoundException e) {
                    e.printStackTrace();
               catch (IOException e) {
                     e.printStackTrace();
               }
         return null;
     }
 
     public static byte[] download(String urlStr) {
            HttpURLConnection conn = null;
            InputStream is = null;
            byte[] result = null;
            ByteArrayOutputStream bos = null;
            try {
                URL url = new URL(urlStr);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(TIME_OUT);
                conn.setReadTimeout(TIME_OUT);
                conn.setDoInput(true);
                conn.setUseCaches(false);//不使用缓存
                if(conn.getResponseCode() == 200) {
                    is = conn.getInputStream();
                    byte [] buffer = new byte[1024*8];
                    int len;
                    bos = new ByteArrayOutputStream();
                    while((len = is.read(buffer)) != -1) {
                        bos.write(buffer,0,len);
                    }
                    bos.flush();
                    result = bos.toByteArray();
                }
            catch (MalformedURLException e) {
                e.printStackTrace();
            catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bos != null){
                        bos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    if (conn != null)conn.disconnect();
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
 
    /**
     * 获取缓存文件
     */
     public static File getDiskCacheFile(Context context,String filename,boolean isExternal) {
        if(isExternal && (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
            return new File(context.getExternalCacheDir(),filename);
        }else {
            return new File(context.getCacheDir(),filename);
        }
    }
 
    /**
     * 获取缓存文件目录
     */
     public static File getDiskCacheDirectory(Context context) {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return context.getExternalCacheDir();
        }else {
            return context.getCacheDir();
        }
    }
 }

加密

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
package net.wujingchao.android.utility
 
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class CipherUtil { 
 
    private CipherUtil() {
 
    }
 
    //字节数组转化为16进制字符串
    public static String byteArrayToHex(byte[] byteArray) {
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9''A','B','C','D','E','F' };
        char[] resultCharArray =new char[byteArray.length * 2];
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    }
 
    //字节数组md5算法
    public static byte[] md5 (byte [] bytes) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(bytes);
            return messageDigest.digest();
        catch (NoSuchAlgorithmException 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
37
38
39
40
41
42
43
44
45
package net.wujingchao.android.utility
import java.text.SimpleDateFormat;
import java.util.Date;
 
 
public class DateUtil {
 
    //转换中文对应的时段
    public static String convertNowHour2CN(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        String hourString = sdf.format(date);
        int hour = Integer.parseInt(hourString);
        if(hour < 6) {
            return "凌晨";
        }else if(hour >= 6 && hour < 12) {
            return "早上";
        }else if(hour == 12) {
            return "中午";
        }else if(hour > 12 && hour <=18) {
            return "下午";
        }else if(hour >=19) {
            return "晚上";
        }
        return "";
    }
 
    //剩余秒数转换
    public static String convertSecond2Day(int time) {
        int day = time/86400;
        int hour = (time - 86400*day)/3600;
        int min = (time - 86400*day - 3600*hour)/60;
        int sec = (time - 86400*day - 3600*hour - 60*min);
        StringBuilder sb = new StringBuilder();
        sb.append(day);
        sb.append("天");
        sb.append(hour);
        sb.append("时");
        sb.append(min);
        sb.append("分");
        sb.append(sec);
        sb.append("秒");
        return sb.toString();
    }
 
}

 


0 0