Android Utils
public class UserUtils {
/**
* 地图中绘制多边形、圆形的边界颜色
*
* @since 3.3.0
*/
public static final int STROKE_COLOR = Color.argb(180, 63, 145, 252);
/**
* 地图中绘制多边形、圆形的填充颜色
*
* @since 3.3.0
*/
public static final int FILL_COLOR = Color.argb(163, 118, 212, 243);
/**
* 地图中绘制多边形、圆形的边框宽度
*
* @since 3.3.0
*/
public static final float STROKE_WIDTH = 5F;
public final static int AVATAR = 1, UPLOAD = 2;
public static int currentMode = 2;
private static long lastClickTime=0;
private static int spaceTime = 800;
/**
* 防止按钮连续点击
* 每次点击button的时候,获取当前的时间,然后对比上一次的时间,两者的差值如果小于某个规定的时间,则判断为快速点击。
*/
public synchronized static boolean isFastClick() {
long currentTime = System.currentTimeMillis();
boolean isAllowClick;
if (currentTime - lastClickTime < spaceTime) {
isAllowClick = true;
} else {
isAllowClick = false;
}
lastClickTime = currentTime;
return isAllowClick;
}
public static int getCurrentMode() {
return currentMode;
}
public static boolean isLogin() {
if (TextUtils.isEmpty(LocalUserDataModel.accesstoken) || TextUtils.isEmpty(LocalUserDataModel.userName)) {
return false;
} else {
return true;
}
}
public static void uploadImage(int iType, final String imgPath) {
currentMode = 2;
String str = "";
switch (iType) {
case AVATAR:
str = UrlConstants.HOST + "/upload/portraitImage";
break;
case UPLOAD:
str = UrlConstants.HOST + "/file/upload";
break;
}
final String fileName = imgPath.substring(imgPath.lastIndexOf("/") + 1);
final String finalStr = str;
new Thread() {
public void run() {
try {
URL url = new URL(finalStr);
String boundary = "******";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("image", fileName);
connection.setRequestProperty("username", LocalUserDataModel.userName);
connection.setRequestProperty("plateform", "2");
connection.setRequestProperty("accesstoken", LocalUserDataModel.accesstoken);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
File file = new File(imgPath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int numReadByte;
while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
out.write(bytes, 0, numReadByte);
}
out.flush();
fileInputStream.close();
InputStream in = connection.getInputStream();
int res = connection.getResponseCode();
StringBuilder sb2 = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
String Line;
while ((Line = br.readLine()) != null) {
sb2.append(Line);
}
out.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public static void saveBitmapToFile(Bitmap bitmap, String path) {
BufferedOutputStream os = null;
try {
File file = new File(path);
int end = path.lastIndexOf(File.separator);
String _filePath = path.substring(0, end);
File filePath = new File(_filePath);
if (!filePath.exists()) {
filePath.mkdirs();
}
file.createNewFile();
os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
public static String htmlPrepare(String content) {
String header = "<html>\n" +
"<style type=\"text/css\">\n" +
"body {\n" +
" font-size: 16px;\n" +
" line-height: 150%;\n" +
"}\n" +
"</style>\n" +
"<body>\n";
String tail = "</body>\n" +
"</hmtl>\n";
String htmlContent = header + content + tail;
return htmlContent;
}
public static PackageInfo getAppVersion(Context context) {
PackageInfo pinfo = null;
try {
pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Integer versionCode = pinfo.versionCode;
String versionName = pinfo.versionName;
return pinfo;
}
public static void checkUpdate(Context context, boolean showNoUpdateUI) {
}
public static void showAlertDialog(@Nullable String title, @Nullable String message,
@Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
@NonNull String positiveText,
@Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
@NonNull String negativeText, @NonNull Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
builder.show();
}
public static long timeToUnix(String time, String format) {
long unixTime;
SimpleDateFormat sf = new SimpleDateFormat(format);
Date date = new Date();
try {
date = sf.parse(time);
unixTime = date.getTime();
return unixTime;
} catch (ParseException e) {
e.printStackTrace();
}
return -1;
}
public static String unixToTime(long UnixTimestamp, String format) {
String date = new java.text.SimpleDateFormat(format).format(new java.util.Date(UnixTimestamp * 1000));
return date;
}
public static long getCurrentUnixTime() {
long UnixTimestamp = System.currentTimeMillis() / 1000L;
return UnixTimestamp;
}
/**
* 获取阶段性日期
*
* @param dateline
* @return
*/
public static String getPeriodDate(long dateline) {
long minute = 60;
long hour = 60 * minute;
long day = 24 * hour;
long month = 31 * day;
long year = 12 * month;
if (dateline == 0) {
return null;
}
long diff = Long.valueOf(String.valueOf(new Date().getTime()).substring(0, 10)) - dateline;
if (diff >= 2 * day) {
return unixToTime(dateline, "MM-dd HH:mm");
}
if (diff >= day && diff < 2 * day) {
return "昨天" + unixToTime(dateline, " HH:mm");
}
return "今天" + unixToTime(dateline, " HH:mm");
}
public static float getScreenDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}
public static int dip2px(Context context, float px) {
final float scale = getScreenDensity(context);
return (int) (px * scale + 0.5);
}
public static String base64Decode(String content) {
if (TextUtils.isEmpty(content)) return "";
final byte data[] = Base64.decode(content, Base64.DEFAULT);
String text = null;
try {
text = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return text;
}
public static String base64encode(String content) {
byte[] bytes = content.getBytes();
byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
String encodeString = "";
try {
encodeString = new String(encode, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodeString;
}
public static String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
/**************************************************************************************************/
/**
* 阿里云图片上传
*/
public static void getAliYunPath(final Context context, final String path, final BeinCallBackListener beinCallBackListener) {
OSS oss;
OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIarzd41OS5sPA", "cpcPY6FDsfJ5Bq9RpzgWXlIKM3qIAq");
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000);
conf.setSocketTimeout(15 * 1000);
conf.setMaxConcurrentRequest(8);
conf.setMaxErrorRetry(2);
oss = new OSSClient(context, "oss-cn-shanghai.aliyuncs.com", credentialProvider, conf);
String newpath = "android/" + LocalUserDataModel.userName + "/";
Calendar c = Calendar.getInstance();
String month = unixToTime(getCurrentUnixTime(), "yyyyMM");
newpath = newpath + month + "/"
+ String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/"
+ c.getTimeInMillis() + "_" + UserUtils.randomInt()
+ path.substring(path.indexOf("."), path.length());
PutObjectRequest put = new PutObjectRequest("isbein", newpath, path);
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
}
});
final String finalNewpath = newpath;
final OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("PutObject", "UploadSuccess");
beinCallBackListener.onSuccess("http://oss.isbein.com/" + finalNewpath);
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
if (clientExcepion != null) {
clientExcepion.printStackTrace();
}
if (serviceException != null) {
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
beinCallBackListener.onSuccess("");
}
});
}
/**
* 随机生成8位数字字符串
*
* @return
*/
public static String randomInt() {
String randomNum = String.valueOf(Math.random());
randomNum = randomNum.replace(".", "");
randomNum = randomNum.substring(0, 8);
return randomNum;
}
/**
* 分享
*
* @param activity
* @param url
* @param title
* @param recommendReason
* @param imageUrl
* @param shareListener
*/
public static void travelOutShare(final Activity activity, final String url, final String title, final String recommendReason, final String imageUrl, final UMShareListener shareListener) {
final SnsPlatform weixin = SHARE_MEDIA.WEIXIN.toSnsPlatform();
final SnsPlatform weiCircle = SHARE_MEDIA.WEIXIN_CIRCLE.toSnsPlatform();
final SnsPlatform sina = SHARE_MEDIA.SINA.toSnsPlatform();
final SnsPlatform qq = SHARE_MEDIA.QQ.toSnsPlatform();
final SnsPlatform more = SHARE_MEDIA.MORE.toSnsPlatform();
new ShareAction(activity).withText("hello")
.addButton("app_name", "app_name", "bein_icon", "bein_icon")
.addButton(weixin.mShowWord, weixin.mKeyword, weixin.mIcon, weixin.mGrayIcon)
.addButton(weiCircle.mShowWord, weiCircle.mKeyword, weiCircle.mIcon, weiCircle.mGrayIcon)
.addButton(sina.mShowWord, sina.mKeyword, sina.mIcon, sina.mGrayIcon)
.addButton(qq.mShowWord, qq.mKeyword, qq.mIcon, qq.mGrayIcon)
.addButton(more.mShowWord, more.mKeyword, more.mIcon, more.mGrayIcon)
.addButton("umeng_sharebutton_copyurl", "umeng_sharebutton_copyurl", "umeng_socialize_copyurl", "umeng_socialize_copyurl")
.setShareboardclickCallback(new ShareBoardlistener() {
@Override
public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
Toast.makeText(activity, "复制文本按钮", Toast.LENGTH_LONG).show();
} else if (snsPlatform.mShowWord.equals("app_name")) {
} else {
if (snsPlatform.mShowWord.equals(weixin.mShowWord)) {
share_media = SHARE_MEDIA.WEIXIN;
} else if (snsPlatform.mShowWord.equals(weiCircle.mShowWord)) {
share_media = SHARE_MEDIA.WEIXIN_CIRCLE;
} else if (snsPlatform.mShowWord.equals(sina.mShowWord)) {
share_media = SHARE_MEDIA.SINA;
} else if (snsPlatform.mShowWord.equals(qq.mShowWord)) {
share_media = SHARE_MEDIA.QQ;
} else if (snsPlatform.mShowWord.equals(more.mShowWord)) {
share_media = SHARE_MEDIA.MORE;
}
final SHARE_MEDIA finalShare_media = share_media;
if (!url.equals("")) {
UMWeb web = new UMWeb(url);
web.setTitle(title);
web.setDescription(recommendReason);
web.setThumb(new UMImage(activity, imageUrl));
new ShareAction(activity).withMedia(web)
.setPlatform(finalShare_media)
.setCallback(shareListener)
.share();
} else {
}
}
}
})
.setCallback(shareListener)
.open();
}
public static int[] calcPopupXY(View rootView, View anchor) {
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
rootView.measure(w, h);
int popupWidth = rootView.getMeasuredWidth();
int popupHeight = rootView.getMeasuredHeight();
Rect anchorRect = getViewAbsoluteLocation(anchor);
int x = anchorRect.left + (anchorRect.right - anchorRect.left) / 2 - popupWidth / 2;
int y = anchorRect.top - popupHeight;
return new int[]{x, y};
}
public static Rect getViewAbsoluteLocation(View view) {
if (view == null) {
return new Rect();
}
int[] location = new int[2];
view.getLocationOnScreen(location);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
Rect rect = new Rect();
rect.left = location[0];
rect.top = location[1];
rect.right = rect.left + width;
rect.bottom = rect.top + height;
return rect;
}
/**
* 语音转换
*
* @param json
* @return
*/
public static String parseIatResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(0);
ret.append(obj.getString("w"));
}
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
/**
* 联系客服
*/
public static void goCustomerService(final Context context) {
LayoutInflater mInflater = LayoutInflater.from(context);
ViewGroup rootView = (ViewGroup) mInflater.inflate(R.layout.dialog_customer_service, null);
rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
final Dialog dialog = new Dialog(context);
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(rootView);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
TextView makeCall = (TextView) rootView.findViewById(R.id.make_call);
TextView dismissCall = (TextView) rootView.findViewById(R.id.dismiss_call);
makeCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "400 1234 567"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
dismissCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
/**
* 图片压缩
*
* @param imagePath
* @return
*/
public static String goCompressBitmap(String imagePath) {
String result = null;
ByteArrayOutputStream baos = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
int height = options.outHeight;
int width = options.outWidth;
float standardW = 480f;
float standardH = 800f;
int inSampleSize = 1;
int minLen = Math.min(height, width);
if (minLen > 200) {
float ratio = (float) minLen / 100.0f;
inSampleSize = (int) ratio;
}
if (width > height && width > standardW) {
inSampleSize = (int) (width / standardW);
} else if (width < height && height > standardH) {
inSampleSize = (int) (height / standardH);
}
if (inSampleSize <= 0)
inSampleSize = 1;
options.inJustDecodeBounds = false;
options.inSampleSize = inSampleSize;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 获取屏幕实际大小
*
* @param context
* @return
*/
public static Point getRealScreenSize(Context context) {
Point size = new Point();
try {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
windowManager.getDefaultDisplay().getRealSize(size);
} else {
try {
Method mGetRawW = Display.class.getMethod("getRawWidth");
Method mGetRawH = Display.class.getMethod("getRawHeight");
size.set((Integer) mGetRawW.invoke(windowManager.getDefaultDisplay()), (Integer) mGetRawH.invoke(windowManager.getDefaultDisplay()));
} catch (Exception e) {
size.set(windowManager.getDefaultDisplay().getWidth(), windowManager.getDefaultDisplay().getHeight());
}
}
} catch (Exception e) {
}
return size;
}
/**
* 获取 url里key为name的值
*
* @param url
* @param name
* @return
*/
public static String queryParam(String url, String name) {
Pattern pattern = Pattern.compile("(^|[?&])" + name + "=([^&]*)(&|$)");
Matcher matcher = pattern.matcher(url);
StringBuffer buffer = new StringBuffer();
String con = "";
while (matcher.find()) {
con = matcher.group();
buffer.append(con + " ");
}
String ret = buffer.toString().trim();
if (ret.contains("&") && ret.lastIndexOf("&") == ret.length() - 1) {
ret = ret.substring(ret.indexOf("=") + 1, ret.length() - 1);
} else {
if (TextUtils.isEmpty(ret)) {
return "";
} else {
ret = ret.substring(ret.indexOf("=") + 1, ret.length());
}
}
return ret;
}
}