Java tutorial
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.grass.caishi.cc.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.easemob.chat.EMMessage; import com.easemob.chat.TextMessageBody; import com.easemob.util.EMLog; import com.grass.caishi.cc.Constant; import com.grass.caishi.cc.R; import com.grass.caishi.cc.db.UserDao; import com.grass.caishi.cc.domain.User; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; public class CommonUtils { // private static MyLogger Log = MyLogger.yLog(); private static final long ONE_MINUTE = 60000L; private static final long ONE_HOUR = 3600000L; private static final long ONE_DAY = 86400000L; private static final long ONE_WEEK = 604800000L; private static final String ONE_SECOND_AGO = "?"; private static final String ONE_MINUTE_AGO = "?"; private static final String ONE_HOUR_AGO = "??"; private static final String ONE_DAY_AGO = "?"; private static final String ONE_MONTH_AGO = "?"; private static final String ONE_YEAR_AGO = "?"; public static String formatTime(long t) { if (String.valueOf(t).length() < 11) { t = Long.valueOf(t + "000"); } long delta = new Date().getTime() - t; if (delta < 1L * ONE_MINUTE) { long seconds = toSeconds(delta); return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO; } if (delta < 45L * ONE_MINUTE) { long minutes = toMinutes(delta); return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO; } if (delta < 24L * ONE_HOUR) { long hours = toHours(delta); return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO; } if (delta < 48L * ONE_HOUR) { return ""; } if (delta < 30L * ONE_DAY) { long days = toDays(delta); return (days <= 0 ? 1 : days) + ONE_DAY_AGO; } if (delta < 12L * 4L * ONE_WEEK) { long months = toMonths(delta); return (months <= 0 ? 1 : months) + ONE_MONTH_AGO; } else { long years = toYears(delta); return (years <= 0 ? 1 : years) + ONE_YEAR_AGO; } } private static long toSeconds(long date) { return date / 1000L; } private static long toMinutes(long date) { return toSeconds(date) / 60L; } private static long toHours(long date) { return toMinutes(date) / 60L; } private static long toDays(long date) { return toHours(date) / 24L; } private static long toMonths(long date) { return toDays(date) / 30L; } private static long toYears(long date) { return toMonths(date) / 365L; } public static String transName(String name) { name = name.substring(4); return name + "******"; } public static String transformDateTime(long t) { if (String.valueOf(t).length() < 11) { t = Long.valueOf(t + "000"); } Date date = new Date(t); SimpleDateFormat dateFormat = new SimpleDateFormat("Md Hm"); return dateFormat.format(date); } public static String transformDateTime(String t) { long time = System.currentTimeMillis(); if (t.length() < 11) { time = Long.valueOf(t + "000"); } Date date = new Date(time); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.format(date); } public static String transformDateTime(String t, String format) { long time = System.currentTimeMillis(); if (t.length() < 11) { time = Long.valueOf(t + "000"); } Date date = new Date(time); SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } public static String transformDate(long t) { if (String.valueOf(t).length() < 11) { t = Long.valueOf(t + "000"); } Date date = new Date(t); SimpleDateFormat dateFormat = new SimpleDateFormat("Md"); return dateFormat.format(date); } public static String transTime(long t) { if (String.valueOf(t).length() < 11) { t = Long.valueOf(t + "000"); } Date date = new Date(t); SimpleDateFormat dateFormat = new SimpleDateFormat("Md"); return dateFormat.format(date); } /** * ?html?<br> * ???????,?? * * @param content * * @return ? */ public static String stripHtml(String content) { // <p>??? content = content.replaceAll("<p .*?>", "/r/n"); // <br><br/>?? content = content.replaceAll("<br//s*/?>", "/r/n"); // <> content = content.replaceAll("//<.*?>", ""); // HTML // content = HTMLDecoder.decode(content); return content; } /** * ?? * * @param context * @return */ public static boolean isNetWorkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null) { return mNetworkInfo.isAvailable(); } } return false; } /** * Sdcard? * * @return */ public static boolean isExitsSdcard() { if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) return true; else return false; } public static String getTopActivity(Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1); if (runningTaskInfos != null) return runningTaskInfos.get(0).topActivity.getClassName(); else return ""; } /** * ??: null?0??Mapempty * * @param obj * @return */ public static boolean isNullOrEmpty(Object obj) { // Log.d( "obj--->"+obj); if (obj != null) { // Log.d("--->not null"); } else { return true; } if (obj.toString() != null) {// ??? // Log.d("--->not null"); } else { return true; } if (obj.toString().trim().equals("null") || obj.toString().trim().equals("NULL")) {// ??? return true; } /* * if (!isNullOrEmpty(obj.toString())){//???0904|?? Log.d("isNullOrEmpty", "=not null"); }else{ return true; } */ if (obj instanceof CharSequence) { // Log.d("--->CharSequence"); return ((CharSequence) obj).length() == 0; } if (obj instanceof Collection) { // Log.d("--->Collection"); return ((Collection) obj).isEmpty(); } if (obj instanceof Map) { // Log.d( "--->Map"); return ((Map) obj).isEmpty(); } if (obj instanceof Object[]) { // Log.d("--->Object[]"); Object[] object = (Object[]) obj; if (object.length == 0) { return true; } boolean empty = true; for (int i = 0; i < object.length; i++) { if (!isNullOrEmpty(object[i])) { empty = false; break; } } return empty; } if (obj instanceof JSONArray) { if (((JSONArray) obj).length() == 0) { return true; } } if (obj instanceof JSONObject) { if (((JSONObject) obj).length() == 0) { return true; } } return false; } /** * ??(?)? * * @param long1 * ? * @param lat1 * * @param long2 * ? * @param lat2 * * @return ? ?? */ public static double Distance(double long1, double lat1, double long2, double lat2) { double a, b, R; R = 6378137; // ?? lat1 = lat1 * Math.PI / 180.0; lat2 = lat2 * Math.PI / 180.0; a = lat1 - lat2; b = (long1 - long2) * Math.PI / 180.0; double d; double sa2, sb2; sa2 = Math.sin(a / 2.0); sb2 = Math.sin(b / 2.0); d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2)); return d; } /** * emoji ? * * @param source * @return */ public static String filterEmoji(String source) { if (!containsEmoji(source)) { return source;// ?? } // ?? StringBuilder buf = null; int len = source.length(); for (int i = 0; i < len; i++) { char codePoint = source.charAt(i); if (!isEmojiCharacter(codePoint)) { if (buf == null) { buf = new StringBuilder(source.length()); } buf.append(codePoint); } else { } } if (buf == null) { return ""; } else { if (buf.length() == len) {// ??toString?? buf = null; return source; } else { return buf.toString(); } } } private static boolean isEmojiCharacter(char codePoint) { return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))); } /** * ?emoji * * @param source * @return ? */ public static boolean containsEmoji(String source) { // if (StringUtils.isBlank(source)) { //?commons-lang-2.5.jar // return false; // } int len = source.length(); for (int i = 0; i < len; i++) { char codePoint = source.charAt(i); if (isEmojiCharacter(codePoint)) { // do nothing return true; } } return false; } public static String getResourceData(Context con, int ResourceID) { try { InputStreamReader inputReader = new InputStreamReader(con.getResources().openRawResource(ResourceID)); BufferedReader bufReader = new BufferedReader(inputReader); String line = ""; String Result = ""; while ((line = bufReader.readLine()) != null) Result += line; return Result; } catch (Exception e) { e.printStackTrace(); } return null; } static String getString(Context context, int resId) { return context.getResources().getString(resId); } /** * ??????? * * @param message * @param context * @return */ public static String getMessageDigest(EMMessage message, Context context) { String digest = ""; switch (message.getType()) { case LOCATION: // ?? if (message.direct == EMMessage.Direct.RECEIVE) { // sdk??ui???string // digest = EasyUtils.getAppResourceString(context, // "location_recv"); digest = getString(context, R.string.location_recv); String m = message.getStringAttribute("nick", ""); if (CommonUtils.isNullOrEmpty(m)) { UserDao dao = new UserDao(context); User user = dao.getUser(message.getFrom(), false); if (user != null) { m = user.getNick(); } } digest = String.format(digest, m); return digest; } else { // digest = EasyUtils.getAppResourceString(context, // "location_prefix"); digest = getString(context, R.string.location_prefix); } break; case IMAGE: // ? digest = getString(context, R.string.picture); break; case VOICE:// ? digest = getString(context, R.string.voice); break; case VIDEO: // ? digest = getString(context, R.string.video); break; case TXT: // ? if (!message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = txtBody.getMessage(); } else { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = getString(context, R.string.voice_call) + txtBody.getMessage(); } break; case FILE: // ? digest = getString(context, R.string.file); break; default: // EMLog.e(TAG, "error, unknow type"); return ""; } return digest; } /** * Map?String * * @param map * :??Map * @return String?? */ public static String MapToString(Map<?, ?> map) { JSONObject job = new JSONObject(map); return job.toString(); } public static Map<String, Object> StringtoMap(String object) { Map<String, Object> data = new HashMap<String, Object>(); // json??jsonObject JSONObject jsonObject; try { jsonObject = new JSONObject(object); Iterator it = jsonObject.keys(); // ??jsonObject?Map while (it.hasNext()) { String key = String.valueOf(it.next()); Object value = jsonObject.get(key); System.out.println(key + "-----" + value); data.put(key, value); } return data; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }