자바 컴 파일 에서 자주 사용 되 는 함수
39282 단어 안 드 로 이 드 학습 편
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("function elementPosition(obj) {");
stringBuilder.append("var curleft = 0,");
stringBuilder.append("curtop = 0;");
stringBuilder.append("if (obj.offsetParent) {");
stringBuilder.append("curleft = obj.offsetLeft;");
stringBuilder.append("curtop = obj.offsetTop;");
stringBuilder.append("while (obj = obj.offsetParent) {");
stringBuilder.append("curleft += obj.offsetLeft;");
stringBuilder.append("curtop += obj.offsetTop;");
stringBuilder.append("}");
stringBuilder.append("}");
stringBuilder.append("return {");
stringBuilder.append("x: curleft,");
stringBuilder.append("y: curtop");
stringBuilder.append("};");
stringBuilder.append("}");
stringBuilder.append(" ");
stringBuilder.append("");
stringBuilder.append("function initVoidePlayQuestionDiv() {");
stringBuilder.append("$(\"div[id='audio-slideshow']\")");
stringBuilder.append(".find(\"a[class='audio-pause']\").each(function (){");
stringBuilder.append("if($(this).is(':visible')){");
stringBuilder.append("$(this).trigger(\"click\");");
stringBuilder.append("}});}");
stringBuilder.append(" ");
stringBuilder.append("");
stringBuilder.append("function astart() {");
stringBuilder.append("$('.audio-slideshow').audioSlideshow({");
stringBuilder.append("jPlayerPath: \"http://resources.ylongedu.com/assets/js/\",");
stringBuilder.append("onlyPlayOne: function() {");
stringBuilder.append("if ($('.audio-pause').length > 0) {");
stringBuilder.append("$('.audio-pause').click();");
stringBuilder.append("}");
stringBuilder.append("}");
stringBuilder.append("});");
stringBuilder.append("}");
stringBuilder.append(" ");
stringBuilder.append("");
stringBuilder.append("function showProview() {");
stringBuilder.append("$('[id=customvideo]').each(function() {");
stringBuilder
.append("var audioFile = ($(this).find('#audioFile').html() != '' && $(this).find('#audioFile').html() != null ? $(this).find('#audioFile').html() : $(this).find('#audioText').html());");
stringBuilder.append("if (audioFile == '' || audioFile == null) return;");
stringBuilder.append("audioFile = '" + resourcesURL + "' + audioFile;");
stringBuilder
.append("var txt = '<div class=\"audio-slideshow\" id=\"audio-slideshow\" data-audio=\"' + audioFile + '\" data-audio-duration=\"0\" style=\" margin:0;';");
stringBuilder.append("var itemobj = $(this).children('#item');");
stringBuilder
.append("if (itemobj.length >= 1 && $(itemobj.get(0)).find('#timestart').html() != null && $(itemobj.get(0)).find('#timestart').html() != '') {} else {");
stringBuilder.append("txt += 'height:50px ';");
stringBuilder.append("}");
stringBuilder.append("txt += '\" >';");
stringBuilder
.append("if (itemobj.length >= 1 && $(itemobj.get(0)).find('#timestart').html() != null && $(itemobj.get(0)).find('#timestart').html() != '') {");
stringBuilder.append("txt += '<div class=\"audio-slides\">';");
stringBuilder.append("for (var j = 0; j < itemobj.length; j++) {");
stringBuilder.append("if ($(itemobj.get(j)).find('#timestart').html() != null && $(itemobj.get(j)).find('#timestart').html() != '') {");
stringBuilder.append("var tt = $(itemobj.get(j)).find('#timestart').html();");
stringBuilder.append("var tp = tt.split(':');");
stringBuilder.append("var ttime = parseInt(tp[0]) * 60 + parseInt(tp[1]);");
stringBuilder
.append("txt += '<img src=\"' + $(itemobj.get(j)).find('#picture_name').html() + '\" data-thumbnail=\"\" data-slide-time=\"' + ttime + '\" style=\"display: block;\"> ';");
stringBuilder.append("}");
stringBuilder.append("}");
stringBuilder.append("txt += '</div>';");
stringBuilder.append("}");
stringBuilder.append("txt += '<div class=\"audio-control-interface\" style=\"overflow:hidden;\">';");
stringBuilder.append("txt += '<div class=\"play-pause-container\">';");
stringBuilder.append("txt += '<a href=\"javascript:;\" class=\"audio-play\" tabindex=\"1\">Play</a>';");
stringBuilder.append("txt += '<a href=\"javascript:;\" class=\"audio-pause\" tabindex=\"1\">Pause</a></div> ';");
stringBuilder.append("txt += '<div class=\"time-container\">';");
stringBuilder.append("txt += '<span class=\"play-time time-font\"></span> / <span class=\"total-time time-font\"></span></div> ';");
stringBuilder.append("txt += '<div class=\"timeline\" style=\"width:100%;\">';");
stringBuilder.append("txt += '<div class=\"timeline-controls\"></div> <div class=\"playhead\"></div></div> ';");
stringBuilder.append("txt += '<div class=\"jplayer\"></div> </div> </div>';");
stringBuilder.append("$(this).html(txt);");
stringBuilder.append("});");
stringBuilder.append("$('img').each(function() {");
stringBuilder.append("var src = $(this).attr('src');");
stringBuilder.append("if (src.indexOf('http') == -1) {");
stringBuilder.append("$(this).attr('src', '" + resourcesURL + "'+ src);");
stringBuilder.append("}");
stringBuilder.append("});");
stringBuilder.append("}");
stringBuilder.append(" ");
stringBuilder.append("");
stringBuilder.append("function AutoResizeImage(maxWidth,maxHeight,objImg) {");
stringBuilder.append("var img = new Image();");
stringBuilder.append("if(objImg.attr('src') == '' || objImg.attr('src')==null ||objImg.attr('src')=='undefined'){");
stringBuilder.append("return;");
stringBuilder.append("}");
stringBuilder.append("if(objImg.attr(\"id\") == 'nochange') return;");
stringBuilder.append("img.src = objImg.attr('src');");
stringBuilder.append("var hRatio;");
stringBuilder.append("var wRatio;");
stringBuilder.append("var Ratio = 1;");
stringBuilder.append("var w = img.width;");
stringBuilder.append("var h = img.height;");
stringBuilder.append("wRatio = maxWidth / w;");
stringBuilder.append("hRatio = maxHeight / h;");
stringBuilder.append("if (maxWidth ==0 && maxHeight==0){");
stringBuilder.append("Ratio = 1;");
stringBuilder.append("}else if (maxWidth==0){");
stringBuilder.append("if (hRatio<1) Ratio = hRatio;");
stringBuilder.append(" }else if (maxHeight==0){");
stringBuilder.append("if (wRatio<1) Ratio = wRatio;");
stringBuilder.append("}else if (wRatio<1 || hRatio<1){");
stringBuilder.append("Ratio = (wRatio<=hRatio?wRatio:hRatio);");
stringBuilder.append("}");
stringBuilder.append("if (Ratio<1){");
stringBuilder.append("w = w * Ratio;");
stringBuilder.append("h = h * Ratio;");
stringBuilder.append(" }");
stringBuilder.append("objImg.css('height',h);");
stringBuilder.append("objImg.css('width', w);");
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("$(document).ready(function(){showProview(); astart(); $('img').load(function(){AutoResizeImage($(window).width()-20,0,$(this)); $(this).parent().parent('#audio-slideshow').css('height',$(this).height()+70);});}); ");
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("