转载自:https://blog.csdn.net/xiaoyi_tdcq/article/details/52902844
Android开发常用工具类集合
android开发中为了避免重复造轮子,一些常用的工具类可以整理和收集一下,方便下次使用。
主要包括:时间获取转换类、加密工具类、键盘监听工具类、图片处理工具类、网络工具类、log日志打印工具类、SD卡文件处理工具类、邮箱手机等正则验证工具类、汉字转拼音工具类等具体查看下面代码。
时间帮助类
package com.example.xiaoyi.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.util.Log;
/**
* 日期工具类
*/
public class DateUtils {
/**
* 获取当前时间
*
* @param mDateFormat
* 日期格式化字符串(eg:yyyy-MM-dd hh:mm:ss,12小时制为hh,24小时制为HH)
* @return
*/
public static String getCurDateTime(SimpleDateFormat mDateFormat) {
String date = mDateFormat.format(getCurDate());
return date;
}
/**
* 获取当前日期
*
* @return
*/
public static Date getCurDate() {
return new Date(System.currentTimeMillis());
}
/**
*
* 获取当前年份
*
* @return
*/
public static int getCurYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
/**
*
* 获取当前月份
*
* @return
*/
public static int getCurMonth() {
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
/**
*
* 获取当前是几号
*
* @return
*/
public static int getCurDay() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* 将字符串格式转化成毫秒
*
* @param 字符串格式的时间 2016-10-23 10:00:00
* @param dateForma 传入解析时间Strng格式 yyyy-MM-dd HH:mm:ss
* @return time long
* **/
public static long formatDataToLong(String time,String dateForma)
{
SimpleDateFormat sf = new SimpleDateFormat(dateForma,Locale.getDefault());
Date date = null;
try
{
date = sf.parse(time);
}
catch (ParseException e)
{
Log.d("dateUtils", "ParseException:"+e.getMessage());
}
long mlong = 0;
if (date != null)
{
mlong = date.getTime();
}
return mlong;
}
/**
* 时间戳转换成本地时间
*
* @param time 时间戳
* @param dateFormat 返回格式 yyyy-MM-dd HH:mm:ss
* @param timeZone GMT-0
* @return 返回需要的格式
*/
public static String formatData(long time,String dateFormat,String timeZone)
{
time = time * 1000;
Date date = new Date(time);
SimpleDateFormat sf = new SimpleDateFormat(dateFormat,Locale.getDefault());
TimeZone t = TimeZone.getTimeZone(timeZone);
sf.setTimeZone(t);
return sf.format(date);
}
}
文件帮助类
package com.example.xiaoyi.utils;
import java.io.BufferedInputStream;
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.OutputStream;
import android.os.Environment;
import android.util.Log;
public class FileUtils {
//暂时没有用到all
private static final String TAG = "TAG";
/**
* 文件是否存在
*/
public static boolean isExist(String filePathName) {
File file = new File(filePathName);
return (!file.isDirectory() && file.exists());
}
/**
* 目录是否存在
*/
public static boolean isDirExist(String filePathName) {
if (!filePathName.endsWith("/"))
filePathName += "/";
File file = new File(filePathName);
return (file.isDirectory() && file.exists());
}
/**
* 重命名
*
* @param filePathName
* @param newPathName
*/
public static void rename(String filePathName, String newPathName) {
if (isNullString(filePathName))
return;
if (isNullString(newPathName))
return;
FileUtils.delete(newPathName); // liuwp 20120830 新名称对应的文件可能已经存在,先删除
File file = new File(filePathName);
File newFile = new File(newPathName);
file.renameTo(newFile);
}
/**
* 删除文件
*/
public static void delete(String filePathName) {
if (isNullString(filePathName))
return;
File file = new File(filePathName);
if (file.isFile() && file.exists()) {
boolean isDelete = file.delete();
if(!isDelete){
Write.debug("DelFile :delete log file fail");
}
}
}
/**
* 删除文件夹下的所有文件和文件夹
* @param fPath
* @return
*/
public static boolean deleteAllFile(String fPath) {
File myFile = new File(fPath);
if (!myFile.exists()) {
return false;
}
if (!myFile.isDirectory()) {
return false;
}
String[] tList = myFile.list();
File tempFile = null;
for (int i = 0; i < tList.length; i++) {
if (fPath.endsWith(File.separator)) {
tempFile = new File(fPath + tList[i]);
} else {
tempFile = new File(fPath + File.separator + tList[i]);
}
if (null != tempFile && tempFile.exists() && tempFile.isFile()) {
boolean isFileDelete = tempFile.delete();
if(!isFileDelete){
Write.debug("DelFile :tempFile.delete() fail");
}
}
if (tempFile.isDirectory()) {
boolean isDeleteAllFile = deleteAllFile(fPath + "/" + tList[i]);
if(!isDeleteAllFile){
Write.debug("DelFile :delete all log file fail");
}
delete(fPath + "/" + tList[i]);
return true;
}
}
return false;
}
/**
* 创建目录,整个路径上的目录都会创建
*
* @param path
*/
public static void createDir(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 尝试创建空文件 <br>
* 如果文件已经存在不操作,返回true
*
* @param path
* 路径
* @return 如果创建失败(Exception) 返回false,否则true
*/
public static boolean createEmptyFile(String path) {
File file = new File(path);
if (!file.exists()) {
try {
return file.createNewFile();
} catch (Exception e) {
return false;
}
}
return true;
}
/**
* 获取文件大小
*
* @param filePathName
* @return
*/
public static long getSize(String filePathName) {
if (isNullString(filePathName))
return 0;
File file = new File(filePathName);
if (file.isFile())
return file.length();
return 0;
}
/**
* 读取文件数据到byte数组
*
* @param filePathName
* 文件名
* @param readOffset
* 从哪里开始读
* @param readLength
* 读取长度
* @param dataBuf
* 保存数据的缓冲区
* @param bufOffset
* 从哪里保存
* @return
*/
public static boolean readData(String filePathName, int readOffset, int readLength, byte[] dataBuf, int bufOffset) {
try {
int readedTotalSize = 0;
int onceReadSize = 0;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePathName));
in.skip(readOffset);
while (readedTotalSize < readLength && (onceReadSize = in.read(dataBuf, bufOffset + readedTotalSize, readLength - readedTotalSize)) >= 0) {
readedTotalSize += onceReadSize;
}
in.read(dataBuf, bufOffset, readLength);
in.close();
in = null;
} catch (Exception e) {
return false;
}
return true;
}
/**
* 将某个流的内容输出到文件
*
* @param in
* 输入流
* @param filePathName
* 目标文件
* @return
*/
public static boolean writeFile(InputStream in, String filePathName) {
boolean flag = false;
OutputStream outStream = null;
try {
File destFile = new File(filePathName);
if (destFile.exists()) {
destFile.delete();
} else {
destFile.createNewFile();
}
outStream = new FileOutputStream(filePathName);
byte[] buffer = new byte[1024];
int count = 0;
while (true) {
int length = in.read(buffer, 0, 1024);
if (length > 0) {
outStream.write(buffer, 0, length);
} else {
break;
}
count += length;
}
if (count > 0) {
flag = true;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 判断当前字符串是否为空
*
* @param str
* @return
*/
public static boolean isNullString(String str) {
if (str == null || str.equals(""))
return true;
return false;
}
/**
* 复制文件
*
* @param fromPathName
* @param toPathName
* @return
*/
public static int copy(String fromPathName, String toPathName) {
try {
InputStream from = new FileInputStream(fromPathName);
return copy(from, toPathName);
} catch (FileNotFoundException e) {
return -1;
}
}
/**
* 复制文件
*
* @param from
* @param toPathName
* @return
*/
public static int copy(InputStream from, String toPathName) {
try {
FileUtils.delete(toPathName); // liuwp 20120925 先删除
OutputStream to = new FileOutputStream(toPathName);
byte buf[] = new byte[1024];
int c;
while ((c = from.read(buf)) > 0) {
to.write(buf, 0, c);
}
from.close();
to.close();
return 0;
} catch (Exception ex) {
return -1;
}
}
/**
* 根据zip文件路径转换为文件路径
*
* @param zipFullPath
* 必须带.zip
* @return
*/
public static String zip2FileFullPath(String zipFullPath) {
int zipIndex = zipFullPath.lastIndexOf(".zip");
int zipIndexTmp = zipFullPath.lastIndexOf(".ZIP");
String tmp = "";
if (zipIndex > -1) {
tmp = zipFullPath.substring(0, zipIndex);
} else if (zipIndexTmp > -1) {
tmp = zipFullPath.substring(0, zipIndexTmp);
}
return tmp;
}
/**
* 改变文件权限
*
* @param permission
* @param filePathName
*/
public static void chmod(String permission, String filePathName) {
try {
String command = "chmod " + permission + " " + filePathName;
Runtime runtime = Runtime.getRuntime();
runtime.exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 缓存中取出文件
* @param imageUri
* @return
*/
public static File getCacheFile(String imageUri){
File cacheFile = null;
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();
String fileName = getFileName(imageUri);
Log.d("TAG", "sdCardDir.getCanonicalPath()"+sdCardDir.getCanonicalPath());
File dir = new File(sdCardDir.getCanonicalPath()
+ AsynImageLoader.CACHE_DIR);
//File dir = new File(AsynImageLoader.CACHE_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
cacheFile = new File(dir, fileName);
Log.i(TAG, "exists:" + cacheFile.exists() + ",dir:" + dir + ",file:" + fileName);
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "getCacheFileError:" + e.getMessage());
}
return cacheFile;
}
/**
* 路径中获取文件名称
* @param path
* @return
*/
public static String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
}
加密工具类
package com.example.xiaoyi.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 加密工具类
* @author xy
*
*/
public class EncryptionUtils {
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
/**
* MD5 加密
* @return 加密后的密码
*/
public static String getMD5Str(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
Write.debug("NoSuchAlgorithmException:"+e.getMessage());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(
Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString();
}
/**
* 将摘要信息转换成SHA-256编码
* @param message 摘要信息
* @return SHA-256编码之后的字符串
*/
public static String sha256Encode(String message){
return encode("SHA-256",message);
}
/**
* 将字节数组转换为16进制的字符串
* @param byteArray 字节数组
* @return 16进制的字符串
*/
private static String byteArrayToHexString(byte[] byteArray){
StringBuffer sb = new StringBuffer();
for(byte byt:byteArray){
sb.append(byteToHexString(byt));
}
return sb.toString();
}
/**
* 将字节转换为16进制字符串
* @param byt 字节
* @return 16进制字符串
*/
private static String byteToHexString(byte byt) {
int n = byt;
if (n < 0)
n = 256 + n;
return hexDigits[n/16] + hexDigits[n%16];
}
/**
* 将摘要信息转换为相应的编码
* @param code 编码类型
* @param message 摘要信息
* @return 相应的编码字符串
*/
private static String encode(String code,String message){
MessageDigest md;
String encode = null;
try {
md = MessageDigest.getInstance(code);
encode = byteArrayToHexString(md.digest(message
.getBytes("UTF-8")));
} catch (Exception e) {
Write.debug("encode fail: "+e.getMessage());
}
return encode;
}
}
log打印帮助类
package com.example.xiaoyi.utils;
import android.util.Log;
/**
* 打印日志工具
*
* @author xiaoyi 2014年8月21日
*/
public class LogUtil {
public static final int VERBOSE = 1;
public static final int DEBUG = 2;
public static final int INFO = 3;
public static final int WARN = 4;
public static final int ERROR = 5;
public static final int NOTHING = 6;
public static final int LEVEL = VERBOSE;
public static void v(String tag, String msg) {
if (LEVEL <= VERBOSE) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (LEVEL <= DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (LEVEL <= INFO) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (LEVEL <= WARN) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if (LEVEL <= ERROR) {
Log.e(tag, msg);
}
}
}
软键盘帮助类
package com.example.xiaoyi.utils;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* 打开或关闭软键盘
*
*/
public class KeyBoardUtils {
/**
* 打卡软键盘
*
* @param mEditText
* 输入框
* @param mContext
* 上下文
*/
public static void openKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
/**
* 关闭软键盘
*
* @param mEditText
* 输入框
* @param mContext
* 上下文
*/
public static void closeKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
}
跟网络相关的工具类
package com.example.xiaoyi.utils;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.util.Log;
/**
* 跟网络相关的工具类
*
*/
public class NetUtils {
private NetUtils() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判断网络是否连接
*
* @param context
* @return
*/
public static boolean isConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != connectivity) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
/**
* 判断是否是wifi连接
*/
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* 打开网络设置界面
*/
public static void openSetting(Activity activity) {
Intent intent = new Intent("/");
ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent, 0);
}
/**
* 获取ip
*
* @return
*/
public static String getLocalIPAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& inetAddress instanceof Inet4Address) {
// return inetAddress.getAddress().toString();
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("BaseScanTvDeviceClient", "获取本机IP false =" + ex.toString());
}
return null;
}
public static String getLocalIPAddress(Context context) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = FormatIP(wifiInfo.getIpAddress());
return ipAddress;
}
public static String FormatIP(int ip) {
return Formatter.formatIpAddress(ip);
}
// /获取本机IP地址
public static String getLocalIpAddress(Context ctx) {
WifiManager wifiManager = (WifiManager) ctx
.getSystemService(android.content.Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
try {
return InetAddress.getByName(
String.format("%d.%d.%d.%d", (ipAddress & 0xff),
(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff))).toString();
} catch (UnknownHostException e) {
return null;
}
}
// 获取本机的物理地址
public static String getLocalMacAddress(Context ctx) {
WifiManager wifi = (WifiManager) ctx
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
/**
* 校验IP地址和默认网关和子网掩码之间关系是否正确
* @param ip
* @param subMask 子网掩码
* @param gate 默认网关
* @return
*/
public static boolean checkIP(String ip,String subMask,String gate){
int IPAddr = (int) ipToLong(ip);
int SubMask = (int) ipToLong(subMask);
int Gate = (int) ipToLong(gate);
int IPAndSubMask = IPAddr & SubMask;
int GateAndSubMask = Gate & SubMask;
if( 0 == SubMask)// 子网掩码不为0.0.0.0
{
return false;
}
if( IPAddr == Gate){// IP地址和网关地址不同
return false;
}
if(IPAndSubMask != GateAndSubMask){// IP所在网段和网关所在网段相同
return false;
}
if(IPAndSubMask == IPAddr){ // IP地址和IP地址的网段号不同
return false;
}
if((IPAndSubMask|(~SubMask)) == IPAddr ){// IP地址和IP地址的网段号不同
return false;
}
int SubMaskTest = (~SubMask) + 1;
if (0 != (SubMaskTest & (SubMaskTest - 1)))
{// 子网掩码合法性判断,应该是子网掩码不为0的判断。
return false;
}
int Ip1Code = (IPAddr >> 24) & 0xFF;
if(0==Ip1Code || (Ip1Code>223 && Ip1Code<255) || 255==Ip1Code )
{// IP地址最高位判断
return false;
}
return true;
}
/**
* 将127.0.0.1 形式的IP地址转换成10进制整数,这里没有进行任何错误处理
* @param strIP
* @return
*/
public static long ipToLong(String strIP) {
long[] ip = new long[4];
// 先找到IP地址字符串中.的位置
int position1 = strIP.indexOf(".");
int position2 = strIP.indexOf(".", position1 + 1);
int position3 = strIP.indexOf(".", position2 + 1);
// 将每个.之间的字符串转换成整型
ip[0] = Long.parseLong(strIP.substring(0, position1));
ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2));
ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3));
ip[3] = Long.parseLong(strIP.substring(position3 + 1));
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
}
apk相关帮助类
package com.example.xiaoyi.utils;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;
/**
* apk相关帮助类
*
*/
public class PackageUtils {
/**
* 获取app版本名称
*
* @param context
* @return 获取失败返回"",否则返回版本名称
*/
public static String getVersionName(Context ctx) {
String versionName = "";
if (ctx == null)
return versionName;
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), 0);
versionName = pi.versionName;
if (TextUtils.isEmpty(versionName)) {
return "";
}
} catch (Exception e) {
}
return versionName;
}
/**
* 获取app版本号
*
* @param context
* @return 获取失败返回-1,否则返回版本号
*/
public static int getVersionCode(Context ctx) {
int versionCode = -1;
if (ctx == null)
return versionCode;
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), 0);
versionCode = pi.versionCode;
} catch (Exception e) {
}
return versionCode;
}
/**
* 返回程序包名
*
* @param context
* @return 获取失败返回"",否则返回程序包名
*/
public static String getPackageName(Context ctx) {
if (ctx == null)
return "";
return ctx.getPackageName();
}
/**
*
* 检查包名所在的程序是否有某项权限
*
* @param context
* @param permName
* 权限名称
* @param pkgName
* 程序所在的包名
* @return
*/
public static boolean checkPermission(Context ctx, String permName,
String pkgName) {
PackageManager pm = ctx.getPackageManager();
try {
boolean isHave = (PackageManager.PERMISSION_GRANTED == pm
.checkPermission(permName, pkgName));
return isHave;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 检查当前应用是否有某项权限
*
* @param permName
* @return
*/
public static boolean checkPermission(Context ctx, String permName) {
return checkPermission(ctx, permName, ctx.getPackageName());
}
// 获取ApiKey
public static String getMetaValue(Context context, String metaKey) {
Bundle metaData = null;
String apiKey = null;
if (context == null || metaKey == null) {
return null;
}
try {
ApplicationInfo ai = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
if (null != ai) {
metaData = ai.metaData;
}
if (null != metaData) {
apiKey = metaData.getString(metaKey);
}
} catch (NameNotFoundException e) {
}
return apiKey;
}
/**
* 判断程序的运行在前台还是后台
*
* @param context
* @return 0在后台运行 大于0在前台运行 2表示当前主界面是com.xy.demo.activity.MainFragmentActivity
*/
public static int isBackground(Context context,String packageName,String bingMapMainActivityClassName) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
if (tasksInfo.size() > 0) {
ComponentName topConponent = tasksInfo.get(0).topActivity;
LogUtil.d("TAG",
"topConponent.getPackageName()..."
+ topConponent.getPackageName());
if (packageName.equals(topConponent.getPackageName())) {
// 当前的APP在前台运行
if (topConponent.getClassName().equals(
bingMapMainActivityClassName)) {
// 当前正在运行的是不是期望的Activity
LogUtil.d("TAG", bingMapMainActivityClassName+"在运行");
return 2;
}
LogUtil.d("TAG", packageName+"前台运行");
return 1;
} else {
// 当前的APP在后台运行
LogUtil.d("TAG", packageName+"后台运行");
return 0;
}
}
return 0;
}
/**
* 判断app服务是否已经在运行,如果是 则先停止服务 防止后面查询数据时超时获取其他异常
*/
public static boolean checkServerFun(Context ctx,String serviceStr)
{
// 获取Activity管理器
ActivityManager activityManger = (ActivityManager) ctx.getSystemService(ctx.ACTIVITY_SERVICE);
// 从窗口管理器中获取正在运行的Service
List<ActivityManager.RunningServiceInfo> serviceList = activityManger
.getRunningServices(60);
// 判断app服务是否已经在运行,如果是 则先停止服务 防止后面查询数据时超时获取其他异常
if (serviceList != null && serviceList.size() > 0)
{
for (int i = 0; i < serviceList.size(); i++)
{
if (serviceStr.equals(serviceList.get(i).service.getClassName()))
{
return true;
}
}
}
return false;
}
}
图片处理工具类
package com.example.xiaoyi.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
import android.os.Environment;
/**
* 图片工具类
*
*/
public class PhotoUtil {
public static String camera_path = Environment.getExternalStorageDirectory().toString()+"/e_community/image";
public static String head_image_path = Environment.getExternalStorageDirectory().toString()+"/e_community/head_image";
/**
* 将bitmap处理成黑白图片
* @param bitmap
* @return
*/
public static final Bitmap grey(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap faceIconGreyBitmap = Bitmap
.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(faceIconGreyBitmap);
Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);
ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
colorMatrix);
paint.setColorFilter(colorMatrixFilter);
canvas.drawBitmap(bitmap, 0, 0, paint);
return faceIconGreyBitmap;
}
/**
* 将图片变为圆角
*
* @param bitmap
* 原Bitmap图片
* @param pixels
* 图片圆角的弧度(单位:像素(px))
* @return 带有圆角的图片(Bitmap 类型)
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static boolean saveToSDCard(Bitmap bitmap) {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return false;
}
FileOutputStream fileOutputStream = null;
File file = new File("/sdcard/cloudTeam/Download/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = UUID.randomUUID().toString() + ".jpg";
String filePath = "/sdcard/cloudTeam/Download/" + fileName;
File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
fileOutputStream = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
fileOutputStream);
} catch (IOException e) {
return false;
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
return false;
}
}
}
return true;
}
/**
* 保存图片到本地(JPG)
*
* @param bm
* 保存的图片
* @return 图片路径
*/
public static String saveToLocal(Bitmap bm) {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return null;
}
FileOutputStream fileOutputStream = null;
File file = new File("/sdcard/cloudTeam/Images/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = UUID.randomUUID().toString() + ".jpg";
String filePath = "/sdcard/cloudTeam/Images/" + fileName;
File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
fileOutputStream = new FileOutputStream(filePath);
bm.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
} catch (IOException e) {
return null;
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
return null;
}
}
}
return filePath;
}
/**
* 保存图片到本地(PNG)
*
* @param bm
* 保存的图片
* @return 图片路径
*/
public static String saveToLocalPNG(Bitmap bm) {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return null;
}
FileOutputStream fileOutputStream = null;
File file = new File("/sdcard/cloudTeam/Images/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = UUID.randomUUID().toString() + ".png";
String filePath = "/sdcard/cloudTeam/Images/" + fileName;
File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
fileOutputStream = new FileOutputStream(filePath);
bm.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (IOException e) {
return null;
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
return null;
}
}
}
return filePath;
}
/**
* 获取缩略图图片
*
* @param imagePath
* 图片的路径
* @param width
* 图片的宽度
* @param height
* 图片的高度
* @return 缩略图图片
*/
public static Bitmap getImageThumbnail(String imagePath, int width,
int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高,注意此处的bitmap为null
bitmap = BitmapFactory.decodeFile(imagePath, options);
options.inJustDecodeBounds = false; // 设为 false
// 计算缩放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
/**
* LOMO特效
*
* @param bitmap
* 原图片
* @return LOMO特效图片
*/
public static Bitmap lomoFilter(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int dst[] = new int[width * height];
bitmap.getPixels(dst, 0, width, 0, 0, width, height);
int ratio = width > height ? height * 32768 / width : width * 32768
/ height;
int cx = width >> 1;
int cy = height >> 1;
int max = cx * cx + cy * cy;
int min = (int) (max * (1 - 0.8f));
int diff = max - min;
int ri, gi, bi;
int dx, dy, distSq, v;
int R, G, B;
int value;
int pos, pixColor;
int newR, newG, newB;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pos = y * width + x;
pixColor = dst[pos];
R = Color.red(pixColor);
G = Color.green(pixColor);
B = Color.blue(pixColor);
value = R < 128 ? R : 256 - R;
newR = (value * value * value) / 64 / 256;
newR = (R < 128 ? newR : 255 - newR);
value = G < 128 ? G : 256 - G;
newG = (value * value) / 128;
newG = (G < 128 ? newG : 255 - newG);
newB = B / 2 + 0x25;
// ==========边缘黑暗==============//
dx = cx - x;
dy = cy - y;
if (width > height)
dx = (dx * ratio) >> 15;
else
dy = (dy * ratio) >> 15;
distSq = dx * dx + dy * dy;
if (distSq > min) {
v = ((max - distSq) << 8) / diff;
v *= v;
ri = (int) (newR * v) >> 16;
gi = (int) (newG * v) >> 16;
bi = (int) (newB * v) >> 16;
newR = ri > 255 ? 255 : (ri < 0 ? 0 : ri);
newG = gi > 255 ? 255 : (gi < 0 ? 0 : gi);
newB = bi > 255 ? 255 : (bi < 0 ? 0 : bi);
}
// ==========边缘黑暗end==============//
dst[pos] = Color.rgb(newR, newG, newB);
}
}
Bitmap acrossFlushBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
acrossFlushBitmap.setPixels(dst, 0, width, 0, 0, width, height);
return acrossFlushBitmap;
}
/**
* 旧时光特效
*
* @param bmp
* 原图片
* @return 旧时光特效图片
*/
public static Bitmap oldTimeFilter(Bitmap bmp) {
int width = bmp.getWidth();
int height = bmp.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
int pixColor = 0;
int pixR = 0;
int pixG = 0;
int pixB = 0;
int newR = 0;
int newG = 0;
int newB = 0;
int[] pixels = new int[width * height];
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 0; i < height; i++) {
for (int k = 0; k < width; k++) {
pixColor = pixels[width * i + k];
pixR = Color.red(pixColor);
pixG = Color.green(pixColor);
pixB = Color.blue(pixColor);
newR = (int) (0.393 * pixR + 0.769 * pixG + 0.189 * pixB);
newG = (int) (0.349 * pixR + 0.686 * pixG + 0.168 * pixB);
newB = (int) (0.272 * pixR + 0.534 * pixG + 0.131 * pixB);
int newColor = Color.argb(255, newR > 255 ? 255 : newR,
newG > 255 ? 255 : newG, newB > 255 ? 255 : newB);
pixels[width * i + k] = newColor;
}
}
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
/**
* 暖意特效
*
* @param bmp
* 原图片
* @param centerX
* 光源横坐标
* @param centerY
* 光源纵坐标
* @return 暖意特效图片
*/
public static Bitmap warmthFilter(Bitmap bmp, int centerX, int centerY) {
final int width = bmp.getWidth();
final int height = bmp.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
int pixR = 0;
int pixG = 0;
int pixB = 0;
int pixColor = 0;
int newR = 0;
int newG = 0;
int newB = 0;
int radius = Math.min(centerX, centerY);
final float strength = 150F; // 光照强度 100~150
int[] pixels = new int[width * height];
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
int pos = 0;
for (int i = 1, length = height - 1; i < length; i++) {
for (int k = 1, len = width - 1; k < len; k++) {
pos = i * width + k;
pixColor = pixels[pos];
pixR = Color.red(pixColor);
pixG = Color.green(pixColor);
pixB = Color.blue(pixColor);
newR = pixR;
newG = pixG;
newB = pixB;
// 计算当前点到光照中心的距离,平面座标系中求两点之间的距离
int distance = (int) (Math.pow((centerY - i), 2) + Math.pow(
centerX - k, 2));
if (distance < radius * radius) {
// 按照距离大小计算增加的光照值
int result = (int) (strength * (1.0 - Math.sqrt(distance)
/ radius));
newR = pixR + result;
newG = pixG + result;
newB = pixB + result;
}
newR = Math.min(255, Math.max(0, newR));
newG = Math.min(255, Math.max(0, newG));
newB = Math.min(255, Math.max(0, newB));
pixels[pos] = Color.argb(255, newR, newG, newB);
}
}
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
/**
* 根据饱和度、色相、亮度调整图片
*
* @param bm
* 原图片
* @param saturation
* 饱和度
* @param hue
* 色相
* @param lum
* 亮度
* @return 处理后的图片
*/
public static Bitmap handleImage(Bitmap bm, int saturation, int hue, int lum) {
Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
paint.setAntiAlias(true);
ColorMatrix mLightnessMatrix = new ColorMatrix();
ColorMatrix mSaturationMatrix = new ColorMatrix();
ColorMatrix mHueMatrix = new ColorMatrix();
ColorMatrix mAllMatrix = new ColorMatrix();
float mSaturationValue = saturation * 1.0F / 127;
float mHueValue = hue * 1.0F / 127;
float mLumValue = (lum - 127) * 1.0F / 127 * 180;
mHueMatrix.reset();
mHueMatrix.setScale(mHueValue, mHueValue, mHueValue, 1);
mSaturationMatrix.reset();
mSaturationMatrix.setSaturation(mSaturationValue);
mLightnessMatrix.reset();
mLightnessMatrix.setRotate(0, mLumValue);
mLightnessMatrix.setRotate(1, mLumValue);
mLightnessMatrix.setRotate(2, mLumValue);
mAllMatrix.reset();
mAllMatrix.postConcat(mHueMatrix);
mAllMatrix.postConcat(mSaturationMatrix);
mAllMatrix.postConcat(mLightnessMatrix);
paint.setColorFilter(new ColorMatrixColorFilter(mAllMatrix));
canvas.drawBitmap(bm, 0, 0, paint);
return bmp;
}
/**
* 添加图片外边框
*
* @param context
* 上下文
* @param bm
* 原图片
* @param frameName
* 边框名称
* @return 带有边框的图片
*/
public static Bitmap combinateFrame(Context context, Bitmap bm,
String frameName) {
// 原图片的宽高
int imageWidth = bm.getWidth();
int imageHeight = bm.getHeight();
// 边框
Bitmap leftUp = decodeBitmap(context, frameName, 0);
Bitmap leftDown = decodeBitmap(context, frameName, 2);
Bitmap rightDown = decodeBitmap(context, frameName, 4);
Bitmap rightUp = decodeBitmap(context, frameName, 6);
Bitmap top = decodeBitmap(context, frameName, 7);
Bitmap down = decodeBitmap(context, frameName, 3);
Bitmap left = decodeBitmap(context, frameName, 1);
Bitmap right = decodeBitmap(context, frameName, 5);
Bitmap newBitmap = null;
Canvas canvas = null;
// 判断大小图片的宽高
int judgeWidth = 0;
int judgeHeight = 0;
if ("frame7".equals(frameName)) {
judgeWidth = leftUp.getWidth() + rightUp.getWidth()
+ top.getWidth() * 5;
judgeHeight = leftUp.getHeight() + leftDown.getHeight()
+ left.getHeight() * 5;
} else if ("frame10".equals(frameName)) {
judgeWidth = leftUp.getWidth() + rightUp.getWidth()
+ top.getWidth() * 5;
judgeHeight = leftUp.getHeight() + leftDown.getHeight()
+ left.getHeight() * 10;
} else {
judgeWidth = leftUp.getWidth() + rightUp.getWidth()
+ top.getWidth();
judgeHeight = leftUp.getHeight() + leftDown.getHeight()
+ left.getHeight();
}
// 内边框
if (imageWidth > judgeWidth && imageHeight > judgeHeight) {
// 重新定义一个bitmap
newBitmap = Bitmap.createBitmap(imageWidth, imageHeight,
Config.ARGB_8888);
canvas = new Canvas(newBitmap);
Paint paint = new Paint();
// 画原图
canvas.drawBitmap(bm, 0, 0, paint);
// 上空余宽度
int topWidth = imageWidth - leftUp.getWidth() - rightUp.getWidth();
// 上空余填充个数
int topCount = (int) Math.ceil(topWidth * 1.0f / top.getWidth());
for (int i = 0; i < topCount; i++) {
canvas.drawBitmap(top, leftUp.getWidth() + top.getWidth() * i,
0, paint);
}
// 下空余宽度
int downWidth = imageWidth - leftDown.getWidth()
- rightDown.getWidth();
// 下空余填充个数
int downCount = (int) Math.ceil(downWidth * 1.0f / down.getWidth());
for (int i = 0; i < downCount; i++) {
canvas.drawBitmap(down, leftDown.getWidth() + down.getWidth()
* i, imageHeight - down.getHeight(), paint);
}
// 左空余高度
int leftHeight = imageHeight - leftUp.getHeight()
- leftDown.getHeight();
// 左空余填充个数
int leftCount = (int) Math.ceil(leftHeight * 1.0f
/ left.getHeight());
for (int i = 0; i < leftCount; i++) {
canvas.drawBitmap(left, 0,
leftUp.getHeight() + left.getHeight() * i, paint);
}
// 右空余高度
int rightHeight = imageHeight - rightUp.getHeight()
- rightDown.getHeight();
// 右空余填充个数
int rightCount = (int) Math.ceil(rightHeight * 1.0f
/ right.getHeight());
for (int i = 0; i < rightCount; i++) {
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight() + right.getHeight() * i, paint);
}
// 画左上角
canvas.drawBitmap(leftUp, 0, 0, paint);
// 画左下角
canvas.drawBitmap(leftDown, 0, imageHeight - leftDown.getHeight(),
paint);
// 画右下角
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
imageHeight - rightDown.getHeight(), paint);
// 画右上角
canvas.drawBitmap(rightUp, imageWidth - rightUp.getWidth(), 0,
paint);
} else {
if ("frame7".equals(frameName)) {
imageWidth = leftUp.getWidth() + top.getWidth() * 5
+ rightUp.getWidth();
imageHeight = leftUp.getHeight() + left.getHeight() * 5
+ leftDown.getHeight();
} else if ("frame10".equals(frameName)) {
imageWidth = leftUp.getWidth() + top.getWidth() * 5
+ rightUp.getWidth();
imageHeight = leftUp.getHeight() + left.getHeight() * 10
+ leftDown.getHeight();
} else {
imageWidth = leftUp.getWidth() + top.getWidth()
+ rightUp.getWidth();
imageHeight = leftUp.getHeight() + left.getHeight()
+ leftDown.getHeight();
}
newBitmap = Bitmap.createBitmap(imageWidth, imageHeight,
Config.ARGB_8888);
canvas = new Canvas(newBitmap);
Paint paint = new Paint();
int newImageWidth = imageWidth - left.getWidth() - right.getWidth()
+ 5;
int newImageHeight = imageHeight - top.getHeight()
- down.getHeight() + 5;
bm = Bitmap.createScaledBitmap(bm, newImageWidth, newImageHeight,
true);
canvas.drawBitmap(bm, left.getWidth(), top.getHeight(), paint);
if ("frame7".equals(frameName)) {
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(top, leftUp.getWidth() + top.getWidth()
* i, 0, paint);
}
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(left, 0,
leftUp.getHeight() + left.getHeight() * i, paint);
}
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight() + right.getHeight() * i, paint);
}
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(down,
leftDown.getWidth() + down.getWidth() * i,
imageHeight - down.getHeight(), paint);
}
canvas.drawBitmap(leftUp, 0, 0, paint);
canvas.drawBitmap(rightUp, leftUp.getWidth() + top.getWidth()
* 5, 0, paint);
canvas.drawBitmap(leftDown, 0,
leftUp.getHeight() + left.getHeight() * 5, paint);
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
rightUp.getHeight() + right.getHeight() * 5, paint);
} else if ("frame10".equals(frameName)) {
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(top, leftUp.getWidth() + top.getWidth()
* i, 0, paint);
}
for (int i = 0; i < 10; i++) {
canvas.drawBitmap(left, 0,
leftUp.getHeight() + left.getHeight() * i, paint);
}
for (int i = 0; i < 10; i++) {
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight() + right.getHeight() * i, paint);
}
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(down,
leftDown.getWidth() + down.getWidth() * i,
imageHeight - down.getHeight(), paint);
}
canvas.drawBitmap(leftUp, 0, 0, paint);
canvas.drawBitmap(rightUp, leftUp.getWidth() + top.getWidth()
* 5, 0, paint);
canvas.drawBitmap(leftDown, 0,
leftUp.getHeight() + left.getHeight() * 10, paint);
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
rightUp.getHeight() + right.getHeight() * 10, paint);
} else {
canvas.drawBitmap(leftUp, 0, 0, paint);
canvas.drawBitmap(top, leftUp.getWidth(), 0, paint);
canvas.drawBitmap(rightUp, leftUp.getWidth() + top.getWidth(),
0, paint);
canvas.drawBitmap(left, 0, leftUp.getHeight(), paint);
canvas.drawBitmap(leftDown, 0,
leftUp.getHeight() + left.getHeight(), paint);
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight(), paint);
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
rightUp.getHeight() + right.getHeight(), paint);
canvas.drawBitmap(down, leftDown.getWidth(),
imageHeight - down.getHeight(), paint);
}
}
// 回收
leftUp.recycle();
leftUp = null;
leftDown.recycle();
leftDown = null;
rightDown.recycle();
rightDown = null;
rightUp.recycle();
rightUp = null;
top.recycle();
top = null;
down.recycle();
down = null;
left.recycle();
left = null;
right.recycle();
right = null;
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newBitmap;
}
/**
* 获取边框图片
*
* @param context
* 上下文
* @param frameName
* 边框名称
* @param position
* 边框的类型
* @return 边框图片
*/
private static Bitmap decodeBitmap(Context context, String frameName,
int position) {
try {
switch (position) {
case 0:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/leftup.png"));
case 1:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/left.png"));
case 2:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/leftdown.png"));
case 3:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/down.png"));
case 4:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/rightdown.png"));
case 5:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/right.png"));
case 6:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/rightup.png"));
case 7:
return BitmapFactory.decodeStream(context.getAssets().open(
"frames/" + frameName + "/up.png"));
default:
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 添加内边框
*
* @param bm
* 原图片
* @param frame
* 内边框图片
* @return 带有边框的图片
*/
public static Bitmap addBigFrame(Bitmap bm, Bitmap frame) {
Bitmap newBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
Paint paint = new Paint();
canvas.drawBitmap(bm, 0, 0, paint);
frame = Bitmap.createScaledBitmap(frame, bm.getWidth(), bm.getHeight(),
true);
canvas.drawBitmap(frame, 0, 0, paint);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newBitmap;
}
/**
* 创建一个缩放的图片
*
* @param path
* 图片地址
* @param w
* 图片宽度
* @param h
* 图片高度
* @return 缩放后的图片
*/
public static Bitmap createBitmap(String path, int w, int h) {
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
// 这里是整个方法的关键,inJustDecodeBounds设为true时将不为图片分配内存。
BitmapFactory.decodeFile(path, opts);
int srcWidth = opts.outWidth;// 获取图片的原始宽度
int srcHeight = opts.outHeight;// 获取图片原始高度
int destWidth = 0;
int destHeight = 0;
// 缩放的比例
double ratio = 0.0;
if (srcWidth < w || srcHeight < h) {
ratio = 0.0;
destWidth = srcWidth;
destHeight = srcHeight;
} else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度
ratio = (double) srcWidth / w;
destWidth = w;
destHeight = (int) (srcHeight / ratio);
} else {
ratio = (double) srcHeight / h;
destHeight = h;
destWidth = (int) (srcWidth / ratio);
}
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 缩放的比例,缩放是很难按准备的比例进行缩放的,目前我只发现只能通过inSampleSize来进行缩放,其值表明缩放的倍数,SDK中建议其值是2的指数值
newOpts.inSampleSize = (int) ratio + 1;
// inJustDecodeBounds设为false表示把图片读进内存中
newOpts.inJustDecodeBounds = false;
// 设置大小,这个一般是不准确的,是以inSampleSize的为准,但是如果不设置却不能缩放
newOpts.outHeight = destHeight;
newOpts.outWidth = destWidth;
// 获取缩放后图片
return BitmapFactory.decodeFile(path, newOpts);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
正则验证帮助类
package com.example.xiaoyi.utils;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.TextUtils;
/**
* 正则验证帮助类
*
* @author xy
*
*/
public class regularVerificationUtil {
/**
* 验证邮箱格式
*
* @param email
* @return
*/
public static boolean emailFormat(String email) {
boolean tag = true;
String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern pattern = Pattern.compile(pattern1);
Matcher mat = pattern.matcher(email);
if (!mat.find()) {
tag = false;
}
return tag;
}
/**
* 验证输入的邮箱格式是否符合
*
* @param email
* @return 是否合法
*/
public static boolean emailFormat2(String email) {
boolean tag = true;
final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
final Pattern pattern = Pattern.compile(pattern1);
final Matcher mat = pattern.matcher(email);
if (!mat.find()) {
tag = false;
}
return tag;
}
/**
* 判断是否是手机号码
*
* @param mobiles
* 手机号码
* @return
*/
public static boolean isMobileNO(String mobiles) {
Pattern p = Pattern
.compile("^((13[0-9])|(14[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}
/**
* 判断是否含有中文下的标点符号
*
* @param tempStr
* @return
*/
public static boolean getCnCheckResult(String tempStr) {
if (tempStr == null)
return false;
return Pattern.compile("[?!·¥()……—【】‘;:“”’。,、?]").matcher(tempStr)
.find();
}
/**
* 判断字符串,不能包含以下字符,如果包含返回true 否则返回false
* @param str
* @return
*/
public static boolean isLegalCharacter(String str){
// String regex = "[\\<\\>:\\,'‘“”\\?()#&\\$|%+\\;~^]+$";
// String regex = "[0-9a-zA-Z`!@$^*()-_=\\{\\}\\[\\]\\.\\<\\>\\/]+$";
String regex = "[\\<\\>:\\,'\"\\?()#&\\$|%+\\;~^]+$";//'导致无法连续输入中文
for (int i = 0; i < str.length(); i++) {
String tempStr = str.substring(i, i+1);
if(Pattern.compile(regex).matcher(tempStr).find()){
return true;
}
}
return false;
}
/**
* 判断字符串,只能包含以下字符,如果是返回true 否则返回false
* @param str
* @return
*/
public static boolean isLegalInput(String str){
String regex = "[0-9a-zA-Z`!@*()-_=\\{\\}\\[\\]\\.\\<\\>\\/]+$";
return Pattern.compile(regex).matcher(str).matches();
}
/**
* 判断字符串中是否是合法邮箱格式
* @param str
* @return
*/
public static boolean isLegalEmail(String email){
String check = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
return matcher.matches();
}
/**
* 是否包含中文,有中文返回true 否则返回false
* @param s
* @return
*/
public static boolean checkfilename(String s){
try {
s=new String(s.getBytes("UTF-8"),"UTF-8");
} catch (UnsupportedEncodingException e) {
Write.debug("method name --> checkfilename :"+e.getMessage());
}//用GBK编码
String pattern="[\u4e00-\u9fa5]+";
Pattern p=Pattern.compile(pattern);
Matcher result=p.matcher(s);
return result.find(); //是否含有中文字符
}
/**
* a)口令长度至少6个字符; b)口令必须包含如下至少两种字符的组合: -至少一个小写字母; -至少一个大写字母; -至少一个数字;
* -至少一个特殊字符:`~!@#$%^&*()-_=+\|[{}];:'",<.>/?和空格
*
* @param str
* @return
*/
public static boolean getCheckResult(String str) {
if (getCnCheckResult(str)) {
return false;
}
String result = check(str);
if (!TextUtils.isEmpty(result)) {
if (is_alpha(result)) {
return true;
}
}
return false;
}
public static boolean is_alpha(String alpha) {
if (alpha == null)
return false;
return Pattern.compile("[a-zA-Z|0-9]").matcher(alpha).find();
}
public static String check(String result) {
String str = "";
String regaz = "[a-z]";
String regAZ = "[A-Z]";
// String regOther = "[`~!@#$%^&*()\\-_=+\\|\\[{}\\];:'\",<.>/?\\s]";
String regDig = "[0-9]";
if (Pattern.compile(regaz).matcher(result).find()) {
return stringFilter(result, regaz);
} else if (Pattern.compile(regAZ).matcher(result).find()) {
return stringFilter(result, regAZ);
} else if (Pattern.compile(regDig).matcher(result).find()) {
return stringFilter(result, regDig);
}
return str;
}
// 过滤特殊字符
public static String stringFilter(String str, String regEx) {
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
String result = m.replaceAll("").trim();
return result;
}
}
SharedPreference数据存储工具类
package com.example.xiaoyi.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;
/**
* SharedPreference数据存储工具类
*
*/
public class SharedPreferenceUtils {
public static final String PREFERENCES_NAME = "packageName";
public SharedPreferences.Editor mEditor;
public SharedPreferences mSharedPreferences;
/**
* 必须实例化,才能调用操作方法
*/
public SharedPreferenceUtils(Context ctx) {
mSharedPreferences = ctx.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
}
public void saveBoolean(String key, boolean value) {
mEditor.putBoolean(key, value).commit();
}
public boolean getBoolean(String key, boolean defValue) {
return mSharedPreferences.getBoolean(key, defValue);
}
public void saveInt(String key, int value) {
mEditor.putInt(key, value).commit();
}
public int getInt(String key, int defValue) {
return mSharedPreferences.getInt(key, defValue);
}
public void saveFloat(String key, float value) {
mEditor.putFloat(key, value).commit();
}
public float getFloat(String key, float defValue) {
return mSharedPreferences.getFloat(key, defValue);
}
public void saveString(String key, String value) {
mEditor.putString(key, value).commit();
}
public String getString(String key, String defValue) {
return mSharedPreferences.getString(key, defValue);
}
public void saveLong(String key, long value) {
mEditor.putLong(key, value).commit();
}
public long getLong(String key, long defValue) {
return mSharedPreferences.getLong(key, defValue);
}
/**
* 保存对象,object所在的类必须实现{@link Serializable}接口
*
* @param key
* @param object
*/
public void saveObject(String key, Object object) {
if ((object instanceof Serializable) == false) {
throw new RuntimeException("请将object所在的类实现Serializable接口");
}
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
String strBase64 = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
saveString(key, strBase64);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oos.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取存储的object
*
* @param key
* @param defValue
* @return 获取成功则返回存储的object,否则返回默认值
*/
public Object getObject(String key, Object defValue) {
Object object = null;
String strBase64 = getString(key, "");
if (TextUtils.isEmpty(strBase64)) {
return defValue;
}
byte[] base64 = Base64.decode(strBase64.getBytes(), Base64.DEFAULT);
ByteArrayInputStream bais = null;
ObjectInputStream bis = null;
try {
bais = new ByteArrayInputStream(base64);
bis = new ObjectInputStream(bais);
object = bis.readObject();
return object;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return defValue;
}
}
汉字转拼音工具类
package com.example.xiaoyi.utils;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import android.text.TextUtils;
import android.util.Log;
/**
* An object to convert Chinese character to its corresponding pinyin string. For characters with
* multiple possible pinyin string, only one is selected according to collator. Polyphone is not
* supported in this implementation. This class is implemented to achieve the best runtime
* performance and minimum runtime resources with tolerable sacrifice of accuracy. This
* implementation highly depends on zh_CN ICU collation data and must be always synchronized with
* ICU.
*
* Currently this file is aligned to zh.txt in ICU 4.6
*/
public class HanziToPinyin {
private static final String TAG = "HanziToPinyin";
// Turn on this flag when we want to check internal data structure.
private static final boolean DEBUG = false;
// 汉字返回拼音,字母原样返回,都转换为小写
public static String getPinYin(String input) {
ArrayList<Token> tokens = HanziToPinyin.getInstance().get(input);
StringBuilder sb = new StringBuilder();
if (tokens != null && tokens.size() > 0) {
for (Token token : tokens) {
if (Token.PINYIN == token.type) {
sb.append(token.target);
} else {
sb.append(token.source);
}
}
}
return sb.toString().toLowerCase();
}
/**
* Unihans array. Each unihans is the first one within same pinyin. Use it to determine pinyin
* for all ~20k unihans.
*/
public static final char[] UNIHANS = {
'\u5475', '\u54ce', '\u5b89', '\u80ae', '\u51f9',
'\u516b', '\u6300', '\u6273', '\u90a6', '\u5305', '\u5351', '\u5954', '\u4f3b',
'\u5c44', '\u8fb9', '\u6807', '\u618b', '\u90a0', '\u69df', '\u7676', '\u5cec',
'\u5693', '\u5a47', '\u98e1', '\u4ed3', '\u64cd', '\u518a', '\u5d7e', '\u564c',
'\u53c9', '\u9497', '\u8fbf', '\u4f25', '\u6284', '\u8f66', '\u62bb', '\u67fd',
'\u5403', '\u5145', '\u62bd', '\u51fa', '\u6b3b', '\u63e3', '\u5ddd', '\u75ae',
'\u5439', '\u6776', '\u9034', '\u75b5', '\u5306', '\u51d1', '\u7c97', '\u6c46',
'\u5d14', '\u90a8', '\u6413', '\u5491', '\u5927', '\u75b8', '\u5f53', '\u5200',
'\u6dc2', '\u5f97', '\u6265', '\u706f', '\u6c10', '\u55f2', '\u7538', '\u5201',
'\u7239', '\u4ec3', '\u4e1f', '\u4e1c', '\u5517', '\u561f', '\u5073', '\u5806',
'\u9413', '\u591a', '\u5a40', '\u8bf6', '\u5940', '\u97a5', '\u800c', '\u53d1',
'\u5e06', '\u65b9', '\u98de', '\u5206', '\u4e30', '\u8985', '\u4ecf', '\u7d11',
'\u4f15', '\u65ee', '\u8be5', '\u7518', '\u5188', '\u768b', '\u6208', '\u7d66',
'\u6839', '\u5e9a', '\u5de5', '\u52fe', '\u4f30', '\u74dc', '\u7f6b', '\u5173',
'\u5149', '\u5f52', '\u886e', '\u5459', '\u54c8', '\u54b3', '\u9878', '\u82c0',
'\u84bf', '\u8bc3', '\u9ed2', '\u62eb', '\u4ea8', '\u5677', '\u543d', '\u9f41',
'\u5322', '\u82b1', '\u6000', '\u72bf', '\u5ddf', '\u7070', '\u660f', '\u5419',
'\u4e0c', '\u52a0', '\u620b', '\u6c5f', '\u827d', '\u9636', '\u5dfe', '\u52a4',
'\u5182', '\u52fc', '\u530a', '\u5a1f', '\u5658', '\u519b', '\u5494', '\u5f00',
'\u520a', '\u95f6', '\u5c3b', '\u533c', '\u524b', '\u80af', '\u962c', '\u7a7a',
'\u62a0', '\u5233', '\u5938', '\u84af', '\u5bbd', '\u5321', '\u4e8f', '\u5764',
'\u6269', '\u5783', '\u6765', '\u5170', '\u5577', '\u635e', '\u4ec2', '\u52d2',
'\u5844', '\u5215', '\u5006', '\u5941', '\u826f', '\u64a9', '\u5217', '\u62ce',
'\u3007', '\u6e9c', '\u9f99', '\u779c', '\u565c', '\u5a08', '\u7567', '\u62a1',
'\u7f57', '\u5463', '\u5988', '\u973e', '\u5ada', '\u9099', '\u732b', '\u9ebc',
'\u6c92', '\u95e8', '\u753f', '\u54aa', '\u7720', '\u55b5', '\u54a9', '\u6c11',
'\u540d', '\u8c2c', '\u6478', '\u54de', '\u6bea', '\u62cf', '\u5b7b', '\u56e1',
'\u56ca', '\u5b6c', '\u8bb7', '\u9981', '\u6041', '\u80fd', '\u59ae', '\u62c8',
'\u5b22', '\u9e1f', '\u634f', '\u60a8', '\u5b81', '\u599e', '\u519c', '\u7fba',
'\u5974', '\u597b', '\u8650', '\u632a', '\u5594', '\u8bb4', '\u8db4', '\u62cd',
'\u7705', '\u4e53', '\u629b', '\u5478', '\u55b7', '\u5309', '\u4e15', '\u504f',
'\u527d', '\u6c15', '\u59d8', '\u4e52', '\u948b', '\u5256', '\u4ec6', '\u4e03',
'\u6390', '\u5343', '\u545b', '\u6084', '\u767f', '\u4fb5', '\u9751', '\u909b',
'\u4e18', '\u66f2', '\u5f2e', '\u7f3a', '\u590b', '\u5465', '\u7a63', '\u5a06',
'\u60f9', '\u4eba', '\u6254', '\u65e5', '\u8338', '\u53b9', '\u5982', '\u5827',
'\u6875', '\u95f0', '\u82e5', '\u4ee8', '\u6be2', '\u4e09', '\u6852', '\u63bb',
'\u8272', '\u68ee', '\u50e7', '\u6740', '\u7b5b', '\u5c71', '\u4f24', '\u5f30',
'\u5962', '\u7533', '\u5347', '\u5c38', '\u53ce', '\u4e66', '\u5237', '\u6454',
'\u95e9', '\u53cc', '\u8c01', '\u542e', '\u5981', '\u53b6', '\u5fea', '\u635c',
'\u82cf', '\u72fb', '\u590a', '\u5b59', '\u5506', '\u4ed6', '\u82d4', '\u574d',
'\u94f4', '\u5932', '\u5fd1', '\u71a5', '\u5254', '\u5929', '\u4f7b', '\u5e16',
'\u5385', '\u56f2', '\u5077', '\u92c0', '\u6e4d', '\u63a8', '\u541e', '\u6258',
'\u6316', '\u6b6a', '\u5f2f', '\u5c2a', '\u5371', '\u586d', '\u7fc1', '\u631d',
'\u5140', '\u5915', '\u867e', '\u4eda', '\u4e61', '\u7071', '\u4e9b', '\u5fc3',
'\u661f', '\u51f6', '\u4f11', '\u65f4', '\u8f69', '\u75b6', '\u52cb', '\u4e2b',
'\u6079', '\u592e', '\u5e7a', '\u8036', '\u4e00', '\u6b2d', '\u5e94', '\u54df',
'\u4f63', '\u4f18', '\u625c', '\u9e22', '\u66f0', '\u6655', '\u531d', '\u707d',
'\u7ccc', '\u7242', '\u50ae', '\u5219', '\u8d3c', '\u600e', '\u5897', '\u5412',
'\u635a', '\u6cbe', '\u5f20', '\u948a', '\u8707', '\u8d1e', '\u4e89', '\u4e4b',
'\u4e2d', '\u5dde', '\u6731', '\u6293', '\u8de9', '\u4e13', '\u5986', '\u96b9',
'\u5b92', '\u5353', '\u5b5c', '\u5b97', '\u90b9', '\u79df', '\u94bb', '\u539c',
'\u5c0a', '\u6628', };
/**
* Pinyin array. Each pinyin is corresponding to unihans of same offset in the unihans array.
*/
public static final byte[][] PINYINS = {
{ 65, 0, 0, 0, 0, 0 }, { 65, 73, 0, 0, 0, 0 }, { 65, 78, 0, 0, 0, 0 },
{ 65, 78, 71, 0, 0, 0 }, { 65, 79, 0, 0, 0, 0 }, { 66, 65, 0, 0, 0, 0 },
{ 66, 65, 73, 0, 0, 0 }, { 66, 65, 78, 0, 0, 0 }, { 66, 65, 78, 71, 0, 0 },
{ 66, 65, 79, 0, 0, 0 }, { 66, 69, 73, 0, 0, 0 }, { 66, 69, 78, 0, 0, 0 },
{ 66, 69, 78, 71, 0, 0 }, { 66, 73, 0, 0, 0, 0 }, { 66, 73, 65, 78, 0, 0 },
{ 66, 73, 65, 79, 0, 0 }, { 66, 73, 69, 0, 0, 0 }, { 66, 73, 78, 0, 0, 0 },
{ 66, 73, 78, 71, 0, 0 }, { 66, 79, 0, 0, 0, 0 }, { 66, 85, 0, 0, 0, 0 },
{ 67, 65, 0, 0, 0, 0 }, { 67, 65, 73, 0, 0, 0 },
{ 67, 65, 78, 0, 0, 0 }, { 67, 65, 78, 71, 0, 0 }, { 67, 65, 79, 0, 0, 0 },
{ 67, 69, 0, 0, 0, 0 }, { 67, 69, 78, 0, 0, 0 }, { 67, 69, 78, 71, 0, 0 },
{ 67, 72, 65, 0, 0, 0 }, { 67, 72, 65, 73, 0, 0 }, { 67, 72, 65, 78, 0, 0 },
{ 67, 72, 65, 78, 71, 0 }, { 67, 72, 65, 79, 0, 0 }, { 67, 72, 69, 0, 0, 0 },
{ 67, 72, 69, 78, 0, 0 }, { 67, 72, 69, 78, 71, 0 }, { 67, 72, 73, 0, 0, 0 },
{ 67, 72, 79, 78, 71, 0 }, { 67, 72, 79, 85, 0, 0 }, { 67, 72, 85, 0, 0, 0 },
{ 67, 72, 85, 65, 0, 0 }, { 67, 72, 85, 65, 73, 0 }, { 67, 72, 85, 65, 78, 0 },
{ 67, 72, 85, 65, 78, 71 }, { 67, 72, 85, 73, 0, 0 }, { 67, 72, 85, 78, 0, 0 },
{ 67, 72, 85, 79, 0, 0 }, { 67, 73, 0, 0, 0, 0 }, { 67, 79, 78, 71, 0, 0 },
{ 67, 79, 85, 0, 0, 0 }, { 67, 85, 0, 0, 0, 0 }, { 67, 85, 65, 78, 0, 0 },
{ 67, 85, 73, 0, 0, 0 }, { 67, 85, 78, 0, 0, 0 }, { 67, 85, 79, 0, 0, 0 },
{ 68, 65, 0, 0, 0, 0 }, { 68, 65, 73, 0, 0, 0 }, { 68, 65, 78, 0, 0, 0 },
{ 68, 65, 78, 71, 0, 0 }, { 68, 65, 79, 0, 0, 0 }, { 68, 69, 0, 0, 0, 0 },
{ 68, 69, 73, 0, 0, 0 }, { 68, 69, 78, 0, 0, 0 }, { 68, 69, 78, 71, 0, 0 },
{ 68, 73, 0, 0, 0, 0 }, { 68, 73, 65, 0, 0, 0 }, { 68, 73, 65, 78, 0, 0 },
{ 68, 73, 65, 79, 0, 0 }, { 68, 73, 69, 0, 0, 0 }, { 68, 73, 78, 71, 0, 0 },
{ 68, 73, 85, 0, 0, 0 }, { 68, 79, 78, 71, 0, 0 }, { 68, 79, 85, 0, 0, 0 },
{ 68, 85, 0, 0, 0, 0 }, { 68, 85, 65, 78, 0, 0 }, { 68, 85, 73, 0, 0, 0 },
{ 68, 85, 78, 0, 0, 0 }, { 68, 85, 79, 0, 0, 0 }, { 69, 0, 0, 0, 0, 0 },
{ 69, 73, 0, 0, 0, 0 }, { 69, 78, 0, 0, 0, 0 }, { 69, 78, 71, 0, 0, 0 },
{ 69, 82, 0, 0, 0, 0 }, { 70, 65, 0, 0, 0, 0 }, { 70, 65, 78, 0, 0, 0 },
{ 70, 65, 78, 71, 0, 0 }, { 70, 69, 73, 0, 0, 0 }, { 70, 69, 78, 0, 0, 0 },
{ 70, 69, 78, 71, 0, 0 }, { 70, 73, 65, 79, 0, 0 }, { 70, 79, 0, 0, 0, 0 },
{ 70, 79, 85, 0, 0, 0 }, { 70, 85, 0, 0, 0, 0 }, { 71, 65, 0, 0, 0, 0 },
{ 71, 65, 73, 0, 0, 0 }, { 71, 65, 78, 0, 0, 0 }, { 71, 65, 78, 71, 0, 0 },
{ 71, 65, 79, 0, 0, 0 }, { 71, 69, 0, 0, 0, 0 }, { 71, 69, 73, 0, 0, 0 },
{ 71, 69, 78, 0, 0, 0 }, { 71, 69, 78, 71, 0, 0 }, { 71, 79, 78, 71, 0, 0 },
{ 71, 79, 85, 0, 0, 0 }, { 71, 85, 0, 0, 0, 0 }, { 71, 85, 65, 0, 0, 0 },
{ 71, 85, 65, 73, 0, 0 }, { 71, 85, 65, 78, 0, 0 }, { 71, 85, 65, 78, 71, 0 },
{ 71, 85, 73, 0, 0, 0 }, { 71, 85, 78, 0, 0, 0 }, { 71, 85, 79, 0, 0, 0 },
{ 72, 65, 0, 0, 0, 0 }, { 72, 65, 73, 0, 0, 0 }, { 72, 65, 78, 0, 0, 0 },
{ 72, 65, 78, 71, 0, 0 }, { 72, 65, 79, 0, 0, 0 }, { 72, 69, 0, 0, 0, 0 },
{ 72, 69, 73, 0, 0, 0 }, { 72, 69, 78, 0, 0, 0 }, { 72, 79, 85, 0, 0, 0 },
{ 72, 77, 0, 0, 0, 0 }, { 72, 79, 78, 71, 0, 0 }, { 72, 79, 85, 0, 0, 0 },
{ 72, 85, 0, 0, 0, 0 }, { 72, 85, 65, 0, 0, 0 }, { 72, 85, 65, 73, 0, 0 },
{ 72, 85, 65, 78, 0, 0 }, { 72, 85, 65, 78, 71, 0 }, { 72, 85, 73, 0, 0, 0 },
{ 72, 85, 78, 0, 0, 0 }, { 72, 85, 79, 0, 0, 0 }, { 74, 73, 0, 0, 0, 0 },
{ 74, 73, 65, 0, 0, 0 }, { 74, 73, 65, 78, 0, 0 }, { 74, 73, 65, 78, 71, 0 },
{ 74, 73, 65, 79, 0, 0 }, { 74, 73, 69, 0, 0, 0 }, { 74, 73, 78, 0, 0, 0 },
{ 74, 73, 78, 71, 0, 0 }, { 74, 73, 79, 78, 71, 0 }, { 74, 73, 85, 0, 0, 0 },
{ 74, 85, 0, 0, 0, 0 }, { 74, 85, 65, 78, 0, 0 }, { 74, 85, 69, 0, 0, 0 },
{ 74, 85, 78, 0, 0, 0 }, { 75, 65, 0, 0, 0, 0 }, { 75, 65, 73, 0, 0, 0 },
{ 75, 65, 78, 0, 0, 0 }, { 75, 65, 78, 71, 0, 0 }, { 75, 65, 79, 0, 0, 0 },
{ 75, 69, 0, 0, 0, 0 }, { 75, 69, 73, 0, 0, 0 }, { 75, 69, 78, 0, 0, 0 },
{ 75, 69, 78, 71, 0, 0 }, { 75, 79, 78, 71, 0, 0 }, { 75, 79, 85, 0, 0, 0 },
{ 75, 85, 0, 0, 0, 0 }, { 75, 85, 65, 0, 0, 0 }, { 75, 85, 65, 73, 0, 0 },
{ 75, 85, 65, 78, 0, 0 }, { 75, 85, 65, 78, 71, 0 }, { 75, 85, 73, 0, 0, 0 },
{ 75, 85, 78, 0, 0, 0 }, { 75, 85, 79, 0, 0, 0 }, { 76, 65, 0, 0, 0, 0 },
{ 76, 65, 73, 0, 0, 0 }, { 76, 65, 78, 0, 0, 0 }, { 76, 65, 78, 71, 0, 0 },
{ 76, 65, 79, 0, 0, 0 }, { 76, 69, 0, 0, 0, 0 }, { 76, 69, 73, 0, 0, 0 },
{ 76, 69, 78, 71, 0, 0 }, { 76, 73, 0, 0, 0, 0 }, { 76, 73, 65, 0, 0, 0 },
{ 76, 73, 65, 78, 0, 0 }, { 76, 73, 65, 78, 71, 0 }, { 76, 73, 65, 79, 0, 0 },
{ 76, 73, 78, 0, 0, 0 }, { 76, 73, 78, 0, 0, 0 }, { 76, 73, 78, 71, 0, 0 },
{ 76, 73, 85, 0, 0, 0 }, { 76, 79, 78, 71, 0, 0 }, { 76, 79, 85, 0, 0, 0 },
{ 76, 85, 0, 0, 0, 0 }, { 76, 85, 0, 0, 0, 0 }, { 76, 85, 69, 0, 0, 0 },
{ 76, 85, 78, 0, 0, 0 }, { 76, 85, 79, 0, 0, 0 }, { 77, 0, 0, 0, 0, 0 },
{ 77, 65, 0, 0, 0, 0 }, { 77, 65, 73, 0, 0, 0 }, { 77, 65, 78, 0, 0, 0 },
{ 77, 65, 78, 71, 0, 0 }, { 77, 65, 79, 0, 0, 0 }, { 77, 69, 0, 0, 0, 0 },
{ 77, 69, 73, 0, 0, 0 }, { 77, 69, 78, 0, 0, 0 }, { 77, 69, 78, 71, 0, 0 },
{ 77, 73, 0, 0, 0, 0 }, { 77, 73, 65, 78, 0, 0 }, { 77, 73, 65, 79, 0, 0 },
{ 77, 73, 69, 0, 0, 0 }, { 77, 73, 78, 0, 0, 0 }, { 77, 73, 78, 71, 0, 0 },
{ 77, 73, 85, 0, 0, 0 }, { 77, 79, 0, 0, 0, 0 }, { 77, 79, 85, 0, 0, 0 },
{ 77, 85, 0, 0, 0, 0 }, { 78, 65, 0, 0, 0, 0 }, { 78, 65, 73, 0, 0, 0 },
{ 78, 65, 78, 0, 0, 0 }, { 78, 65, 78, 71, 0, 0 }, { 78, 65, 79, 0, 0, 0 },
{ 78, 69, 0, 0, 0, 0 }, { 78, 69, 73, 0, 0, 0 }, { 78, 69, 78, 0, 0, 0 },
{ 78, 69, 78, 71, 0, 0 }, { 78, 73, 0, 0, 0, 0 }, { 78, 73, 65, 78, 0, 0 },
{ 78, 73, 65, 78, 71, 0 }, { 78, 73, 65, 79, 0, 0 }, { 78, 73, 69, 0, 0, 0 },
{ 78, 73, 78, 0, 0, 0 }, { 78, 73, 78, 71, 0, 0 }, { 78, 73, 85, 0, 0, 0 },
{ 78, 79, 78, 71, 0, 0 }, { 78, 79, 85, 0, 0, 0 }, { 78, 85, 0, 0, 0, 0 },
{ 78, 85, 65, 78, 0, 0 }, { 78, 85, 69, 0, 0, 0 }, { 78, 85, 79, 0, 0, 0 },
{ 79, 0, 0, 0, 0, 0 }, { 79, 85, 0, 0, 0, 0 }, { 80, 65, 0, 0, 0, 0 },
{ 80, 65, 73, 0, 0, 0 }, { 80, 65, 78, 0, 0, 0 }, { 80, 65, 78, 71, 0, 0 },
{ 80, 65, 79, 0, 0, 0 }, { 80, 69, 73, 0, 0, 0 }, { 80, 69, 78, 0, 0, 0 },
{ 80, 69, 78, 71, 0, 0 }, { 80, 73, 0, 0, 0, 0 }, { 80, 73, 65, 78, 0, 0 },
{ 80, 73, 65, 79, 0, 0 }, { 80, 73, 69, 0, 0, 0 }, { 80, 73, 78, 0, 0, 0 },
{ 80, 73, 78, 71, 0, 0 }, { 80, 79, 0, 0, 0, 0 }, { 80, 79, 85, 0, 0, 0 },
{ 80, 85, 0, 0, 0, 0 }, { 81, 73, 0, 0, 0, 0 }, { 81, 73, 65, 0, 0, 0 },
{ 81, 73, 65, 78, 0, 0 }, { 81, 73, 65, 78, 71, 0 }, { 81, 73, 65, 79, 0, 0 },
{ 81, 73, 69, 0, 0, 0 }, { 81, 73, 78, 0, 0, 0 }, { 81, 73, 78, 71, 0, 0 },
{ 81, 73, 79, 78, 71, 0 }, { 81, 73, 85, 0, 0, 0 }, { 81, 85, 0, 0, 0, 0 },
{ 81, 85, 65, 78, 0, 0 }, { 81, 85, 69, 0, 0, 0 }, { 81, 85, 78, 0, 0, 0 },
{ 82, 65, 78, 0, 0, 0 }, { 82, 65, 78, 71, 0, 0 }, { 82, 65, 79, 0, 0, 0 },
{ 82, 69, 0, 0, 0, 0 }, { 82, 69, 78, 0, 0, 0 }, { 82, 69, 78, 71, 0, 0 },
{ 82, 73, 0, 0, 0, 0 }, { 82, 79, 78, 71, 0, 0 }, { 82, 79, 85, 0, 0, 0 },
{ 82, 85, 0, 0, 0, 0 }, { 82, 85, 65, 78, 0, 0 }, { 82, 85, 73, 0, 0, 0 },
{ 82, 85, 78, 0, 0, 0 }, { 82, 85, 79, 0, 0, 0 }, { 83, 65, 0, 0, 0, 0 },
{ 83, 65, 73, 0, 0, 0 }, { 83, 65, 78, 0, 0, 0 }, { 83, 65, 78, 71, 0, 0 },
{ 83, 65, 79, 0, 0, 0 }, { 83, 69, 0, 0, 0, 0 }, { 83, 69, 78, 0, 0, 0 },
{ 83, 69, 78, 71, 0, 0 }, { 83, 72, 65, 0, 0, 0 }, { 83, 72, 65, 73, 0, 0 },
{ 83, 72, 65, 78, 0, 0 }, { 83, 72, 65, 78, 71, 0 }, { 83, 72, 65, 79, 0, 0 },
{ 83, 72, 69, 0, 0, 0 }, { 83, 72, 69, 78, 0, 0 }, { 83, 72, 69, 78, 71, 0 },
{ 83, 72, 73, 0, 0, 0 }, { 83, 72, 79, 85, 0, 0 }, { 83, 72, 85, 0, 0, 0 },
{ 83, 72, 85, 65, 0, 0 }, { 83, 72, 85, 65, 73, 0 }, { 83, 72, 85, 65, 78, 0 },
{ 83, 72, 85, 65, 78, 71 }, { 83, 72, 85, 73, 0, 0 }, { 83, 72, 85, 78, 0, 0 },
{ 83, 72, 85, 79, 0, 0 }, { 83, 73, 0, 0, 0, 0 }, { 83, 79, 78, 71, 0, 0 },
{ 83, 79, 85, 0, 0, 0 }, { 83, 85, 0, 0, 0, 0 }, { 83, 85, 65, 78, 0, 0 },
{ 83, 85, 73, 0, 0, 0 }, { 83, 85, 78, 0, 0, 0 }, { 83, 85, 79, 0, 0, 0 },
{ 84, 65, 0, 0, 0, 0 }, { 84, 65, 73, 0, 0, 0 }, { 84, 65, 78, 0, 0, 0 },
{ 84, 65, 78, 71, 0, 0 }, { 84, 65, 79, 0, 0, 0 }, { 84, 73, 65, 78, 0, 0 },
{ 84, 69, 78, 71, 0, 0 }, { 84, 73, 0, 0, 0, 0 }, { 84, 73, 65, 78, 0, 0 },
{ 84, 73, 65, 79, 0, 0 }, { 84, 73, 69, 0, 0, 0 }, { 84, 73, 78, 71, 0, 0 },
{ 84, 79, 78, 71, 0, 0 }, { 84, 79, 85, 0, 0, 0 }, { 84, 85, 0, 0, 0, 0 },
{ 84, 85, 65, 78, 0, 0 }, { 84, 85, 73, 0, 0, 0 }, { 84, 85, 78, 0, 0, 0 },
{ 84, 85, 79, 0, 0, 0 }, { 87, 65, 0, 0, 0, 0 }, { 87, 65, 73, 0, 0, 0 },
{ 87, 65, 78, 0, 0, 0 }, { 87, 65, 78, 71, 0, 0 }, { 87, 69, 73, 0, 0, 0 },
{ 87, 69, 78, 0, 0, 0 }, { 87, 69, 78, 71, 0, 0 }, { 87, 79, 0, 0, 0, 0 },
{ 87, 85, 0, 0, 0, 0 }, { 88, 73, 0, 0, 0, 0 }, { 88, 73, 65, 0, 0, 0 },
{ 88, 73, 65, 78, 0, 0 }, { 88, 73, 65, 78, 71, 0 }, { 88, 73, 65, 79, 0, 0 },
{ 88, 73, 69, 0, 0, 0 }, { 88, 73, 78, 0, 0, 0 }, { 88, 73, 78, 71, 0, 0 },
{ 88, 73, 79, 78, 71, 0 }, { 88, 73, 85, 0, 0, 0 }, { 88, 85, 0, 0, 0, 0 },
{ 88, 85, 65, 78, 0, 0 }, { 88, 85, 69, 0, 0, 0 }, { 88, 85, 78, 0, 0, 0 },
{ 89, 65, 0, 0, 0, 0 }, { 89, 65, 78, 0, 0, 0 }, { 89, 65, 78, 71, 0, 0 },
{ 89, 65, 79, 0, 0, 0 }, { 89, 69, 0, 0, 0, 0 }, { 89, 73, 0, 0, 0, 0 },
{ 89, 73, 78, 0, 0, 0 }, { 89, 73, 78, 71, 0, 0 }, { 89, 79, 0, 0, 0, 0 },
{ 89, 79, 78, 71, 0, 0 }, { 89, 79, 85, 0, 0, 0 }, { 89, 85, 0, 0, 0, 0 },
{ 89, 85, 65, 78, 0, 0 }, { 89, 85, 69, 0, 0, 0 }, { 89, 85, 78, 0, 0, 0 },
{ 90, 65, 0, 0, 0, 0 }, { 90, 65, 73, 0, 0, 0 }, { 90, 65, 78, 0, 0, 0 },
{ 90, 65, 78, 71, 0, 0 }, { 90, 65, 79, 0, 0, 0 }, { 90, 69, 0, 0, 0, 0 },
{ 90, 69, 73, 0, 0, 0 }, { 90, 69, 78, 0, 0, 0 }, { 90, 69, 78, 71, 0, 0 },
{ 90, 72, 65, 0, 0, 0 }, { 90, 72, 65, 73, 0, 0 }, { 90, 72, 65, 78, 0, 0 },
{ 90, 72, 65, 78, 71, 0 }, { 90, 72, 65, 79, 0, 0 }, { 90, 72, 69, 0, 0, 0 },
{ 90, 72, 69, 78, 0, 0 }, { 90, 72, 69, 78, 71, 0 }, { 90, 72, 73, 0, 0, 0 },
{ 90, 72, 79, 78, 71, 0 }, { 90, 72, 79, 85, 0, 0 }, { 90, 72, 85, 0, 0, 0 },
{ 90, 72, 85, 65, 0, 0 }, { 90, 72, 85, 65, 73, 0 }, { 90, 72, 85, 65, 78, 0 },
{ 90, 72, 85, 65, 78, 71 }, { 90, 72, 85, 73, 0, 0 }, { 90, 72, 85, 78, 0, 0 },
{ 90, 72, 85, 79, 0, 0 }, { 90, 73, 0, 0, 0, 0 }, { 90, 79, 78, 71, 0, 0 },
{ 90, 79, 85, 0, 0, 0 }, { 90, 85, 0, 0, 0, 0 }, { 90, 85, 65, 78, 0, 0 },
{ 90, 85, 73, 0, 0, 0 }, { 90, 85, 78, 0, 0, 0 }, { 90, 85, 79, 0, 0, 0 }, };
/** First and last Chinese character with known Pinyin according to zh collation */
private static final String FIRST_PINYIN_UNIHAN = "\u963F";
private static final String LAST_PINYIN_UNIHAN = "\u84D9";
/** The first Chinese character in Unicode block */
private static final char FIRST_UNIHAN = '\u3400';
private static final Collator COLLATOR = Collator.getInstance(Locale.CHINA);
private static HanziToPinyin sInstance;
private final boolean mHasChinaCollator;
public static class Token {
/**
* Separator between target string for each source char
*/
public static final String SEPARATOR = " ";
public static final int LATIN = 1;
public static final int PINYIN = 2;
public static final int UNKNOWN = 3;
public Token() {
}
public Token(int type, String source, String target) {
this.type = type;
this.source = source;
this.target = target;
}
/**
* Type of this token, ASCII, PINYIN or UNKNOWN.
*/
public int type;
/**
* Original string before translation.
*/
public String source;
/**
* Translated string of source. For Han, target is corresponding Pinyin. Otherwise target is
* original string in source.
*/
public String target;
}
protected HanziToPinyin(boolean hasChinaCollator) {
mHasChinaCollator = hasChinaCollator;
}
public static HanziToPinyin getInstance() {
synchronized (HanziToPinyin.class) {
if (sInstance != null) {
return sInstance;
}
// Check if zh_CN collation data is available
final Locale locale[] = Collator.getAvailableLocales();
for (int i = 0; i < locale.length; i++) {
if (locale[i].equals(Locale.CHINA)) {
// Do self validation just once.
if (DEBUG) {
Log.d(TAG, "Self validation. Result: " + doSelfValidation());
}
sInstance = new HanziToPinyin(true);
return sInstance;
}
}
Log.w(TAG, "There is no Chinese collator, HanziToPinyin is disabled");
sInstance = new HanziToPinyin(false);
return sInstance;
}
}
/**
* Validate if our internal table has some wrong value.
*
* @return true when the table looks correct.
*/
private static boolean doSelfValidation() {
char lastChar = UNIHANS[0];
String lastString = Character.toString(lastChar);
for (char c : UNIHANS) {
if (lastChar == c) {
continue;
}
final String curString = Character.toString(c);
int cmp = COLLATOR.compare(lastString, curString);
if (cmp >= 0) {
Log.e(TAG, "Internal error in Unihan table. " + "The last string \"" + lastString
+ "\" is greater than current string \"" + curString + "\".");
return false;
}
lastString = curString;
}
return true;
}
private Token getToken(char character) {
Token token = new Token();
final String letter = Character.toString(character);
token.source = letter;
int offset = -1;
int cmp;
if (character < 256) {
token.type = Token.LATIN;
token.target = letter;
return token;
} else if (character < FIRST_UNIHAN) {
token.type = Token.UNKNOWN;
token.target = letter;
return token;
} else {
cmp = COLLATOR.compare(letter, FIRST_PINYIN_UNIHAN);
if (cmp < 0) {
token.type = Token.UNKNOWN;
token.target = letter;
return token;
} else if (cmp == 0) {
token.type = Token.PINYIN;
offset = 0;
} else {
cmp = COLLATOR.compare(letter, LAST_PINYIN_UNIHAN);
if (cmp > 0) {
token.type = Token.UNKNOWN;
token.target = letter;
return token;
} else if (cmp == 0) {
token.type = Token.PINYIN;
offset = UNIHANS.length - 1;
}
}
}
token.type = Token.PINYIN;
if (offset < 0) {
int begin = 0;
int end = UNIHANS.length - 1;
while (begin <= end) {
offset = (begin + end) / 2;
final String unihan = Character.toString(UNIHANS[offset]);
cmp = COLLATOR.compare(letter, unihan);
if (cmp == 0) {
break;
} else if (cmp > 0) {
begin = offset + 1;
} else {
end = offset - 1;
}
}
}
if (cmp < 0) {
offset--;
}
StringBuilder pinyin = new StringBuilder();
for (int j = 0; j < PINYINS[offset].length && PINYINS[offset][j] != 0; j++) {
pinyin.append((char) PINYINS[offset][j]);
}
token.target = pinyin.toString();
return token;
}
/**
* Convert the input to a array of tokens. The sequence of ASCII or Unknown characters without
* space will be put into a Token, One Hanzi character which has pinyin will be treated as a
* Token. If these is no China collator, the empty token array is returned.
*/
public ArrayList<Token> get(final String input) {
ArrayList<Token> tokens = new ArrayList<Token>();
if (!mHasChinaCollator || TextUtils.isEmpty(input)) {
// return empty tokens.
return tokens;
}
final int inputLength = input.length();
final StringBuilder sb = new StringBuilder();
int tokenType = Token.LATIN;
// Go through the input, create a new token when
// a. Token type changed
// b. Get the Pinyin of current charater.
// c. current character is space.
for (int i = 0; i < inputLength; i++) {
final char character = input.charAt(i);
if (character == ' ') {
if (sb.length() > 0) {
addToken(sb, tokens, tokenType);
}
} else if (character < 256) {
if (tokenType != Token.LATIN && sb.length() > 0) {
addToken(sb, tokens, tokenType);
}
tokenType = Token.LATIN;
sb.append(character);
} else if (character < FIRST_UNIHAN) {
if (tokenType != Token.UNKNOWN && sb.length() > 0) {
addToken(sb, tokens, tokenType);
}
tokenType = Token.UNKNOWN;
sb.append(character);
} else {
Token t = getToken(character);
if (t.type == Token.PINYIN) {
if (sb.length() > 0) {
addToken(sb, tokens, tokenType);
}
tokens.add(t);
tokenType = Token.PINYIN;
} else {
if (tokenType != t.type && sb.length() > 0) {
addToken(sb, tokens, tokenType);
}
tokenType = t.type;
sb.append(character);
}
}
}
if (sb.length() > 0) {
addToken(sb, tokens, tokenType);
}
return tokens;
}
private void addToken(
final StringBuilder sb, final ArrayList<Token> tokens, final int tokenType) {
String str = sb.toString();
tokens.add(new Token(tokenType, str, str));
sb.setLength(0);
}
//The fillowing lines are provided and maintained by Mediatek inc.
private class DialerSearchToken extends Token {
static final int FIRSTCASE = 0;
static final int UPPERCASE = 1;
static final int LOWERCASE = 2;
}
public String getTokensForDialerSearch(final String input, StringBuilder offsets){
if(offsets == null || input == null || TextUtils.isEmpty(input)){
// return empty tokens
return null;
}
StringBuilder subStrSet = new StringBuilder();
ArrayList<Token> tokens = new ArrayList<Token>();
ArrayList<String> shortSubStrOffset = new ArrayList<String>();
final int inputLength = input.length();
final StringBuilder subString = new StringBuilder();
final StringBuilder subStrOffset = new StringBuilder();
int tokenType = Token.LATIN;
int caseTypePre = DialerSearchToken.FIRSTCASE;
int caseTypeCurr = DialerSearchToken.UPPERCASE;
int mPos = 0;
// Go through the input, create a new token when
// a. Token type changed
// b. Get the Pinyin of current charater.
// c. current character is space.
// d. Token case changed from lower case to upper case,
// e. the first character is always a separated one
// f character == '+' || character == '#' || character == '*' || character == ',' || character == ';'
for (int i = 0; i < inputLength; i++) {
final char character = input.charAt(i);
if (character == '-' || character == ',' ){
mPos++;
} else if (character == ' ') {
if (subString.length() > 0) {
addToken(subString, tokens, tokenType);
addOffsets(subStrOffset, shortSubStrOffset);
}
addSubString(tokens,shortSubStrOffset,subStrSet,offsets);
mPos++;
caseTypePre = DialerSearchToken.FIRSTCASE;
} else if (character < 256) {
if (tokenType != Token.LATIN && subString.length() > 0) {
addToken(subString, tokens, tokenType);
addOffsets(subStrOffset, shortSubStrOffset);
}
caseTypeCurr = (character>='A' && character<='Z')?DialerSearchToken.UPPERCASE:DialerSearchToken.LOWERCASE;
if(caseTypePre == DialerSearchToken.LOWERCASE && caseTypeCurr == DialerSearchToken.UPPERCASE){
addToken(subString, tokens, tokenType);
addOffsets(subStrOffset, shortSubStrOffset);
}
caseTypePre = caseTypeCurr;
tokenType = Token.LATIN;
Character c = Character.toUpperCase(character);
if(c != null){
subString.append(c);
subStrOffset.append((char)mPos);
}
mPos++;
} else if (character < FIRST_UNIHAN) {
//Comment out. Do not cover unknown characters SINCE they can not be input.
// if (tokenType != Token.UNKNOWN && subString.length() > 0) {
// addToken(subString, tokens, tokenType);
// addOffsets(subStrOffset, shortSubStrOffset);
// caseTypePre = Token.FIRSTCASE;
// }
// tokenType = Token.UNKNOWN;
// Character c = Character.toUpperCase(character);
// if(c != null){
// subString.append(c);
// subStrOffset.append((char)(mPos));
// }
mPos++;
} else {
Token t = getToken(character);
int tokenSize = t.target.length();
//Current type is PINYIN
if (t.type == Token.PINYIN) {
if (subString.length() > 0) {
addToken(subString, tokens, tokenType);
addOffsets(subStrOffset, shortSubStrOffset);
}
tokens.add(t);
for(int j=0; j < tokenSize;j++)
subStrOffset.append((char)mPos);
addOffsets(subStrOffset,shortSubStrOffset);
tokenType = Token.PINYIN;
caseTypePre = DialerSearchToken.FIRSTCASE;
mPos++;
} else {
//Comment out. Do not cover special characters SINCE they can not be input.
// if (tokenType != t.type && subString.length() > 0) {
// addToken(subString, tokens, tokenType);
// addOffsets(subStrOffset, shortSubStrOffset);
// caseTypePre = Token.FIRSTCASE;
// }else{
// caseTypeCurr = (character>='A' && character<='Z')?Token.UPPERCASE:Token.LOWERCASE;
// if(caseTypePre == Token.LOWERCASE && caseTypeCurr == Token.UPPERCASE){
// addToken(subString, tokens, tokenType);
// addOffsets(subStrOffset, shortSubStrOffset);
// }
// caseTypePre = caseTypeCurr;
// }
// tokenType = t.type;
// Character c = Character.toUpperCase(character);
// if(c != null){
// subString.append(c);
// subStrOffset.append(mPos);
// }
mPos++;
}
}
//IF the name string is too long, cut it off to meet the storage request of dialer search.
if(mPos > 127)
break;
}
if (subString.length() > 0) {
addToken(subString, tokens, tokenType);
addOffsets(subStrOffset, shortSubStrOffset);
}
addSubString(tokens,shortSubStrOffset,subStrSet,offsets);
return subStrSet.toString();
}
private void addOffsets(final StringBuilder sb, final ArrayList<String> shortSubStrOffset){
String str = sb.toString();
shortSubStrOffset.add(str);
sb.setLength(0);
}
private void addSubString(final ArrayList<Token> tokens, final ArrayList<String> shortSubStrOffset,
StringBuilder subStrSet, StringBuilder offsets){
if(tokens == null || tokens.isEmpty())
return;
int size = tokens.size();
int len = 0;
StringBuilder mShortSubStr = new StringBuilder();
StringBuilder mShortSubStrOffsets = new StringBuilder();
StringBuilder mShortSubStrSet = new StringBuilder();
StringBuilder mShortSubStrOffsetsSet = new StringBuilder();
for(int i=size-1; i>=0 ; i--){
String mTempStr = tokens.get(i).target;
len += mTempStr.length();
String mTempOffset = shortSubStrOffset.get(i);
if(mShortSubStr.length()>0){
mShortSubStr.deleteCharAt(0);
mShortSubStrOffsets.deleteCharAt(0);
}
mShortSubStr.insert(0, mTempStr);
mShortSubStr.insert(0,(char)len);
mShortSubStrOffsets.insert(0,mTempOffset);
mShortSubStrOffsets.insert(0,(char)len);
mShortSubStrSet.insert(0,mShortSubStr);
mShortSubStrOffsetsSet.insert(0, mShortSubStrOffsets);
}
subStrSet.append(mShortSubStrSet);
offsets.append(mShortSubStrOffsetsSet);
tokens.clear();
shortSubStrOffset.clear();
}
//The previous lines are provided and maintained by Mediatek inc.
}