您的位置:首页 > 移动开发 > Android开发

Android 开发之常用工具utils

2017-02-24 00:00 309 查看

log类

import android.util.Log;

import com.zhou.learnnews.BuildConfig;

/**
* 包装后的Log输出,可控制显示哪些级别的LOG
* @author Administrator
*
*/
public class Logutil {
private static String className;            //所在的类名
private static String methodName;            //所在的方法名
private static int lineNumber;                //所在行号

public static final int VERBOSE = 1;          //显示Verbose及以上的Log
public static final int DEBUG = 2;            //显示Debug及以上的Log
public static final int INFO = 3;            //显示Info及以上的Log
public static final int WARN = 4;            //显示Warn及以上的Log
public static final int ERROR = 5;            //显示Error及以上的Log
public static final int NOTHING = 6;        //全部不显示

public static final int LEVEL = VERBOSE;    //控制显示的级别

private Logutil() {
}

public static boolean isDebuggable() {
return BuildConfig.DEBUG;
}

private static String createLog(String log) {

StringBuffer buffer = new StringBuffer();
buffer.append("[");
buffer.append(methodName);
buffer.append(":");
buffer.append(lineNumber);
buffer.append("]");
buffer.append(log);

return buffer.toString();
}

private static void getMethodNames(StackTraceElement[] sElements) {
className = sElements[1].getFileName();
methodName = sElements[1].getMethodName();
lineNumber = sElements[1].getLineNumber();
}

public static void v(String message) {
if (!isDebuggable()) {
return;
}

if (LEVEL <= VERBOSE) {
getMethodNames(new Throwable().getStackTrace());
Log.v(className, createLog(message));
}
}

public static void d(String message) {
if (!isDebuggable()) {
return;
}

if (LEVEL <= DEBUG) {
getMethodNames(new Throwable().getStackTrace());
Log.d(className, createLog(message));
}
}

public static void i(String message) {
if (!isDebuggable()) {
return;
}

if (LEVEL <= INFO) {
getMethodNames(new Throwable().getStackTrace());
Log.i(className, createLog(message));
}
}

public static void w(String message) {
if (!isDebuggable()) {
return;
}

if (LEVEL <= WARN) {
getMethodNames(new Throwable().getStackTrace());
Log.w(className, createLog(message));
}
}

public static void e(String message) {
if (!isDebuggable()) {
return;
}

if (LEVEL <= ERROR) {
getMethodNames(new Throwable().getStackTrace());
Log.e(className, createLog(message));
}
}
}

toast类

import android.R.string;
import android.content.Context;
import android.widget.Toast;

public class ToastUtil {

private static Toast toast;

public static void showLongToast (Context context ,String msg) {
if (toast == null) {
toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
}
else {
toast.setText(msg);
}
toast.show();
}
public static void showShortToast (Context context ,String msg) {
if (toast == null) {
toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
}
else {
toast.setText(msg);
}
toast.show();

}

}

###SharedPreferences封装类

package com.zhy.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;

public class SPUtils
{
/**
* 保存在手机里面的文件名
*/
public static final String FILE_NAME = "share_data";

/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
* @param context
* @param key
* @param object
*/
public static void put(Context context, String key, Object object)
{

SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();

if (object instanceof String)
{
editor.putString(key, (String) object);
} else if (object instanceof Integer)
{
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean)
{
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float)
{
editor.putFloat(key, (Float) object);
} else if (object instanceof Long)
{
editor.putLong(key, (Long) object);
} else
{
editor.putString(key, object.toString());
}

SharedPreferencesCompat.apply(editor);
}

/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object get(Context context, String key, Object defaultObject)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);

if (defaultObject instanceof String)
{
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer)
{
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean)
{
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float)
{
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long)
{
return sp.getLong(key, (Long) defaultObject);
}

return null;
}

/**
* 移除某个key值已经对应的值
* @param context
* @param key
*/
public static void remove(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}

/**
* 清除所有数据
* @param context
*/
public static void clear(Context context)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
}

/**
* 查询某个key是否已经存在
* @param context
* @param key
* @return
*/
public static boolean contains(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.contains(key);
}

/**
* 返回所有的键值对
*
* @param context
* @return
*/
public static Map<String, ?> getAll(Context context)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.getAll();
}

/**
* 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
*
* @author zhy
*
*/
private static class SharedPreferencesCompat
{
private static final Method sApplyMethod = findApplyMethod();

/**
* 反射查找apply的方法
*
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Method findApplyMethod()
{
try
{
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e)
{
}

return null;
}

/**
* 如果找到则使用apply执行,否则使用commit
*
* @param editor
*/
public static void apply(SharedPreferences.Editor editor)
{
try
{
if (sApplyMethod != null)
{
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e)
{
} catch (IllegalAccessException e)
{
} catch (InvocationTargetException e)
{
}
editor.commit();
}
}

}

单位转换类 DensityUtils

package com.zhy.utils;

import android.content.Context;
import android.util.TypedValue;

/**
* 常用单位转换的辅助类
*
*
*
*/
public class DensityUtils
{
private DensityUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}

/**
* dp转px
*
* @param context
* @param val
* @return
*/
public static int dp2px(Context context, float dpVal)
{
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}

/**
* sp转px
*
* @param context
* @param val
* @return
*/
public static int sp2px(Context context, float spVal)
{
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}

/**
* px转dp
*
* @param context
* @param pxVal
* @return
*/
public static float px2dp(Context context, float pxVal)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}

/**
* px转sp
*
* @param fontScale
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal)
{
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}

}

###App相关辅助类

package com.zhy.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

/**
* 跟App相关的辅助类
*
*
*
*/
public class AppUtils
{

private AppUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");

}

/**
* 获取应用程序名称
*/
public static String getAppName(Context context)
{
try
{
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (NameNotFoundException e)
{
e.printStackTrace();
}
return null;
}

/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static String getVersionName(Context context)
{
try
{
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionName;

} catch (NameNotFoundException e)
{
e.printStackTrace();
}
return null;
}

}

###网络相关辅助类1NetWorkUtils

package com.jaydenxiao.common.commonutils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* des:网络管理工具
* Created by xsf
* on 2016.04.10:34
*/
public class NetWorkUtils {

/**
* 检查网络是否可用
*
* @param paramContext
* @return
*/
public static boolean isNetConnected(Context paramContext) {
boolean i = false;
NetworkInfo localNetworkInfo = ((ConnectivityManager) paramContext
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable()))
return true;
return false;
}
/**
* 检测wifi是否连接
*/
public static boolean isWifiConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
}

/**
* 检测3G是否连接
*/
public static boolean is3gConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
return false;
}

/**
* 判断网址是否有效
*/
public static boolean isLinkAvailable(String link) {
Pattern pattern = Pattern.compile("^(http://|https://)?((?:[A-Za-z0-9]+-[A-Za-z0-9]+|[A-Za-z0-9]+)\\.)+([A-Za-z]+)[/\\?\\:]?.*$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(link);
if (matcher.matches()) {
return true;
}
return false;
}
}

###网络相关辅助类2 NetUtils

package com.zhy.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
* 跟网络相关的工具类
*
*
*
*/
public class NetUtils
{
private NetUtils()
{
/* cannot be instantiated */
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);
}

}

###软键盘相关辅助类KeyBoardUtils

package com.zhy.utils;

import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
* 打开或关闭软键盘
*
* @author zhy
*
*/
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: