xcy396
11/18/2017 - 9:38 AM

Utils

// 获取网络时间 ntp 服务器地址:http://ntp.org.cn/
// https://github.com/instacart/truetime-android
Executors.newSingleThreadExecutor()
        .execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TrueTime.build()
                            .withNtpHost("cn.ntp.org.cn")
                            .initialize();
                    Date date = TrueTime.now();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd.HHmmss", Locale.ENGLISH);
                    String time = simpleDateFormat.format(date);
                    ShellUtil.execute("date -s " + time);
                    Log.e(TAG, "run: 设定时间为:" + time);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
import android.os.Environment;

import java.io.File;

/**
 * Created by Mark Xu on 2017/11/30.
 * Site: http://xuchongyang.com
 */

public class SdCardUtil {
    /**
     * 判断 SD 卡(外部存储)是否可用
     * @return 是否可用
     */
    public static boolean hasSDCardMounted() {
        String state = Environment.getExternalStorageState();
        return state != null && state.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取非 Root 用户的可用空间
     * @param path 路径
     * @return 可用空间大小
     */
    public static long getUsableSpace(File path) {
        return path.getUsableSpace();
    }

    /**
     * 获取 Root 用户的可用空间
     * @param path 路径
     * @return 可用空间大小
     */
    public static long getFreeSpace(File path) {
        return path.getFreeSpace();
    }
}
/**
 * SharedPreferenceUtils
 * Created by xcy396 on 16/10/30.
 */
 
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.util.Map;

public class SharedPreferencesUtil {

    /**
     * 保存数据到指定文件中
     *
     * @param context
     *            上下文
     * @param sharedPreferencesFileName
     *            用SharedPreferences保存的文件名
     * @param key
     *            键值
     * @param value
     *            键对应的值
     */
    public static void save(Context context, String sharedPreferencesFileName, String key, Object value) {
        SharedPreferences sp = context.getSharedPreferences(sharedPreferencesFileName, Context.MODE_PRIVATE);
        save(sp, key, value);
    }

    /**
     * 保存数据到默认的文件中
     *
     * @param context
     *            上下文
     * @param key
     *            键值
     * @param value
     *            键对应的值
     */
    public static void save(Context context, String key, Object value) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        save(sp, key, value);
    }

    private static void save(SharedPreferences sp, String key, Object value) {
        if (value==null) {
            return;
        }
        String type = value.getClass().getSimpleName();
        SharedPreferences.Editor editor = sp.edit();
        if ("String".equals(type)) {
            editor.putString(key, (String) value);
        } else if ("Integer".equals(type)) {
            editor.putInt(key, (Integer) value);
        } else if ("Boolean".equals(type)) {
            editor.putBoolean(key, (Boolean) value);
        } else if ("Float".equals(type)) {
            editor.putFloat(key, (Float) value);
        } else if ("Long".equals(type)) {
            editor.putLong(key, (Long) value);
        }

        editor.apply();
    }

    /**
     * 根据KEY和文件名,取得保存的值,否则返回默认值
     *
     * @param context
     *            上下文
     * @param sharedPreferencesFileName
     *            用SharedPreferences保存的文件名
     * @param key
     *            键值
     * @param defaultValue
     *            默认值
     * @return 返回键对应的值
     */
    public static Object get(Context context, String sharedPreferencesFileName, String key, Object defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(sharedPreferencesFileName, Context.MODE_PRIVATE);
        return get(sp, key, defaultValue);
    }

