编写不易,如有转载,请声明出处:http://blog.csdn.net/zxc514257857/article/details/68962539
1,可以控制Log开关的工具类LogUtil
import android.util.Log;
/**
* 控制Log开关的工具类
*/
public final class LogUtils {
private LogUtils() {}
// 如果想屏蔽所有log,可以设置为0
public static final int LOG_LEVEL = 6;
public static final int VERBOSE = 5;
public static final int DEBUG = 4;
public static final int INFO = 3;
public static final int WARN = 2;
public static final int ERROR = 1;
public static void v(String tag, String msg) {
if (LOG_LEVEL > VERBOSE) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (LOG_LEVEL > DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (LOG_LEVEL > INFO) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (LOG_LEVEL > WARN) {
Log.i(tag, msg);
}
}
public static void e(String tag, String msg) {
if (LOG_LEVEL > ERROR) {
Log.e(tag, msg);
}
}
public static void v(String msg) {
if (LOG_LEVEL > VERBOSE) {
Log.v(getCallerName(), msg);
}
}
public static void d(String msg) {
if (LOG_LEVEL > DEBUG) {
Log.d(getCallerName(), msg);
}
}
public static void i(String msg) {
if (LOG_LEVEL > INFO) {
Log.i(getCallerName(), msg);
}
}
public static void w(String msg) {
if (LOG_LEVEL > WARN) {
Log.w(getCallerName(), msg);
}
}
public static void e(String msg) {
if (LOG_LEVEL > ERROR) {
Log.e(getCallerName(), msg);
}
}
/**
* 获取调用者的类名
*/
public static String getCallerName() {
StackTraceElement caller = Thread.currentThread().getStackTrace()[4];
String className = caller.getClassName();// 带有包名信息
className = className.substring(className.lastIndexOf(".") + 1);
return className;
}
/**
* 描述:日志内容多的时候(超过4k)需要打印全时
*/
public static void showLog(String str) {
str = str.trim();
int index = 0;
int maxLength = 4000;
String finalString;
while (index < str.length()) {
if (str.length() <= index + maxLength) {
finalString = str.substring(index);
} else {
finalString = str.substring(index, maxLength);
}
index += maxLength;
i(getCallerName(), finalString.trim());
}
}
}
2,自定义Toast背景颜色及字体颜色,防止Toast多次创建的ToastUtil
Demo效果展示如下:
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.test.toastutil.R;
/**
* 自定义Toast背景颜色及字体颜色,防止多次创建
*/
public class ToastUtil {
private static Toast mToast;
private static Handler mHandler = new Handler();
private static Runnable runnable = new Runnable() {
public void run() {
mToast.cancel();
//toast隐藏后,将其置为null
mToast=null;
}
};
public static void showToast(Context context, String message) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//自定义布局
View view = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) view.findViewById(R.id.toast_message);
//显示的提示文字
text.setText(message);
mHandler.removeCallbacks(runnable);
//只有mToast==null时才重新创建,否则只需更改提示文字
if (mToast == null){
mToast = new Toast(context);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.setView(view);
}
mToast.show();
}
}
-----------------------------------------------------------
//布局代码
//(layout)activity_main
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.toastutil.activity.MainActivity">
<Button
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击显示toast"
android:onClick="click"/>
</RelativeLayout>
-----------------------------------------------------------
//(layout)custom_toast
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:background="@drawable/toast_bg"
android:padding="10dp" >
<TextView
android:id="@+id/toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="2"
android:textColor="#fff"
android:textSize="14sp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text=""/>
</RelativeLayout>
-----------------------------------------------------------
//(drawable)toast_bg
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充的颜色 -->
<solid android:color="#2BA6E1" />
<!-- 弧形的半径 -->
<corners android:radius="20dp" />
<!-- 边框的颜色及粗细 -->
<stroke android:color="#000"
android:width="4dp"/>
</shape>
-----------------------------------------------------------
//activity代码
//(activity)MainActivity
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.test.toastutil.R;
import com.test.toastutil.util.ToastUtil;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view){
ToastUtil.showToast(MainActivity.this , "Toast一下");
}
}
Demo下载请移步:http://download.csdn.net/detail/zxc514257857/9832927
3,对OkHttp封装的OkHttpUtil
使用说明参照:Android 一个改善的okHttp封装库 http://blog.csdn.net/lmj623565791/article/details/49734867/
4,dp和px的转换,sp和px的转换的工具类DensityUtil
import android.content.Context;
import android.util.TypedValue;
/**
* 常用单位转换的辅助类
*/
public class DensityUtil {
private DensityUtil() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*/
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp转px
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转dp
*/
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
5,存放和获取SharePreference数据的工具类PrefUtil
import android.content.Context;
import android.content.SharedPreferences;
/**
* 专门存放和获取SharePreference数据的工具类, 保存和配置一些设置信息
*/
public class PrefUtil {
// 存放在/data/data/<package name>/shared_prefs目录下的xml文件名为config.xml
private static final String SHARE_PREFS_NAME = "config";
/**
* 描述:存放布尔类型的数据到sp中
*/
public static void putBoolean(Context ctx, String key, boolean value) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().putBoolean(key, value).commit();
}
/**
* 描述:取出sp中布尔类型的数据
*/
public static boolean getBoolean(Context ctx, String key,
boolean defaultValue) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
return pref.getBoolean(key, defaultValue);
}
/**
* 描述:存放string类型的数据到sp中
*/
public static void putString(Context ctx, String key, String value) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().putString(key, value).commit();
}
/**
* 描述:取出sp中string类型的数据
*/
public static String getString(Context ctx, String key, String defaultValue) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
return pref.getString(key, defaultValue);
}
/**
* 描述:存放int类型的数据到sp中
*/
public static void putInt(Context ctx, String key, int value) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().putInt(key, value).commit();
}
/**
* 描述:取出sp中int类型的数据
*/
public static int getInt(Context ctx, String key, int defaultValue) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
return pref.getInt(key, defaultValue);
}
}
**6,主线程和子线程切换的工具类ThreadUtil **
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* 用于主线程和子线程切换的工具类
*/
public class ThreadUtil {
private static Handler sHandler = new Handler(Looper.getMainLooper());
// 当前是单一线程池,如需多个线程池改变接口的实现类即可
private static Executor sExecutor = Executors.newSingleThreadExecutor();
/**
* 描述:运行在子线程
*/
public static void runOnSubThread(Runnable runnable) {
sExecutor.execute(runnable);
}
/**
* 描述:运行在主线程
*/
public static void runOnMainThread(Runnable runnable) {
sHandler.post(runnable);
}
}
**7,判断是否具有Root权限的工具类RootUtil **
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
/**
* 用于判断是否具有Root权限的工具类RootUtil
*/
public class RootUtil {
@Deprecated
public static boolean isRooted() {
Process process = null;
try {
process = Runtime.getRuntime().exec("su");
OutputStream outputStream = process.getOutputStream();
InputStream inputStream = process.getInputStream();
outputStream.write("id\n".getBytes());
outputStream.flush();
outputStream.write("exit\n".getBytes());
outputStream.flush();
process.waitFor();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s = bufferedReader.readLine();
if (s.contains("uid=0")) return true;
} catch (IOException e) {
Log.e(TAG, "没有root权限");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (process != null)
process.destroy();
}
return false;
}
public static boolean checkRooted() {
boolean result = false;
try {
result = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
**8,获取Release方式打包证书SHA1值工具类 MessageDigestUtil **
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
/**
* 获取Release方式打包证书SHA1值工具类 MessageDigestUtil
*/
public class Sha1Utils {
public static String getCertificateSHA1Fingerprint(Context context) {
// 获取包管理器
PackageManager pm = context.getPackageManager();
// 获取当前要获取SHA1值的包名,也可以用其他的包名,但需要注意,
// 在用其他包名的前提是,此方法传递的参数Context应该是对应包的上下文。
String packageName = context.getPackageName();
// 返回包括在包中的签名信息
int flags = PackageManager.GET_SIGNATURES;
PackageInfo packageInfo = null;
try {
// 获得包的所有内容信息类
packageInfo = pm.getPackageInfo(packageName, flags);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
// 签名信息
Signature[] signatures = packageInfo.signatures;
byte[] cert = signatures[0].toByteArray();
// 将签名转换为字节数组流
InputStream input = new ByteArrayInputStream(cert);
// 证书工厂类,这个类实现了出厂合格证算法的功能
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X509");
} catch (Exception e) {
e.printStackTrace();
}
// X509证书,X.509是一种非常通用的证书格式
X509Certificate c = null;
try {
c = (X509Certificate) cf.generateCertificate(input);
} catch (Exception e) {
e.printStackTrace();
}
String hexString = null;
try {
// 加密算法的类,这里的参数可以改为MD5,SHA256等
MessageDigest md = MessageDigest.getInstance("SHA1");
//获得公钥
byte[] publicKey = md.digest(c.getEncoded());
// 字节到十六进制的格式转换
hexString = byte2HexFormatted(publicKey);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (CertificateEncodingException e) {
e.printStackTrace();
}
return hexString;
}
/**
* 将获取到得编码进行16进制转换
*/
private static String byte2HexFormatted(byte[] arr) {
StringBuilder str = new StringBuilder(arr.length * 2);
for (int i = 0; i < arr.length; i++) {
String h = Integer.toHexString(arr[i]);
int l = h.length();
if (l == 1)
h = "0" + h;
if (l > 2)
h = h.substring(l - 2, l);
str.append(h.toUpperCase());
if (i < (arr.length - 1))
str.append(':');
}
return str.toString();
}
}
----------因本人才疏学浅,如博客或Demo中有错误的地方请大家随意指出,与大家一起讨论,共同进步,谢谢!----------