Acitity工具类
public class ActivityUtil {
/**
* 开启另外一个activity
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivity(Activity activity, Class<?> cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
/**
* 开启另外一个activity(默认动画)
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityDefault(Activity activity, Class<?> cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
}
/**
* 开启另外一个activity
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityBack(Activity activity, Class<?> cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
/**
* 开启另外一个activity
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode,
Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivityForResult(intent, requestCode);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
/**
* Fragment中开启另外一个activity
*
* @param fragment
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityForResult(Fragment fragment, Class<?> cls, int requestCode,
Bundle bundle, boolean isFinish) {
Intent intent = new Intent(fragment.getActivity(), cls);
if (bundle != null) {
intent.putExtras(bundle);
}
fragment.startActivityForResult(intent, requestCode);
if (isFinish) {
fragment.getActivity().finish();
}
fragment.getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
/**
* 开启另外一个activity
*
* @param activity
* @param intent
* @param bundle 传递的bundle对象
* @param requestCode
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityForResultIntent(Activity activity, Intent intent,
Bundle bundle, int requestCode, boolean isFinish) {
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivityForResult(intent, requestCode);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
public static void finishActivity(Activity activity){
// 退出Activity时动画
activity.finish();
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
/**
* 进入创建直播界面
* @param activity
* @param cls
* @param bundle
* @param isFinish
*/
public static void startCreateLiveActivity(Activity activity, Class cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
}
}
CircleImageView工具类
public class CircleImageView extends ImageView {
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 1;
private static final int DEFAULT_BORDER_WIDTH = 2;
private static final int DEFAULT_BORDER_COLOR = Color.WHITE;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private boolean mReady;
private boolean mSetupPending;
public CircleImageView(Context context) {
super(context);
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setScaleType(SCALE_TYPE);
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
@Override
public ScaleType getScaleType() {
return SCALE_TYPE;
}
@Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor(int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
return null;
}
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
}
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
用户头像等保存的文件类
public class FileUtil {
private static final String TAG = "FileUtil";
// 用户头像保存位置
private final static String HEADPHOTO_PATH = "/data/com.hipad.ssoAuth/";
// 剪切头像时临时保存头像名字,完成或取消时删除
public final static String HEADPHOTO_NAME_TEMP = "user_photo_temp.jpg";
//拍照临时存取图片
public final static String HEADPHOTO_NAME_RAW = "user_photo_raw.jpg";
// 剪切壁纸图片
private final static String WALLPAPER = "wallpaper.jpg";
public static String getCropPath(String path) {
String storageState = Environment.getExternalStorageState();
if (Environment.MEDIA_REMOVED.equals(storageState)) {
return null;
}
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + HEADPHOTO_PATH + "cache" + File.separator;
String s = MD5.Md5Encode(path)+".jpg";
return dirPath + s;
}
/**
* 用户头像保存路径
*/
public static String getHeadPhotoDir() {
String storageState = Environment.getExternalStorageState();
if (Environment.MEDIA_REMOVED.equals(storageState)) {
return null;
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + HEADPHOTO_PATH;
SDCardUtil.mkdirs(path);
return path;
}
/**
* 剪切头像时临时保存头像名字,完成或取消时删除
*/
public static File getHeadPhotoFileTemp() {
File file = new File(getHeadPhotoDir() + HEADPHOTO_NAME_TEMP);
return file;
}
/**
* 剪切头像时临时保存头像名字,完成或取消时删除(用于拍照时存储原始图片)
*/
public static File getHeadPhotoFileRaw() {
File file = new File(getHeadPhotoDir() + HEADPHOTO_NAME_RAW);
return file;
}
/**
* 获取剪切壁纸图片
*/
public static File getWallPaperFile() {
File file = new File(getHeadPhotoDir() + WALLPAPER);
return file;
}
public static void saveCutBitmapForCache(Context context, Bitmap bitmap) {
File file = new File(getHeadPhotoDir() + /*File.separator +*/ HEADPHOTO_NAME_RAW);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取图片属性:旋转的角度
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 旋转图片
* @param angle
* @param bitmap
* @return Bitmap
*/
public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
//旋转图片 动作
Matrix matrix = new Matrix();;
matrix.postRotate(angle);
System.out.println("angle2=" + angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* Delete the file/dir from the local disk
*
*/
public static boolean deleteFile(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
Log.w(TAG, "the file is not exist while delete the file");
return false;
}
return deleteDir(file);
}
/**
* Delete the file from the local disk
*
* @param dir
*/
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
if (children != null) {
// 递归删除目录中的子目录下
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
}
if (!dir.canRead() || !dir.canWrite()) {
Log.w(TAG, "has no permission to can or write while delete the file");
return false;
}
// 目录此时为空,可以删除
return dir.delete();
}
/**
* 删除临时文件(拍照的原始图片以及临时文件)
* @param path
*/
public static void deleteTempAndRaw() {
deleteFile(FileUtil.getHeadPhotoDir() + FileUtil.HEADPHOTO_NAME_TEMP);
deleteFile(FileUtil.getHeadPhotoDir() + FileUtil.HEADPHOTO_NAME_RAW);
}
}
测量Listview的高度
public class ListViewHeight {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
SDCardUtil缓存
public class SDCardUtil {
private static final String APP_DIR_NAME = "durian";
public static String getImageCachePath() {
String path = getCacheDir() + "image/";
mkdirs(path);
return path;
}
public static String getThmbnailsCachePath() {
return getCacheDir() + "thumbnails/";
}
/**
* SdCard cache鐩綍
*
* @return
*/
public static String getCacheDir() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/com.storm.durian/cache/";
mkdirs(path);
return path;
}
/**
* 获取缓存目录路径
*
* @return
*/
public static File getCahcePath() {
return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED) ? AppApplication.geContext()
.getExternalCacheDir() : AppApplication.geContext() .getCacheDir();
}
public synchronized static void mkdirs(String dir){
File filedir = new File(dir);
if (filedir != null && !filedir.exists()) {
filedir.mkdirs();
}
}
/*
/**
* SdCard cache鐩綍, 澶勭悊Coolpad 鎵嬫満鐨?udisk鎯呭喌,
*
* @param context
* @return
*/
/*public static String getSDCardDir(Context context) {
String path = null;
boolean bExists = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (bExists) {
path = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
ArrayList<String> pathList = FileOperationUtils.getSdPaths(context);
for (String pathStr : pathList) {
if (new File(pathStr).exists() && new File(pathStr).canWrite()) {
path = pathStr;
break;
}
}
}
return path + "/Android/data/com.storm.smart/cache/";
}*/
public static boolean isExsit() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* @param type The type of storage directory to return. Should be one of
* {@link #DIRECTORY_MUSIC}, {@link #DIRECTORY_PODCASTS},
* {@link #DIRECTORY_RINGTONES}, {@link #DIRECTORY_ALARMS},
* {@link #DIRECTORY_NOTIFICATIONS}, {@link #DIRECTORY_PICTURES},
* {@link #DIRECTORY_MOVIES}, {@link #DIRECTORY_DOWNLOADS}, or
* {@link #DIRECTORY_DCIM}. May not be null.
*/
public static String getExternalStoragePublicDirectory(String type) {
String path;
if (!isExsit()) {
return "";
}
return Environment.getExternalStoragePublicDirectory(type).getPath();
}
/**
* 鑾峰彇鐢熸垚鐨勭缉鐣ュ浘璺緞
*
* @param path
* @return
*/
public static String getDCIMThumbPath(String path) {
return getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/.thumbnails/" + MD5.Md5Encode(path) + ".png";
}
public static String getExternalStoragePath() {
if (isExsit()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return "/";
}
public static String getMntPath() {
String mntPath = getExternalStoragePath();
if (!"/".equals(mntPath) && mntPath.lastIndexOf("/") != -1
&& !mntPath.endsWith("/storage/emulated/0")) {
mntPath = mntPath.substring(0, mntPath.lastIndexOf("/") + 1);
}
return mntPath;
}
public static String getMntPath2() {
String mntPath = getExternalStoragePath();
if (!"/".equals(mntPath) && mntPath.lastIndexOf("/") != -1
&& !mntPath.endsWith("/storage/emulated/0")) {
mntPath = mntPath.substring(0, mntPath.lastIndexOf("/"));
}
return mntPath;
}
/**
* 鎴睆缂撳瓨
*
* @return
*/
public static String getScreenShotExternalStorageCacheDir() {
String path = "";
if (!TextUtils.isEmpty(getCacheDir())) {
path = getCacheDir() + "screen_shoot/";
}
return path;
}
/**
* 浠庣綉缁滀笅杞藉箍鍛婂浘鐗囷紝瀛樺湪imgFile涓?
*
* @param url
* @param imgFile
* @return
*/
public static boolean createAdImageinCacheFromUrl(String url, File imgFile) {
FileOutputStream outputStream = null;
HttpEntity entity = null;
InputStream in = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse response = StormHttpClient.getInstance().execute(get);
if (response == null) {
return false;
}
int statusCode = response.getStatusLine().getStatusCode();
entity = response.getEntity();
if (statusCode != HttpStatus.SC_OK || entity == null) {
return false;
}
in = entity.getContent();
if (in != null) {
imgFile.createNewFile();
outputStream = new FileOutputStream(imgFile);
} else {
return false;
}
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
outputStream.flush();
}
return true;
} catch (Exception e) {
// Log.e("", "when create new ad image error happen" + e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (entity != null) {
entity.consumeContent();
}
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return false;
}
/**
* 鍒犻櫎杩囨湡鐨勫箍鍛婂浘鐗?
*
* @param dirPath 鍒犻櫎鏂囦欢鎵?湪鐨勭洰褰?
* @param filelimits 璇ョ洰褰曚腑鏂囦欢涓婇檺
*/
public static void deleteExpiredImage(String dirPath, int filelimits) {
if (filelimits <= 0 || dirPath == null)
return;
File adDir = new File(dirPath);
if (!adDir.exists())
return;
if (!adDir.isDirectory())
return;
File list[] = adDir.listFiles();
if (list == null || list.length <= filelimits)
return;
Arrays.sort(list, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = f1.lastModified() - f2.lastModified();
if (diff > 0)
return 1;
else if (diff == 0)
return 0;
else
return -1;
}
public boolean equals(Object obj) {
return true;
}
});
for (int k = 0; k < list.length - filelimits; k++)
list[k].delete();
return;
}
/**
* 鑾峰彇path璺緞鐨勬?绌洪棿澶у皬
*
* @param path
* @return
*/
public static long getTotalCapacityInPath(String path) {
long capacity = 0;
try {
StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize();
long blockCount = stat.getBlockCount();
capacity = blockSize * blockCount;
} catch (Exception e) {
e.printStackTrace();
}
return capacity;
}
public static double[] getSDCardCapacityInfo(String path) {
double[] capacitys = new double[]{
0.0, 0.0, 0.0
};
String state = Environment.getExternalStorageState();
try {
if (Environment.MEDIA_MOUNTED.equals(state)) {
StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getBlockCount();
long availaBlock = stat.getAvailableBlocks();
double totalCapacity = availableBlocks * blockSize;
double vailaleCapacity = availaBlock * blockSize;
capacitys[0] = totalCapacity;
capacitys[1] = vailaleCapacity;
capacitys[2] = totalCapacity - vailaleCapacity;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return capacitys;
}
public static double getSdcardAvailableSpace() {
String state = Environment.getExternalStorageState();
try {
if (Environment.MEDIA_MOUNTED.equals(state)) {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getBlockCount();
long availaBlock = stat.getAvailableBlocks();
double vailaleCapacity = availaBlock * blockSize;
return vailaleCapacity;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return 0;
}
}