    /**
     * 根据KEY,到默认的文件中取得保存的值,否则返回默认值
     *
     * @param context
     *            上下文
     * @param key
     *            键值
     * @param defaultValue
     *            键对应的值
     * @return
     */
    public static Object get(Context context, String key, Object defaultValue) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        return get(sp, key, defaultValue);
    }

    private static Object get(SharedPreferences sp, String key, Object defaultValue) {
        String type = defaultValue.getClass().getSimpleName();

        if ("String".equals(type)) {
            return sp.getString(key, (String) defaultValue);
        } else if ("Integer".equals(type)) {
            return sp.getInt(key, (Integer) defaultValue);
        } else if ("Boolean".equals(type)) {
            return sp.getBoolean(key, (Boolean) defaultValue);
        } else if ("Float".equals(type)) {
            return sp.getFloat(key, (Float) defaultValue);
        } else if ("Long".equals(type)) {
            return sp.getLong(key, (Long) defaultValue);
        }

        return null;
    }

    /**
     * 根据key值删除
     *
     * @param context
     *            Context上下文
     * @param sharedPreferencesFileName
     *            用SharedPreferences保存的文件名
     * @param key
     *            key值
     */
    public static void remove(Context context, String sharedPreferencesFileName, String key) {
        SharedPreferences sp = context.getSharedPreferences(sharedPreferencesFileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        editor.apply();
    }

    /**
     * 根据key值删除
     *
     * @param context
     *            Context上下文
     * @param key
     *            key值
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        editor.apply();
    }

    /**
     * 获取SharedPreferences中所有数据
     *
     * @param context
     *            上下文
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        return sp.getAll();
    }

    /**
     * 获取SharedPreferences中所有数据
     *
     * @param context
     *            上下文
     * @param sharedPreferencesFileName
     *            用SharedPreferences保存的文件名
     */
    public static Map<String, ?> getAll(Context context, String sharedPreferencesFileName) {
        SharedPreferences sp = context.getSharedPreferences(sharedPreferencesFileName, Context.MODE_PRIVATE);
        return sp.getAll();
    }
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Mark Xu on 17/4/13.
 * Site: http://xuchongyang.com
 * StringsUtils 相关
 */

public class StringUtil {
    /**
     * 去除字符串中的空格、回车符、制表符等
     * @param originalString 待修改的字符
     * @return 修正完毕的字符
     */
    public String removeCharacter(String originalString) {
        Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");
        Matcher matcher = pattern.matcher(originalString);
        return matcher.replaceAll("");
    }
}
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by Mark Xu on 2017/11/9.
 * Site: http://xuchongyang.com
 */

public class NetworkUtil {
    /**
     * 网络是否连接
     * @param context 上下文
     * @return 是否连接
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            // 获取NetworkInfo对象
            NetworkInfo networkInfo = manager != null ? manager.getActiveNetworkInfo() : null;
            //判断NetworkInfo对象是否为空
            if (networkInfo != null)
                return networkInfo.isAvailable();
        }
        return false;
    }

    /**
     * 网络是否可用
     * @return ping 结果
     */
    public static boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);// ping 网址 1 次
            // 读取ping的内容,可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping 的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }

    /**
     * 移动数据开启和关闭
     * @param context 上下文
     * @param enabled 开启或关闭
     */
    public static void setMobileDataStatus(Context context, boolean enabled) {
        ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //ConnectivityManager类
        Class<?> conMgrClass = null;
        //ConnectivityManager类中的字段
        Field iConMgrField = null;
        //IConnectivityManager类的引用
        Object iConMgr = null;
        //IConnectivityManager类
        Class<?> iConMgrClass = null;
        //setMobileDataEnabled方法
        Method setMobileDataEnabledMethod = null;
        try {
            //取得ConnectivityManager类
            conMgrClass = Class.forName(conMgr.getClass().getName());
            //取得ConnectivityManager类中的对象Mservice
            iConMgrField = conMgrClass.getDeclaredField("mService");
            //设置mService可访问
            iConMgrField.setAccessible(true);
            //取得mService的实例化类IConnectivityManager
            iConMgr = iConMgrField.get(conMgr);
            //取得IConnectivityManager类
            iConMgrClass = Class.forName(iConMgr.getClass().getName());

            //取得IConnectivityManager类中的setMobileDataEnabled(boolean)方法
            setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);

            //设置setMobileDataEnabled方法是否可访问
            setMobileDataEnabledMethod.setAccessible(true);
            //调用setMobileDataEnabled方法
            setMobileDataEnabledMethod.invoke(iConMgr, enabled);
        } catch(ClassNotFoundException | NoSuchFieldException | SecurityException | NoSuchMethodException |
                IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取移动数据开关状态
     * @param context 上下文
     * @return 移动数据开关状态
     */
    public static boolean getMobileDataStatus(Context context) {
        ConnectivityManager cm;
        cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Class cmClass = cm.getClass();
        Class[] argClasses = null;
        Object[] argObject = null;
        Boolean isOpen = false;
        try {
            Method method = cmClass.getMethod("getMobileDataEnabled", argClasses);
            isOpen = (Boolean)method.invoke(cm, argObject);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return isOpen;
    }

    /**
     * 获取设备已连接 Wi-Fi 的 MAC 地址
     * @param context 上下文
     * @return MAC 地址
     */
    public static String getConnectedWifiMacAddress(Context context) {
        String connectedWifiMacAddress = null;
        android.net.wifi.WifiManager wifiManager = (android.net.wifi.WifiManager)
                context.getSystemService(Context.WIFI_SERVICE);
        List<ScanResult> wifiList;

        if (wifiManager != null) {
            wifiList = wifiManager.getScanResults();
            WifiInfo info = wifiManager.getConnectionInfo();
            if (wifiList != null && info != null) {
                for (int i = 0; i < wifiList.size(); i++) {
                    ScanResult result = wifiList.get(i);
                    if (info.getBSSID().equals(result.BSSID)) {
                        connectedWifiMacAddress = result.BSSID;
                    }
                }
            }
        }
        return connectedWifiMacAddress;
    }
}