一、CommonUtils工具类.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Vibrator;
import android.view.inputmethod.InputMethodManager;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ren.solid.library.R;
/**
* Created by LW
* Date:2017/9/24
* Time:10:03
*/
public class CommonUtils {
/**
* 是否存在外部存储
*
* @return
*/
public static boolean isExternalStorageExists() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
public static void hideKeyboard(Activity activity) {
try {
((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/*
* 打开设置网络界面
*/
public static void setNetwork(final Context context) {
// 提示对话框
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
try {
builder.setTitle("网络设置提示")
.setMessage("网络连接不可用,是否进行设置?")
.setPositiveButton("设置",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Intent intent = null;
// 判断手机系统的版本 即API大于10 就是3.0或以上版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调用震动器
*
* @param context 调用该方法的Context
* @param milliseconds 震动的时长,单位是毫秒
*/
public static void vibrate(final Context context, long milliseconds) {
Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
vib.vibrate(milliseconds);
}
/**
* 调用震动器
*
* @param context 调用该方法的Context
* @param pattern 自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒
* @param isRepeat 是否反复震动,如果是true,反复震动,如果是false,只震动一次
*/
public static void vibrate(final Context context, long[] pattern, boolean isRepeat) {
Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
vib.vibrate(pattern, isRepeat ? 1 : -1);
}
/**
* 播放音乐
*
* @param context
*/
public static void playMusic(Context context) {
MediaPlayer mp = MediaPlayer.create(context, R.raw.beep);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
}
}
二、DateUtils工具类对日期处理。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by _SOLID
* Date:2017/9/24
* Time:9:58
*/
public class DateUtils {
public static SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
public static SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
/**
* 格式化日期
*
* @param date
* @return 年月日
*/
public static String formatDate(Date date) {
return formatDate.format(date);
}
/**
* 格式化日期
*
* @param date
* @return 年月日 时分秒
*/
public static String formatDateTime(Date date) {
return formatDateTime.format(date);
}
/**
* 判断是不是今天
*
* @param date
* @return
*/
public static boolean isToday(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.setTime(date);
return year == calendar.get(Calendar.YEAR)
&& month == calendar.get(Calendar.MONTH)
&& day == calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 将时间戳解析成日期
*
* @param timeInMillis
* @return 年-月-日
*/
public static String parseDate(long timeInMillis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeInMillis);
Date date = calendar.getTime();
return formatDate(date);
}
/**
* 将时间戳解析成日期
*
* @param timeInMillis
* @return 年-月-日 时:分:秒
*/
public static String parseDateTime(long timeInMillis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeInMillis);
Date date = calendar.getTime();
return formatDateTime(date);
}
/**
* 解析日期
*
* @param date 年-月-日
* @return
*/
public static Date parseDate(String date) {
Date mDate = null;
try {
mDate = formatDate.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return mDate;
}
/**
* 解析日期
*
* @param datetime
* @return
*/
public static Date parseDateTime(String datetime) {
Date mDate = null;
try {
mDate = formatDateTime.parse(datetime);
} catch (ParseException e) {
e.printStackTrace();
}
return mDate;
}
/**
* 以友好的方式显示时间
*
* @param sdate
* @return
*/
public static String friendlyTime(String sdate) {
Date time = parseDateTime(sdate);
if (time == null) {
return "Unknown";
}
String ftime = "";
Calendar cal = Calendar.getInstance();
// 判断是否是同一天
String curDate = formatDate.format(cal.getTime());
String paramDate = formatDate.format(time);
if (curDate.equals(paramDate)) {
int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
if (hour == 0)
ftime = Math.max(
(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
+ "分钟前";
else
ftime = hour + "小时前";
return ftime;
}
long lt = time.getTime() / 86400000;
long ct = cal.getTimeInMillis() / 86400000;
int days = (int) (ct - lt);
if (days == 0) {
int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
if (hour == 0)
ftime = Math.max(
(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
+ "分钟前";
else
ftime = hour + "小时前";
} else if (days == 1) {
ftime = "昨天";
} else if (days == 2) {
ftime = "前天";
} else if (days > 2 && days <= 10) {
ftime = days + "天前";
} else if (days > 10) {
ftime = formatDate.format(time);
}
return ftime;
}
}
三、FileUtils工具栏对文件处理。
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by LW
* Date:2017/9/24
* Time:15:01
*/
public class FileUtils {
private static String TAG = "FileUtils";
private static String FILE_WRITING_ENCODING = "UTF-8";
private static String FILE_READING_ENCODING = "UTF-8";
public static String readFile(String _sFileName, String _sEncoding) throws Exception {
StringBuffer buffContent = null;
String sLine;
FileInputStream fis = null;
BufferedReader buffReader = null;
if (_sEncoding == null || "".equals(_sEncoding)) {
_sEncoding = FILE_READING_ENCODING;
}
try {
fis = new FileInputStream(_sFileName);
buffReader = new BufferedReader(new InputStreamReader(fis,
_sEncoding));
boolean zFirstLine = "UTF-8".equalsIgnoreCase(_sEncoding);
while ((sLine = buffReader.readLine()) != null) {
if (buffContent == null) {
buffContent = new StringBuffer();
} else {
buffContent.append("\n");
}
if (zFirstLine) {
sLine = removeBomHeaderIfExists(sLine);
zFirstLine = false;
}
buffContent.append(sLine);
}// end while
return (buffContent == null ? "" : buffContent.toString());
} catch (FileNotFoundException ex) {
throw new Exception("要读取的文件没有找到!", ex);
} catch (IOException ex) {
throw new Exception("读取文件时错误!", ex);
} finally {
// 增加异常时资源的释放
try {
if (buffReader != null)
buffReader.close();
if (fis != null)
fis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static File writeFile(String path, String content, String encoding, boolean isOverride) throws Exception {
if (TextUtils.isEmpty(encoding)) {
encoding = FILE_WRITING_ENCODING;
}
InputStream is = new ByteArrayInputStream(content.getBytes(encoding));
return writeFile(is, path, isOverride);
}
public static File writeFile(InputStream is, String path, boolean isOverride) throws Exception {
String sPath = extractFilePath(path);
if (!pathExists(sPath)) {
makeDir(sPath, true);
}
if (!isOverride && fileExists(path)) {
if (path.contains(".")) {
String suffix = path.substring(path.lastIndexOf("."));
String pre = path.substring(0, path.lastIndexOf("."));
path = pre + "_" + System.currentTimeMillis() + suffix;
} else {
path = path + "_" + System.currentTimeMillis();
}
}
FileOutputStream os = null;
File file = null;
try {
file = new File(path);
os = new FileOutputStream(file);
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = is.read(bytes)) != -1) {
os.write(bytes, 0, byteCount);
}
os.flush();
return file;
} catch (Exception e) {
e.printStackTrace();
throw new Exception("写文件错误", e);
} finally {
try {
if (os != null)
os.close();
if (is != null)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 移除字符串中的BOM前缀
*
* @param _sLine 需要处理的字符串
* @return 移除BOM后的字符串.
*/
private static String removeBomHeaderIfExists(String _sLine) {
if (_sLine == null) {
return null;
}
String line = _sLine;
if (line.length() > 0) {
char ch = line.charAt(0);
// 使用while是因为用一些工具看到过某些文件前几个字节都是0xfffe.
// 0xfeff,0xfffe是字节序的不同处理.JVM中,一般是0xfeff
while ((ch == 0xfeff || ch == 0xfffe)) {
line = line.substring(1);
if (line.length() == 0) {
break;
}
ch = line.charAt(0);
}
}
return line;
}
/**
* 从文件的完整路径名(路径+文件名)中提取 路径(包括:Drive+Directroy )
*
* @param _sFilePathName
* @return
*/
public static String extractFilePath(String _sFilePathName) {
int nPos = _sFilePathName.lastIndexOf('/');
if (nPos < 0) {
nPos = _sFilePathName.lastIndexOf('\\');
}
return (nPos >= 0 ? _sFilePathName.substring(0, nPos + 1) : "");
}
/**
* 检查指定文件的路径是否存在
*
* @param _sPathFileName 文件名称(含路径)
* @return 若存在,则返回true;否则,返回false
*/
public static boolean pathExists(String _sPathFileName) {
String sPath = extractFilePath(_sPathFileName);
return fileExists(sPath);
}
public static boolean fileExists(String _sPathFileName) {
File file = new File(_sPathFileName);
return file.exists();
}
/**
* 创建目录
*
* @param _sDir 目录名称
* @param _bCreateParentDir 如果父目录不存在,是否创建父目录
* @return
*/
public static boolean makeDir(String _sDir, boolean _bCreateParentDir) {
boolean zResult = false;
File file = new File(_sDir);
if (_bCreateParentDir)
zResult = file.mkdirs(); // 如果父目录不存在,则创建所有必需的父目录
else
zResult = file.mkdir(); // 如果父目录不存在,不做处理
if (!zResult)
zResult = file.exists();
return zResult;
}
public static void moveRawToDir(Context context, String rawName, String dir) {
try {
writeFile(context.getAssets().open(rawName), dir, true);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
}
/**
* 得到手机的缓存目录
*
* @param context
* @return
*/
public static File getCacheDir(Context context) {
Log.i("getCacheDir", "cache sdcard state: " + Environment.getExternalStorageState());
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File cacheDir = context.getExternalCacheDir();
if (cacheDir != null && (cacheDir.exists() || cacheDir.mkdirs())) {
Log.i("getCacheDir", "cache dir: " + cacheDir.getAbsolutePath());
return cacheDir;
}
}
File cacheDir = context.getCacheDir();
Log.i("getCacheDir", "cache dir: " + cacheDir.getAbsolutePath());
return cacheDir;
}
/**
* 得到皮肤目录
*
* @param context
* @return
*/
public static File getSkinDir(Context context) {
File skinDir = new File(getCacheDir(context), "skin");
if (skinDir.exists()) {
skinDir.mkdirs();
}
return skinDir;
}
public static String getSkinDirPath(Context context) {
return getSkinDir(context).getAbsolutePath();
}
public static String getSaveImagePath(Context context) {
String path = getCacheDir(context).getAbsolutePath();
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + Environment.DIRECTORY_DCIM;
} else {
path = path + File.separator + "Pictures";
}
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
return path;
}
public static String generateFileNameByTime() {
return System.currentTimeMillis() + "";
}
public static String getFileName(String path) {
int index = path.lastIndexOf('/');
return path.substring(index + 1);
}
}
四、KeyBoardUtils工具类对系统快keyboard进行显示或关闭。
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* Created by LW
* Date:2017/9/24
* Time:9:30
*/
public final class KeyboardUtils {
private KeyboardUtils() {
}
public static void showKeyboard(Activity activity, View view) {
if (activity != null) {
if (view != null) {
view.requestFocus();
}
InputMethodManager imm = (InputMethodManager)
activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
public static void hideKeyboard(Activity activity) {
if (activity != null) {
InputMethodManager imm = (InputMethodManager)
activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && activity.getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
activity.getCurrentFocus().clearFocus();
}
}
}
public static void hideKeyboard(Activity activity, View view) {
if (activity != null) {
if (view != null) {
InputMethodManager imm = (InputMethodManager)
activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} else {
hideKeyboard(activity);
}
}
}
}
五、NetworkUtils工具类,对网络相关进行操作。
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
*
* author: LW
* blog : http://blankj.com
* time : 2017/9/24
* desc : 网络相关工具类
*
*/
public class NetworkUtil {
private NetworkUtil() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public static final int NETWORK_WIFI = 1; // wifi network
public static final int NETWORK_4G = 4; // "4G" networks
public static final int NETWORK_3G = 3; // "3G" networks
public static final int NETWORK_2G = 2; // "2G" networks
public static final int NETWORK_UNKNOWN = 5; // unknown network
public static final int NETWORK_NO = -1; // no network
private static final int NETWORK_TYPE_GSM = 16;
private static final int NETWORK_TYPE_TD_SCDMA = 17;
private static final int NETWORK_TYPE_IWLAN = 18;
private static final String CMCC_ISP = "46000"; //中国移动
private static final String CMCC2_ISP = "46002";//中国移动
private static final String CU_ISP = "46001"; //中国联通
private static final String CT_ISP = "46003"; //中国电信
/**
* 打开网络设置界面
* 3.0以下打开设置界面
*
* @param context 上下文
*/
public static void openWirelessSettings(Context context) {
if (android.os.Build.VERSION.SDK_INT > 10) {
context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
} else {
context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
}
/**
* 获取活动网络信息
*
* @param context 上下文
* @return NetworkInfo
*/
private static NetworkInfo getActiveNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
/**
* 判断网络是否可用
* 需添加权限 {@code }
*
* @param context 上下文
* @return {@code true}: 可用
{@code false}: 不可用
*/
public static boolean isAvailable(Context context) {
NetworkInfo info = getActiveNetworkInfo(context);
return info != null && info.isAvailable();
}
/**
* 判断网络是否连接
* 需添加权限 {@code }
*
* @param context 上下文
* @return {@code true}: 是
{@code false}: 否
*/
public static boolean isConnected(Context context) {
NetworkInfo info = getActiveNetworkInfo(context);
return info != null && info.isConnected();
}
/**
* 判断网络是否是4G
* 需添加权限 {@code }
*
* @param context 上下文
* @return {@code true}: 是
{@code false}: 不是
*/
public static boolean is4G(Context context) {
NetworkInfo info = getActiveNetworkInfo(context);
return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
}
/**
* 判断wifi是否连接状态
* 需添加权限 {@code }
*
* @param context 上下文
* @return {@code true}: 连接
{@code false}: 未连接
*/
public static boolean isWifiConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm != null && cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* 获取移动网络运营商名称
* 中国移动、如中国联通、中国电信
*
* @param context 上下文
* @return 移动网络运营商名称
*/
public static String getNetworkOperatorName(Context context) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String np = tm != null ? tm.getNetworkOperatorName() : null;
String teleCompany = "unknown";
if (np != null) {
if (np.equals(CMCC_ISP) || np.equals(CMCC2_ISP)) {
teleCompany = "中国移动";
} else if (np.startsWith(CU_ISP)) {
teleCompany = "中国联通";
} else if (np.startsWith(CT_ISP)) {
teleCompany = "中国电信";
}
}
return teleCompany;
}
/**
* 获取移动终端类型
*
* @param context 上下文
* @return 手机制式
*
* - {@link TelephonyManager#PHONE_TYPE_NONE } : 0 手机制式未知
* - {@link TelephonyManager#PHONE_TYPE_GSM } : 1 手机制式为GSM,移动和联通
* - {@link TelephonyManager#PHONE_TYPE_CDMA } : 2 手机制式为CDMA,电信
* - {@link TelephonyManager#PHONE_TYPE_SIP } : 3
*
*/
public static int getPhoneType(Context context) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getPhoneType() : -1;
}
/**
* 获取当前的网络类型(WIFI,2G,3G,4G)
* 需添加权限 {@code }
*
* @param context 上下文
* @return 网络类型
*
* - {@link #NETWORK_WIFI } = 1;
* - {@link #NETWORK_4G } = 4;
* - {@link #NETWORK_3G } = 3;
* - {@link #NETWORK_2G } = 2;
* - {@link #NETWORK_UNKNOWN} = 5;
* - {@link #NETWORK_NO } = -1;
*
*/
public static int getNetWorkType(Context context) {
int netType = NETWORK_NO;
NetworkInfo info = getActiveNetworkInfo(context);
if (info != null && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
netType = NETWORK_WIFI;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
switch (info.getSubtype()) {
case NETWORK_TYPE_GSM:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
netType = NETWORK_2G;
break;
case NETWORK_TYPE_TD_SCDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
netType = NETWORK_3G;
break;
case NETWORK_TYPE_IWLAN:
case TelephonyManager.NETWORK_TYPE_LTE:
netType = NETWORK_4G;
break;
default:
String subtypeName = info.getSubtypeName();
if (subtypeName.equalsIgnoreCase("TD-SCDMA")
|| subtypeName.equalsIgnoreCase("WCDMA")
|| subtypeName.equalsIgnoreCase("CDMA2000")) {
netType = NETWORK_3G;
} else {
netType = NETWORK_UNKNOWN;
}
break;
}
} else {
netType = NETWORK_UNKNOWN;
}
}
return netType;
}
/**
* 获取当前的网络类型(WIFI,2G,3G,4G)
* 依赖上面的方法
*
* @param context 上下文
* @return 网络类型名称
*
* - NETWORK_WIFI
* - NETWORK_4G
* - NETWORK_3G
* - NETWORK_2G
* - NETWORK_UNKNOWN
* - NETWORK_NO
*
*/
public static String getNetWorkTypeName(Context context) {
switch (getNetWorkType(context)) {
case NETWORK_WIFI:
return "NETWORK_WIFI";
case NETWORK_4G:
return "NETWORK_4G";
case NETWORK_3G:
return "NETWORK_3G";
case NETWORK_2G:
return "NETWORK_2G";
case NETWORK_NO:
return "NETWORK_NO";
default:
return "NETWORK_UNKNOWN";
}
}
/**
* 根据域名获取ip地址
*
* @param domain 域名
* @return ip地址
*/
public static String getIpAddress(final String domain) {
try {
ExecutorService exec = Executors.newCachedThreadPool();
Future fs = exec.submit(new Callable() {
@Override
public String call() throws Exception {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(domain);
return inetAddress.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
}
});
return fs.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return null;
}
}
}
六、NumberUtils工具类,对电话号码运营商进行判断。
/**
* Created by LW
* Date:2017/9/24
* Time:10:12
*/
public class NumberUtils {
/**
* 中国移动拥有号码段为:139,138,137,136,135,134,159,158,157(3G),151,150,188(3G),187(3G
* );13个号段 中国联通拥有号码段为:130,131,132,156(3G),186(3G),185(3G);6个号段
* 中国电信拥有号码段为:133,153,189(3G),180(3G);4个号码段
*/
private static String mRegMobileStr = "^1(([3][456789])|([5][01789])|([8][78]))[0-9]{8}$";
private static String mRegMobile3GStr = "^((157)|(18[78]))[0-9]{8}$";
private static String mRegUnicomStr = "^1(([3][012])|([5][6])|([8][56]))[0-9]{8}$";
private static String mRegUnicom3GStr = "^((156)|(18[56]))[0-9]{8}$";
private static String mRegTelecomStr = "^1(([3][3])|([5][3])|([8][09]))[0-9]{8}$";
private static String mRegTelocom3GStr = "^(18[09])[0-9]{8}$";
private static String mRegPhoneString = "^(?:13\\d|15\\d)\\d{5}(\\d{3}|\\*{3})$";
private String mobile = "";
private int facilitatorType = 0;
private boolean isLawful = false;
private boolean is3G = false;
public NumberUtils(String mobile)
{
this.setMobile(mobile);
}
public void setMobile(String mobile)
{
if (mobile == null)
{
return;
}
/** */
/** 第一步判断中国移动 */
if (mobile.matches(NumberUtils.mRegMobileStr))
{
this.mobile = mobile;
this.setFacilitatorType(0);
this.setLawful(true);
if (mobile.matches(NumberUtils.mRegMobile3GStr))
{
this.setIs3G(true);
}
}
/** */
/** 第二步判断中国联通 */
else if (mobile.matches(NumberUtils.mRegUnicomStr))
{
this.mobile = mobile;
this.setFacilitatorType(1);
this.setLawful(true);
if (mobile.matches(NumberUtils.mRegUnicom3GStr))
{
this.setIs3G(true);
}
}
/** */
/** 第三步判断中国电信 */
else if (mobile.matches(NumberUtils.mRegTelecomStr))
{
this.mobile = mobile;
this.setFacilitatorType(2);
this.setLawful(true);
if (mobile.matches(NumberUtils.mRegTelocom3GStr))
{
this.setIs3G(true);
}
}
/** */
/** 第四步判断座机 */
if (mobile.matches(NumberUtils.mRegPhoneString))
{
this.mobile = mobile;
this.setFacilitatorType(0);
this.setLawful(true);
if (mobile.matches(NumberUtils.mRegMobile3GStr))
{
this.setIs3G(true);
}
}
}
public String getMobile()
{
return mobile;
}
public int getFacilitatorType()
{
return facilitatorType;
}
public boolean isLawful()
{
return isLawful;
}
public boolean isIs3G()
{
return is3G;
}
private void setFacilitatorType(int facilitatorType)
{
this.facilitatorType = facilitatorType;
}
private void setLawful(boolean isLawful)
{
this.isLawful = isLawful;
}
private void setIs3G(boolean is3G)
{
this.is3G = is3G;
}
}
七、StringUtils工具类,对String进行操作。
import android.util.Log;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by LW
* Date:2017/9/24
* Time:16:11
*/
public class StringUtils {
/**
* 将字符串进行md5转换
*
* @param str
* @return
*/
public static String md5(String str) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(str.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(str.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
public static boolean isNullOrEmpty(String s) {
return s == null || s.length() == 0;
}
/**
* 清除文本里面的HTML标签
*
* @param htmlStr
* @return
*/
public static String clearHTMLTag(String htmlStr) {
String regEx_script = "