package cn.ylong.com.toefl.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import cn.ylong.com.toefl.R;
import cn.ylong.com.toefl.application.ToeflEduApplication;
import cn.ylong.com.toefl.domain.ClassPager;
import cn.ylong.com.toefl.utils.Constants.Characters;
public class CommonUtils {
/**
* 获取设备的deviceid
*
* @param context
* @return
*/
public static String getDeviceId(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager.getDeviceId();
return imei;
}
/**
* 验证手机号码
*
* @param mobiles
* @return
*/
public static boolean isMobileNO(String mobiles) {
Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}
/**
* 验证密码
*
* @param mobiles
* @return
*/
public static boolean isPassword(String password) {
Pattern p = Pattern.compile("^[a-zA-Z0-9]{8,18}$");
Matcher m = p.matcher(password);
return m.matches();
}
/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean isEmailNo(String email) {
String check = "[A-Z0-9a-z_.]+@[A-Za-z0-9]+\\.[A-Za-z]{1,4}";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
return matcher.matches();
}
// /**
// * 错误提示对话框
// */
// public static void showPromptDialog(String message, Context context) {
// CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
// customBuilder.setTitle(R.string.prompt).setMessage(message).setPositiveButton(R.string.sure,
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// }).create().show();
// }
/**
* 系统错误提示对话框
*/
public static void showSystemDialog(String message, Context context) {
new AlertDialog.Builder(context).setTitle(context.getString(R.string.prompt)).setMessage(message)
.setPositiveButton(context.getString(R.string.sure), null).show();
}
/**
* 判断SDCard是否存在
*
* @return
*/
public static boolean isSDCardExist() {
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
return sdCardExist;
}
/**
* 获得SDCard路径
*
* @return
*/
public static String getSDPath() {
File sdDir = null;
if (isSDCardExist()) {
sdDir = Environment.getExternalStorageDirectory();
}
return sdDir.toString();
}
/**
* 获得pdf图片存放路径
*
* @param context
* @return
*/
public static String getPDFPath(Context context) {
String rootPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/PDF";
return rootPath;
}
/**
* 获得TPO存放的路径
*
* @param context
* @return
*/
public static String getTPOPath(Context context) {
String rootPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/TPO";
return rootPath;
}
/**
* 获得APK存放的路径
*
* @param context
* @return
*/
public static String getAPKPath(Context context) {
String rootPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName();
return rootPath;
}
/**
* 获得VIDEO存放路径
*
* @param context
* @return
*/
public static String getVideoPath(Context context) {
String rootPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/VIDEO";
return rootPath;
}
/**
* 获得录制语音的存放路径
*
* @param context
* @return
*/
public static String getRecordPath(Context context) {
String rootPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/RECORD/";
return rootPath;
}
/**
* 获得存放数据的路径
*
* @param context
* @return
*/
public static String getDictionaryPath(Context context) {
String dictionaryPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/databases";
return dictionaryPath;
}
/**
* 存放测试试卷的路径
*
* @param context
* @return
*/
public static String getTestPagerPath(Context context) {
String pagerPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/testpager";
return pagerPath;
}
/**
* 存放用户信息的路径 登录,注册使用
*
* @param context
* @return
*/
public static String getLoginPath(Context context) {
String pagerPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/LOGIN";
return pagerPath;
}
/**
* pagecache
*
* @param context
* @return
*/
public static String getPageCache(Context context) {
String pagerPath = getSDPath() + "/Android/data/" + ToeflEduApplication.getInstance().getPackageName() + "/pagercache/";
return pagerPath;
}
/**
* 判断当前网络是否可用 不可用
*
* @param context
* @return
*/
public static boolean isNetworkConnection(final Context context) {
boolean flag = false;
ConnectivityManager manager = (ConnectivityManager) ToeflEduApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager.getActiveNetworkInfo() != null) {
flag = manager.getActiveNetworkInfo().isAvailable();
}
return flag;
}
/**
* 判断当前网络是否可用 不可用跳转到设置网络界面
*
* @param context
* @return
*/
public static boolean checkNetworkState(final Context context) {
boolean flag = false;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager.getActiveNetworkInfo() != null) {
flag = manager.getActiveNetworkInfo().isAvailable();
}
if (!flag) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getString(R.string.prompt));
builder.setMessage(context.getString(R.string.network_is_available));
builder.setPositiveButton(context.getString(R.string.setting), new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
Intent mIntent = new Intent("android.settings.WIRELESS_SETTINGS");
context.startActivity(mIntent);
dialog.dismiss();
}
});
builder.setNegativeButton(context.getString(R.string.cancle), new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
builder.show();
}
return flag;
}
/**
* 判读网络是否为WIFI
*
* @param context
* @return
*/
public static boolean checkNetworkStateIsWifi(final Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else {
return false;
}
}
return false;
}
/**
* 获取和保存当前屏幕的截图
*/
@SuppressWarnings("deprecation")
public static String getAndSaveCurrentImage(Activity activity) {
WindowManager windowManager = activity.getWindowManager();
Display display = windowManager.getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
View decorview = activity.getWindow().getDecorView();
decorview.setDrawingCacheEnabled(true);
Bmp = decorview.getDrawingCache();
String SavePath = getSDPath() + "/Android/data/" + activity.getPackageName() + "/printscreen";
String filepath = "";
try {
File path = new File(SavePath);
filepath = SavePath + "/Screen_1.png";
File file = new File(filepath);
if (!path.exists()) {
path.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
fos = new FileOutputStream(file);
if (null != fos) {
Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return filepath;
}
// /**
// * Create a video thumbnail for a video. May return null if the video is
// * corrupt.
// *
// * @param filePath
// */
public static String createVideoThumbnail(Bitmap bitmap, Activity activity) {
String SavePath = getSDPath() + "/Android/data/" + activity.getPackageName() + "/printscreen";
String filepath = "";
try {
File path = new File(SavePath);
filepath = SavePath + "/Screen_1.png";
File file = new File(filepath);
if (!path.exists()) {
path.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
fos = new FileOutputStream(file);
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return filepath;
// return bitmap;
}
public static String createNewVideoThumbnail(Bitmap bitmap, Activity activity, String videoname) {
String SavePath = getSDPath() + "/Android/data/" + activity.getPackageName() + "/printscreen";
String filepath = "";
try {
File path = new File(SavePath);
filepath = SavePath + "/" + videoname + ".png";
File file = new File(filepath);
if (!path.exists()) {
path.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
fos = new FileOutputStream(file);
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return filepath;
// return bitmap;
}
/**
* SDCard 总容量大小
*
* @return GB
*/
@SuppressWarnings("deprecation")
public static long getTotalSize() {
File file = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(file.getPath());
// 获得sdcard上 block的总数
long blockCount = statFs.getBlockCount();
// 获得sdcard上每个block 的大小
long blockSize = statFs.getBlockSize();
// 计算标准大小使用:1024,当然使用1000也可以
long bookTotalSize = blockCount * blockSize / 1000 / 1000 / 1000;
return bookTotalSize;
}
/**
* 计算Sdcard的剩余大小
*
* @return GB
*/
@SuppressWarnings("deprecation")
public static long getAvailableSize() {
File file = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(file.getPath());
// 获得Sdcard上每个block的size
long blockSize = statFs.getBlockSize();
// 获取可供程序使用的Block数量
long blockavailable = statFs.getAvailableBlocks();
// 计算标准大小使用:1024,当然使用1000也可以
long blockavailableTotal = blockSize * blockavailable / 1000 / 1000 / 1000;
return blockavailableTotal;
}
/**
* 时间转换为时、分、秒
*
* @param time
* @return
*/
public static String timeToString(long time) {
long hour = time / 3600;
long minute = time / 60 % 60;
long second = time % 60;
String fs = hour + "小时" + minute + "分钟" + second + "秒";
return fs;
}
public static String timeToString2(long time) {
long hour = time / 3600;
long minute = time / 60 % 60;
long second = time % 60;
String hourString;
String minuteString;
String secondString;
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = hour + "";
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = minute + "";
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = second + "";
}
String fs = hourString + ":" + minuteString + ":" + secondString;
return fs;
}
public static String timeToStringNew(String time) {
String hourString = null;
String minuteString = null;
String secondString = null;
String fs = "00:00:00";
if (time != null && !"".equals(time)) {
if (time.contains("时")) {
String str = time.replace("小时", ":").replace("分", ":").replace("秒", "");
String[] strs = str.split(":");
if (strs.length == 3) {
int i = Integer.parseInt(strs[0]);
int x = Integer.parseInt(strs[1]);
int y = Integer.parseInt(strs[2]);
if (i < 10) {
hourString = "0" + i;
} else {
hourString = i + "";
}
if (x < 10) {
minuteString = "0" + x;
} else {
minuteString = x + "";
}
if (y < 10) {
secondString = "0" + y;
} else {
secondString = y + "";
}
}
fs = hourString + ":" + minuteString + ":" + secondString;
return fs;
} else if (time.contains("分")) {
String str = time.replace("分", ":").replace("秒", "");
String[] s = time.split("分");
int it = Integer.parseInt(s[0]) * 60;
int it2 = 0;
if (s.length > 1 && s[1].contains("秒")) {
String[] ss = s[1].split("秒");
it2 = Integer.parseInt(ss[0]);
}
int z = it + it2;
long zz = z;
String fss = timeToString2(zz);
return fss;
} else {
String str = time.replace("秒", "");
int i = 0;
if (str.equals("")) {
i = 0;
} else {
String[] strs = str.split(":");
i = Integer.parseInt(strs[0]);
}
if (i < 10) {
hourString = "0" + i;
} else {
hourString = i + "";
}
fs = "00:" + "00" + ":" + hourString;
}
}
return fs;
}
/**
* 毫秒转换为分秒
*
* @param time
* @return
*/
// public static String secondChangeString(long time) {
// long minutes = (time % (1000 * 60 * 60)) / (1000 * 60);
// long seconds = (time % (1000 * 60)) / 1000;
//
// if (minutes <= 9 && seconds > 9) {
// return "0" + minutes + " : " + seconds;
// } else if (minutes > 9 && seconds <= 9) {
// return minutes + " : 0" + seconds;
// } else if (minutes > 9 && seconds > 9) {
// return minutes + " : " + seconds;
// } else if (minutes <= 9 && seconds <= 9) {
// return "0" + minutes + " : 0" + seconds;
// }
// return "";
// }
/**
* mp3 时间
*
* @param time
* @return
*/
public static String format(int time) {
SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
return formatter.format(time);
}
/**
* 秒转换为时分秒
*
* @param time
* @return
*/
public static String videoLength(int time) {
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
return formatter.format(time);
}
/**
* 00:00 转换为毫秒
*
* @param time
* @return
*/
public static int stringTimeToMillTime(String time) {
String[] my = time.split(":");
int min = Integer.parseInt(my[0]);
int sec = Integer.parseInt(my[1]);
int totalSec = (min * 60 + sec) * 1000;
return totalSec;
}
/**
* 加载本地图片
*
* @param url
* @return
*/
public static Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取UUID
*
* @return
*/
public static String getUUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
/**
* 转换为A、B....
*
* @param position
* @return
*/
public synchronized static String positonChangeSgin(int position) {
String answer = "";
switch (position) {
case Characters.POSITION_ONE:
answer = Characters.CHARACTER_A;
break;
case Characters.POSITION_TWO:
answer = Characters.CHARACTER_B;
break;
case Characters.POSITION_THREE:
answer = Characters.CHARACTER_C;
break;
case Characters.POSITION_FOUR:
answer = Characters.CHARACTER_D;
break;
case Characters.POSITION_FIVE:
answer = Characters.CHARACTER_E;
break;
case Characters.POSITION_SIX:
answer = Characters.CHARACTER_F;
break;
case Characters.POSITION_SEVEN:
answer = Characters.CHARACTER_G;
break;
case Characters.POSITION_EIGHT:
answer = Characters.CHARACTER_H;
break;
case Characters.POSITION_NINE:
answer = Characters.CHARACTER_I;
break;
default:
break;
}
return answer;
}
/**
* 转换为1,2,3。。。
*
* @param sgin
* @return
*/
public synchronized static int sginChangePosition(String sgin) {
int position = 0;
if (sgin.equals(Characters.CHARACTER_A)) {
position = Characters.POSITION_ONE;
} else if (sgin.equals(Characters.CHARACTER_B)) {
position = Characters.POSITION_TWO;
} else if (sgin.equals(Characters.CHARACTER_C)) {
position = Characters.POSITION_THREE;
} else if (sgin.equals(Characters.CHARACTER_D)) {
position = Characters.POSITION_FOUR;
} else if (sgin.equals(Characters.CHARACTER_E)) {
position = Characters.POSITION_FIVE;
} else if (sgin.equals(Characters.CHARACTER_F)) {
position = Characters.POSITION_SIX;
} else if (sgin.equals(Characters.CHARACTER_G)) {
position = Characters.POSITION_SEVEN;
} else if (sgin.equals(Characters.CHARACTER_H)) {
position = Characters.POSITION_EIGHT;
} else if (sgin.equals(Characters.CHARACTER_I)) {
position = Characters.POSITION_NINE;
}
return position;
}
/**
* 毫秒转换为分
*
* @param s
* @return
*/
public static String millsceondChangeMinute(long s) {
int min = (int) (s / 1000 / 60);
return "" + min;
}
/**
* 小数转换为百分比
*
* @param accuracy
* @return
*/
public static String changePercentage(float accuracy) {
DecimalFormat df = new DecimalFormat("0.00%");
String accuracyString = df.format(accuracy);
if (accuracyString.equals("0.00%")) {
accuracyString = "0%";
}
return accuracyString;
}
/**
* 两个整数的百分比
*
* @param x
* @param y
* @return
*/
public static String getPercent(int x, int y) {
String baifenbi = "";
double baiy = x * 1.0;
double baiz = y * 1.0;
double fen = baiy / baiz;
DecimalFormat df1 = new DecimalFormat("##.00%");
baifenbi = df1.format(fen);
if (".00%".equals(baifenbi)) {
baifenbi = "0%";
}
if ("100.00%".equals(baifenbi)) {
baifenbi = "100%";
}
if (baifenbi.endsWith(".00%")) {
baifenbi = baifenbi.substring(0, baifenbi.length() - 4) + "%";
}
return baifenbi;
}
/**
* 拼接Video Reading的名字
*
* @param tpoName
* @param passage
* @param question
* @return
*/
public static String jointVideoReadingName(Context context, String tpoName, int passage, int question) {
String localPath = getVideoPath(context) + "/" + tpoName + "/";
return localPath + tpoName + "-R-" + "P" + passage + "-Q" + question + ".mp4";
}
/**
* 拼接Video Listening的名字
*
* @param tpoName
* @param name
* @param question
* @return
*/
public static String jointVideoListeningName(Context context, String tpoName, String titleName, int question) {
String localPath = getVideoPath(context) + "/" + tpoName + "/";
String name = "";
String passageNumber = "";
if (titleName.toLowerCase().contains("conversation")) {
name = "C";
} else {
name = "L";
}
passageNumber = titleName.substring(titleName.length() - 1, titleName.length());
return localPath + tpoName + "-L-" + name + passageNumber + "-Q" + question + ".mp4";
}
/**
* 拼接Video Speaking的名字
*
* @param tpoName
* @param question
* @param type
* 1 代表解题思路 2参考答案 3习作点评
* @param comment
* @return
*/
public static String jointVideoSpeakingName(Context context, String tpoName, int question, int type, int comment) {
String localPath = getVideoPath(context) + "/" + tpoName + "/";
String baseName = tpoName + "-S-" + "Q" + question;
if (type == 1) {
return localPath + baseName + "-K" + ".mp4";
} else if (type == 2) {
return localPath + baseName + "-RA" + ".mp4";
} else {
return localPath + baseName + "-SW" + comment + "-TC.mp4";
}
}
/**
* 拼接Video Writing的名字
*
* @param tpoName
* @param type
* @param question
* @return
*/
public static String jointVideoWritingName(Context context, String tpoName, int type, int question) {
String localPath = getVideoPath(context) + "/" + tpoName + "/";
String baseName = tpoName + "-W-" + "T";
if (type == 1) {
return localPath + baseName + question + "-K.mp4";
} else {
return localPath + baseName + question + "-SW1-TC.mp4";
}
}
/**
* 获取当前应用程序的版本号
*/
public static String getVersion(Context context) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
return "";
}
}
/**
* 判断是否快速的点击按钮
*/
private static long lastClickTime;
public static boolean isFastDoubleClick(long waitTime) {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < waitTime) {
return true;
}
lastClickTime = time;
return false;
}
/**
* 获取资源文件的bitmap
*
* @param context
* @param resId
* @return
*/
public static Bitmap readBitMap(Context context, int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}
/**
* 给定的字符串排序
*
* @param context
* @param sortString
* @return
*/
public static String stringSort(Context context, String sortString) {
char[] a = sortString.toCharArray();
Arrays.sort(a);
String rst = new String(a);
return rst;
}
// 判断当前设备是否是模拟器。如果返回TRUE,则当前是模拟器,不是返回FALSE
public static boolean isEmulator(Context context) {
try {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId();
if (imei != null && imei.equals("000000000000000")) {
return true;
}
return (Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"));
} catch (Exception ioe) {
}
return false;
}
/**
* @return Number of bytes available on External storage
*/
@SuppressWarnings("deprecation")
public static long getAvailableSpaceInBytes() {
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace;
}
/**
* @return Number of kilo bytes available on External storage
*/
@SuppressWarnings("deprecation")
public static long getAvailableSpaceInKB() {
final long SIZE_KB = 1024L;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace / SIZE_KB;
}
/**
* @return Number of Mega bytes available on External storage
*/
@SuppressWarnings("deprecation")
public static long getAvailableSpaceInMB() {
final long SIZE_KB = 1024L;
final long SIZE_MB = SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace / SIZE_MB;
}
/**
* @return Number of gega bytes available on External storage
*/
@SuppressWarnings("deprecation")
public static long getAvailableSpaceInGB() {
final long SIZE_KB = 1024L;
final long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace / SIZE_GB;
}
public static boolean isNumeric1(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
/**
* 获取服务器图片
*
* @param imageUrl图片路径
* @return
*/
public static String getImageUrl(String imageUrl) {
if (imageUrl != null && !"".equals(imageUrl)) {
if (imageUrl.contains("http:")) {
return imageUrl;
} else {
if (imageUrl.startsWith("/")) {
imageUrl = imageUrl.substring(1);
}
String url = YLongEduProjectClient.WEB_RESOURCES_ULR + imageUrl;
return url;
}
} else {
return "";
}
}
/**
* 阅读内容组装为html样式
*/
@SuppressLint("DefaultLocale")
public static void pagerTextChangeHtmlString(ClassPager mReadingPager) {
String resourcesURL = "";
if (CommonUtils.isNetworkConnection(ToeflEduApplication.getInstance())) {
if (mReadingPager.getText().contains("http://resources.ylongedu.com")) {
resourcesURL = "";
} else {
resourcesURL = "http://resources.ylongedu.com";
}
}
String[] jsCss = new String[] { "audioslidershow.style.css", "mootools-core-1.3.2-full-nocompat.js", "jquery-1.10.2.min.js",
"jquery.jplayer.js", "jquery.audioslideshow.js" };
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("" + mReadingPager.getPassgername() + " ");
String jsCssPath = "file:///android_asset/";
for (int i = 0; i < jsCss.length; i++) {
String jC = jsCss[i];
if (jC.contains(".css")) {
stringBuilder.append("");
} else {
stringBuilder.append("");
}
}
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
stringBuilder.append("");
if (mReadingPager.getPassgername() != null && !"".equals(mReadingPager.getPassgername())) {
stringBuilder.append("" + mReadingPager.getPassgername() + "
");
}
stringBuilder.append(mReadingPager.getText());
stringBuilder.append(" ");
stringBuilder.append("");
stringBuilder
.append("");
stringBuilder.append("");
String htmlString = stringBuilder.toString();
if (!CommonUtils.isNetworkConnection(ToeflEduApplication.getInstance())) {
String cacheRoot = getPageCache(ToeflEduApplication.getInstance()) + mReadingPager.getTpoName();
Document document = Jsoup.parse(htmlString);
Element picElement = document.getElementById("picture_name");
Element audioElement = document.getElementById("audioFile");
String picText = "";
if (picElement != null) {
picText = picElement.text();
}
String audioText = "";
if (audioElement != null) {
audioText = audioElement.text();
}
String part1 = "";
if (picText != null && !"".equals(picText)) {
part1 = picText.substring(0, picText.lastIndexOf("/"));
} else if (audioText != null && !"".equals(audioText)) {
part1 = audioText.substring(0, audioText.lastIndexOf("/"));
}
String part2 = "";
if ((!"".equals(picText) && picText.toLowerCase().contains("reading"))
|| (!"".equals(audioText) && audioText.toLowerCase().contains("reading"))) {
part2 = cacheRoot + "/reading";
} else if ((!"".equals(picText) && picText.toLowerCase().contains("listening"))
|| (!"".equals(audioText) && audioText.toLowerCase().contains("listening"))) {
part2 = cacheRoot + "/listening";
} else if ((!"".equals(picText) && picText.toLowerCase().contains("speaking"))
|| (!"".equals(audioText) && audioText.toLowerCase().contains("speaking"))) {
part2 = cacheRoot + "/speaking";
} else {
part2 = cacheRoot + "/writing";
}
if (!"".equals(part1) && !"".equals(part2)) {
htmlString = htmlString.replaceAll("(?i)" + part1, part2);
}
}
mReadingPager.setHtmlString(htmlString);
}
/**
* 判断一个字符串是否含有数字
*
* @param content
* @return
*/
public static boolean hasDigit(String content) {
boolean flag = false;
Pattern p = Pattern.compile(".*\\d+.*");
Matcher m = p.matcher(content);
if (m.matches())
flag = true;
return flag;
}
/**
*
* @param str
* @param fileType例如
* :audioFile 或 picture_name
* @return
*/
public static String accessPath(String str, String fileType) {
String text = str.replaceAll("", "").replaceAll("
", "").trim();
// String questionText = text.substring(0, text.indexOf("