package com.partynetwork.dataprovider.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import com.partynetwork.myview.mytoast.TipsToast;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
public class Util {
private static final String SETTING_NAME = "db_set";
private static final String BITMAP_PATH = "data/data/com.dongcemedia.flowingmessage/images/";
/**
* 计算字节大小函数(通过传入的以B为单位的数值,转换为B、KB、MB的形式) 传入的字节数(整数型)
* 返回计算后的大小值(字符串型,以B、KB、MD)
*
* @param size
* @return
*/
public static String CountSize(Long size) {
double baseMB = 1024 * 1024.00;
String strSize = "";
double f = size / baseMB;
strSize = String.format(Locale.CHINESE, "%.2f MB", f);
return strSize;
}
/**
*
* @param paramTime
* @return
*/
public static String getFormatedDateString(long paramTime) {
Date dt = new Date(paramTime);
String tmp = String.valueOf(dt.getYear());
StringBuffer date = new StringBuffer(tmp.substring(tmp.length() - 2,
tmp.length()));
if (dt.getMonth() < 9) {
date.append("0" + (dt.getMonth() + 1));
} else {
date.append((dt.getMonth() + 1));
}
if (dt.getDate() < 9) {
date.append("0" + (dt.getDate()));
} else {
date.append(dt.getDate());
}
return date.toString();
}
/**
*
* @param mct
* @return
*/
public static String[] getDbSql(Context mct) {
String[] ret = new String[3];
try {
ContextWrapper mContextwrapper = new ContextWrapper(mct);
SharedPreferences config = mContextwrapper.getSharedPreferences(
SETTING_NAME, android.content.Context.MODE_PRIVATE);
ret[0] = config.getString("sql0", "");
ret[1] = config.getString("sql1", "");
ret[2] = config.getString("sql2", "");
return ret;
} catch (Exception e) {
return null;
}
}
/**
*
* @param sql
* @param mct
* @return
*/
public static boolean setDbSql(String[] sql, Context mct) {
try {
ContextWrapper mContextwrapper = new ContextWrapper(mct);
SharedPreferences settings = mContextwrapper.getSharedPreferences(
SETTING_NAME, 0);
settings.edit().putString("sql0", sql[0]).commit();
settings.edit().putString("sql1", sql[1]).commit();
settings.edit().putString("sql2", sql[2]).commit();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 检测网络是否正常
*
* @param mct
* @return
*/
public static boolean isNetworkOk(Context mct) {
ConnectivityManager manager = (ConnectivityManager) mct
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
if (null == networkinfo) {
return false;
} else {
return networkinfo.isConnected();
}
}
/**
*
* @param update
* @return
*/
public static long getStringToTime(String update) {
if (null == update) {
return 0;
}
if (6 != update.length()) {
return 0;
}
int year = Integer.parseInt(1 + update.substring(0, 2));
int month = Integer.parseInt(update.substring(2, 4));
int day = Integer.parseInt(update.substring(4, 6));
Date dt = new Date(year, month - 1, day);
Log.i("util", "y=" + year + "m=" + month + "day=" + day);
return dt.getTime();
}
/**
*
* @param paramBmp
* @param paramName
* @throws IOException
*/
public static void saveBitmapToLocal(Bitmap paramBmp, String paramName)
throws IOException {
if (null == paramName || null == paramBmp) {
return;
}
String path = BITMAP_PATH;
String urlPath;
if (paramName.startsWith("/")) {
paramName = paramName.substring(1);
}
if (!paramName.contains(".png")) {
urlPath = path + paramName + ".png";
} else {
urlPath = path + paramName;
}
File f = new File(urlPath);
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
paramBmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param paramBmp
* @param paramName
* @throws IOException
*/
public static void saveBitmapToSDCard(Bitmap paramBmp, String paramName)
throws IOException {
if (null == paramName) {
return;
}
if (!paramName.startsWith(SDCardFileUtils.getSDCardPath())) {
return;
}
if (!paramName.endsWith(".png")) {
paramName = paramName + ".png";
}
File f = new File(paramName);
if (f.exists()) {
f.delete();
}
Log.i("save=", paramName);
f.createNewFile();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
paramBmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param data
* @return
*/
public static String save(byte[] data) {
String path = AppConst.TEMP_PATH + System.currentTimeMillis() + ".png";
try {
// 获取SDCard信息
String storage = Environment.getExternalStorageDirectory()
.toString();
StatFs fs = new StatFs(storage);
long available = fs.getAvailableBlocks() * fs.getBlockSize();
if (available < data.length) {
return null;
}
File file = new File(path);
if (!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return path;
}
/**
* 通过图片的路径 返回一个Bitmap对象
*
* @param path
* @return
*/
public static Bitmap getBitmapFromLocal(String path) {
if (null == path) {
return null;
}
if (path.startsWith("/")) {
path = path.substring(1);
}
final String head = BITMAP_PATH;
Log.i("getBitmapFromLocal", head + path);
return BitmapFactory.decodeFile(head + path);
}
/**
*
* @param is
* @return
*/
public static String ConvertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
// sb.append(line + "\n");
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
*
* @param paramString
* @return
*/
public static Bitmap ConvertStringToBmp(String paramString) {
byte[] buffer = paramString.getBytes();
return BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
}
/**
* 读取的方法
*
* @param inStream
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
private static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // 用数据装
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outstream.write(buffer, 0, len);
}
outstream.close();
inStream.close();
// 关闭流一定要记得。
return outstream.toByteArray();
}
/**
*
* @param context
* @return
*/
public static int getApkVersionCode(Context context) {
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(),
0);
// String packageName = info.packageName;
int versionCode = info.versionCode;
// String versionName = info.versionName;
return versionCode;
} catch (NameNotFoundException e) {
}
return 0;
}
/**
*
* @param context
* @return
*/
public static String getApkName(Context context) {
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(),
0);
String packageName = info.packageName;
return packageName;
} catch (NameNotFoundException e) {
}
return null;
}
/**
*
* @param bytes
* @return
*/
public static java.lang.Object ByteToObject(byte[] bytes) {
java.lang.Object obj = null;
try {
// bytearray to object
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = oi.readObject();
bi.close();
oi.close();
} catch (Exception e) {
System.out.println("translation" + e.getMessage());
e.printStackTrace();
}
return obj;
}
/**
*
* @param obj
* @return
*/
public static byte[] ObjectToByte(java.lang.Object obj) {
byte[] bytes = null;
try {
// object to bytearray
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
System.out.println("translation" + e.getMessage());
e.printStackTrace();
}
return (bytes);
}
/**
*
* @param paramApp
* @return
*/
public static boolean isConnecting1(Application paramApp) {
ConnectivityManager mConnectivity = (ConnectivityManager) paramApp
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = mConnectivity.getActiveNetworkInfo();
if (info == null) {
return false;
}
return info.isConnected();
}
/**
*
* @return
*/
public static boolean isSdPrepareOk() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/**
*
* @return
*/
public static String getLanguage() {
String lan = Locale.getDefault().getLanguage();
if (null != lan) {
if ("zh".equals(lan)) {
return "zh_CN";
} else if ("es".equals(lan)) {
return "es_US";
} else if ("ja".equals(lan)) {
return "ja_JP";
}
}
return "en_US";
}
/**
* 获取系统当前时间
*
* @return
*/
public static String getNowTime() {
Date now = new Date();
String nowTime;
DateFormat time = DateFormat.getInstance();
nowTime = time.format(now);
return nowTime;
}
/**
*
* @param bitmap
* @param w
* @param h
* @return
*/
public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
// load the origial Bitmap
Bitmap BitmapOrg = bitmap;
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;
// calculate the scale
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return new BitmapDrawable(resizedBitmap).getBitmap();
}
/**
* 半角转全角
*
* @param input
* String.
* @return 全角字符串.
*/
public static String ToSBC(String input) {
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
c[i] = '\u3000'; // 采用十六进制,相当于十进制的12288
} else if (c[i] < '\177') { // 采用八进制,相当于十进制的127
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
/**
* 全角转半角
*
* @param input
* String.
* @return 半角字符串
*/
public static String ToDBC(String input) {
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
/**
*
* @param paramTmpAvat
* @return
*/
public static boolean delTempImage(String paramTmpAvat) {
if (null == paramTmpAvat) {
return false;
}
if (paramTmpAvat.startsWith("/")) {
paramTmpAvat = paramTmpAvat.substring(1);
}
final String head = BITMAP_PATH;
File tmp = new File(head + paramTmpAvat);
return tmp.delete();
}
/**
* 获取设备唯一ID
*
* @param context
* @return
*/
public static String getDeviceID(Context context) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getDeviceId() == null) {
return "";
}
return tm.getDeviceId();
}
/**
* 将 dip 转换成px 用于在代码中设置参数
*
* @param context
* @param dipValue
* @return
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* 将小于10(0~9)的整数转化为两位
*
* @param nValue
* @return
*/
public static String digit2two(int nValue) {
String strTemp = "";
if (nValue < 10 && nValue >= 0) {
strTemp = "0" + nValue;
} else {
strTemp += nValue;
}
return strTemp;
}
/**
* 打开 .apk文件
*
* @param file
*/
public static void openFile(File file, Context ctx) {
if (file.exists()) {
Log.e("OpenFile", file.getName());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
ctx.startActivity(intent);
}
}
/**
*
* @param paramContext
* @param paramFileName
* @return
*/
public static Bitmap getBitmapFromAssets(Context paramContext,
String paramFileName) {
InputStream is = null;
try {
is = paramContext.getAssets().open("images/" + paramFileName);
return BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
*
* @param is
* @return
* @throws IOException
*/
public static String inputStreamToStringUTF8(InputStream is)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString("utf8");
}
/**
* 根据jid获取用户名
*/
public static String getJidToUsername(String jid) {
return jid.split("@")[0];
}
/**
*
* @param username
* @return
*/
public static String getUserNameToJid(String username) {
return username + "@" + AppConst.SERVER_NAME;
}
/**
* 获取屏幕宽
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getWidth();
}
/**
* 获取屏幕高
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getHeight();
}
/**
*
* @param context
* @return
*/
public static float getScreenDensity(Context context) {
try {
DisplayMetrics dm = new DisplayMetrics();
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
manager.getDefaultDisplay().getMetrics(dm);
return dm.density;
} catch (Exception ex) {
}
return 1.0f;
}
/**
* 显示提示信息
*
* @param context
* @param msg
*/
public static void showMsg(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
/**
* 显示提示信息
*
* @param context
* @param msg
*/
public static void showMsg(Context context, int res) {
Toast.makeText(context, context.getResources().getString(res),
Toast.LENGTH_SHORT).show();
}
/**
* 保存配置信息
*
* @param context
* @param key
* @param value
*/
public static void saveString(Context context, String key, String value) {
SharedPreferences mSharedPreferences = context.getSharedPreferences(
AppConst.PREFERENCES_NAME, Context.MODE_PRIVATE);
mSharedPreferences.edit().putString(key, value).commit();
}
// 获取AppKey
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;
}
}