主要积累开发中常用的工具类,部分来源于网络。
1.判断手机网络类型。
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
/**
* Created by Administrator on 2016/11/3.
* 获取手机网络状态,详细到移动网络类型
*/
public class NetWorkUtil {
/** 没有网络 */
public static final int NETWORKTYPE_INVALID = 0;
/** wap网络 */
public static final int NETWORKTYPE_WAP = 1;
/** 2G网络 */
public static final int NETWORKTYPE_2G = 2;
/** 3G和3G以上网络,或统称为快速网络 */
public static final int NETWORKTYPE_3G = 3;
/** wifi网络 */
public static final int NETWORKTYPE_WIFI = 4;
private static int mNetWorkType;
/**
* 获取网络状态,wifi,wap,2g,3g.
*
* @param context 上下文
* @return int 网络状态 {@link #NETWORKTYPE_2G},{@link #NETWORKTYPE_3G}, *{@link #NETWORKTYPE_INVALID},{@link #NETWORKTYPE_WAP}* <p>{@link #NETWORKTYPE_WIFI}
*/
public static int getNetWorkType(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String type = networkInfo.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
mNetWorkType = NETWORKTYPE_WIFI;
} else if (type.equalsIgnoreCase("MOBILE")) {
String proxyHost = android.net.Proxy.getDefaultHost();
mNetWorkType = TextUtils.isEmpty(proxyHost)
? (isFastMobileNetwork(context) ? NETWORKTYPE_3G : NETWORKTYPE_2G)
: NETWORKTYPE_WAP;
}
} else {
mNetWorkType = NETWORKTYPE_INVALID;
}
LogUtil.e("info","mNetWorkType:" + mNetWorkType);
return mNetWorkType;
}
/**
* 通过TelephonyManager判断移动网络的类型
* @param context
* @return
*/
private static boolean isFastMobileNetwork(Context context) {
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
switch (telephonyManager.getNetworkType()) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_EHRPD:
return true; // ~ 1-2 Mbps
case TelephonyManager.NETWORK_TYPE_EVDO_B:
return true; // ~ 5 Mbps
case TelephonyManager.NETWORK_TYPE_HSPAP:
return true; // ~ 10-20 Mbps
case TelephonyManager.NETWORK_TYPE_IDEN:
return false; // ~25 kbps
case TelephonyManager.NETWORK_TYPE_LTE:
return true; // ~ 10+ Mbps
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
return false;
default:
return false;
}
}
}
2.日志工具类
public class L
{
private L()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
private static final String TAG = "way";
// 下面四个是默认tag的函数
public static void i(String msg)
{
if (isDebug)
Log.i(TAG, msg);
}
public static void d(String msg)
{
if (isDebug)
Log.d(TAG, msg);
}
public static void e(String msg)
{
if (isDebug)
Log.e(TAG, msg);
}
public static void v(String msg)
{
if (isDebug)
Log.v(TAG, msg);
}
// 下面是传入自定义tag的函数
public static void i(String tag, String msg)
{
if (isDebug)
Log.i(tag, msg);
}
public static void d(String tag, String msg)
{
if (isDebug)
Log.i(tag, msg);
}
public static void e(String tag, String msg)
{
if (isDebug)
Log.i(tag, msg);
}
public static void v(String tag, String msg)
{
if (isDebug)
Log.i(tag, msg);
}
}
3.屏幕相关辅助类
public class ScreenUtils
{
private ScreenUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获得屏幕宽度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* 获得屏幕高度
*
* @param context
* @return
*/
public static int getScreenHeight(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context)
{
int statusHeight = -1;
try
{
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e)
{
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取当前屏幕截图,包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}
4.打开关闭软键盘
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);
}
}
5.http辅助类
public class WebSveUtil { /* * 发送Get请求 * @param urlPath url地址 * @return String字符串 * */ public static String do_get(String urlPath) { String dataResp = null; try { URL url = new URL(urlPath); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.connect(); InputStreamReader inr = new InputStreamReader(urlConnection.getInputStream()); BufferedReader buffer = new BufferedReader(inr); dataResp = readInputStream(urlConnection.getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dataResp; } /* * 发送Post请求 * @param urlPath url地址 * @param paramNameList 参数名称列表 * @param paramNameList 参数值列表 * @return String字符串 * */ public static String do_post(String urlPath, String[] paramNameList, String[] paramValueList) { StringBuffer params = new StringBuffer(); if (paramNameList.length >= 0) { for(int i = 0; i < paramNameList.length; i++) { params.append(paramNameList[i] + "=" ); try { params.append(URLEncoder.encode(paramValueList[i], "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if(i < paramNameList.length - 1) { params.append("&"); } } } return post(urlPath, params.toString()); } /* * 发送Post请求 * @param urlPath url地址 * @param params POJO对象的字符串表达式,如:user.name=james&user.age=38&user.address=cav * @return String字符串 * */ public static String do_post(String urlPath, String paramsPOJO) { return post(urlPath, paramsPOJO); } private static String post(String urlPath, String params) { String dataResp = null; byte[] postData = params.getBytes(); try { URL url = new URL(urlPath); HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("POST"); urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.connect(); DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream()); dos.write(postData); dos.flush();; dos.close(); if(urlConnection.getResponseCode() == 200) { dataResp = readInputStream(urlConnection.getInputStream()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dataResp; } private static String readInputStream(InputStream in) { StringBuffer sbuff = new StringBuffer(); InputStreamReader inr = new InputStreamReader(in); BufferedReader buffer = new BufferedReader(inr); String inputLine = null; try { while ((inputLine = buffer.readLine()) != null) { sbuff.append(inputLine); } } catch (IOException e) { e.printStackTrace(); } return sbuff.toString(); } //获取图片 public static Bitmap getBitmap(String urlStr) throws IOException { Bitmap bitmap; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5*1000); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); return bitmap; } // /* // * 规范web view使用的url // * */ // public static String getUrl(String urlPath, String[] paramNameList, String[] paramValueList) { // StringBuffer params = new StringBuffer(); // if (paramNameList.length >= 0) { // for(int i = 0; i < paramNameList.length; i++) { // params.append(paramNameList[i] + "=" ); // try { // params.append(URLEncoder.encode(paramValueList[i], "utf-8")); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // if(i < paramNameList.length - 1) { // params.append("&"); // } // } // } // return urlPath +"?"+ params.toString(); // } /* * 规范web view使用的url * */ public static String getUrl(String urlPath, Map<String, String> map) { StringBuffer params = new StringBuffer(); if (map.size() >= 0) { for (Map.Entry<String, String> entry : map.entrySet()) { params.append(entry.getKey() + "=" + entry.getValue()); params.append("&"); } params.deleteCharAt(params.length() - 1); } return urlPath +"?"+ params.toString(); } }
6.常用正则表达式
public class RegularUtils { private RegularUtils() { throw new UnsupportedOperationException("u can't fuck me..."); } /** * 验证手机号(简单) */ private static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$"; /** * 验证手机号(精确) * <p> * <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188 * <p>联通:130、131、132、145、155、156、175、176、185、186 * <p>电信:133、153、173、177、180、181、189 * <p>全球星:1349 * <p>虚拟运营商:170 */ private static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-8])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$"; /** * 验证座机号,正确格式:xxx/xxxx-xxxxxxx/xxxxxxxx/ */ private static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}"; /** * 验证邮箱 */ private static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; /** * 验证url */ private static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?"; /** * 验证汉字 */ private static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$"; /** * 验证用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位 */ private static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$"; /** * 验证IP地址 */ private static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"; //If u want more please visit http://toutiao.com/i6231678548520731137/ /** * @param string 待验证文本 * @return 是否符合手机号(简单)格式 */ public static boolean isMobileSimple(String string) { return isMatch(REGEX_MOBILE_SIMPLE, string); } /** * @param string 待验证文本 * @return 是否符合手机号(精确)格式 */ public static boolean isMobileExact(String string) { return isMatch(REGEX_MOBILE_EXACT, string); } /** * @param string 待验证文本 * @return 是否符合座机号码格式 */ public static boolean isTel(String string) { return isMatch(REGEX_TEL, string); } /** * @param string 待验证文本 * @return 是否符合邮箱格式 */ public static boolean isEmail(String string) { return isMatch(REGEX_EMAIL, string); } /** * @param string 待验证文本 * @return 是否符合网址格式 */ public static boolean isURL(String string) { return isMatch(REGEX_URL, string); } /** * @param string 待验证文本 * @return 是否符合汉字 */ public static boolean isChz(String string) { return isMatch(REGEX_CHZ, string); } /** * @param string 待验证文本 * @return 是否符合用户名 */ public static boolean isUsername(String string) { return isMatch(REGEX_USERNAME, string); } /** * @param regex 正则表达式字符串 * @param string 要匹配的字符串 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false; */ public static boolean isMatch(String regex, String string) { return !TextUtils.isEmpty(string) && Pattern.matches(regex, string); } }
7.时间相关
public class DateUtils { private static SimpleDateFormat sf; private static SimpleDateFormat sdf; /** * 获取系统时间 格式为:"yyyy/MM/dd " **/ public static String getCurrentDate() { Date d = new Date(); sf = new SimpleDateFormat("yyyy年MM月dd日"); return sf.format(d); } /** * 获取系统时间 格式为:"yyyy " **/ public static String getCurrentYear() { Date d = new Date(); sf = new SimpleDateFormat("yyyy"); return sf.format(d); } /** * 获取系统时间 格式为:"MM" **/ public static String getCurrentMonth() { Date d = new Date(); sf = new SimpleDateFormat("MM"); return sf.format(d); } /** * 获取系统时间 格式为:"dd" **/ public static String getCurrentDay() { Date d = new Date(); sf = new SimpleDateFormat("dd"); return sf.format(d); } /** * 获取当前时间戳 * * @return */ public static long getCurrentTime() { long d = new Date().getTime() / 1000; return d; } /** * 时间戳转换成字符窜 */ public static String getDateToString(long time) { Date d = new Date(time * 1000); sf = new SimpleDateFormat("yyyy年MM月dd日"); return sf.format(d); } /** * 时间戳中获取年 */ public static String getYearFromTime(long time) { Date d = new Date(time * 1000); sf = new SimpleDateFormat("yyyy"); return sf.format(d); } /** * 时间戳中获取月 */ public static String getMonthFromTime(long time) { Date d = new Date(time * 1000); sf = new SimpleDateFormat("MM"); return sf.format(d); } /** * 时间戳中获取日 */ public static String getDayFromTime(long time) { Date d = new Date(time * 1000); sf = new SimpleDateFormat("dd"); return sf.format(d); } /** * 将字符串转为时间戳 */ public static long getStringToDate(String time) { sdf = new SimpleDateFormat("yyyy年MM月dd日"); Date date = new Date(); try { date = sdf.parse(time); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return date.getTime(); } }
8.解析XML工具类
public class XMLUtil { private XMLUtil(){} /*- * XML文件解析成实体,不涉及到标签的属性值。 * @param xml xml字符串文件 * @param clazz 对应实体的class文件 * @param tagEntity * 开始解析实体的标签,例如下面的实例中就是student<br> * < person ><br> * < student ><br> * < name >Lucy< /name ><br> * < age >21< /age ><br> * < /student ><br> * < /person ><br> * @return 返回解析的对应实体文件 */ public static<T> List<T> xmlToObject(String xml, Class<T> clazz, String tagEntity){ List<T> list = null; XmlPullParser xmlPullParser = Xml.newPullParser(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); try { xmlPullParser.setInput(inputStream, "utf-8"); Field[] fields = clazz.getDeclaredFields(); int type = xmlPullParser.getEventType(); String lastTag = ""; T t = null; while (type != XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<T>(); break; case XmlPullParser.START_TAG: String tagName = xmlPullParser.getName(); if(tagEntity.equals(tagName)){ t = clazz.newInstance(); lastTag = tagEntity; }else if(tagEntity.equals(lastTag)){ String textValue = xmlPullParser.nextText(); String fieldName = xmlPullParser.getName(); for(Field field : fields){ ReflectUtil.setFieldValue(t,field,fieldName,textValue); } } break; case XmlPullParser.END_TAG: tagName = xmlPullParser.getName(); if(tagEntity.equals(tagName)){ list.add(t); lastTag = ""; } break; case XmlPullParser.END_DOCUMENT: break; } } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; } /** * 获取xml字符串标签中的属性值 * @param xml xml字符串 * @param clazz 转换成对应的实体 * @param tagName 实体对应xml字符串的起始标签,如下面实例中的person标签<br> * < person name="Lucy" age="12"><br> * < student ><br> * < name >Lucy< /name ><br> * < age >21< /age ><br> * < /student ><br> * < /person ><br> * @return 返回属性值组成的List对象集合。 */ public static<T> List<T> attributeToObject(String xml, Class<T> clazz, String tagName){ if(TextUtils.isEmpty(tagName))return null; List<T> list = null; XmlPullParser xmlPullParser = Xml.newPullParser(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); try { xmlPullParser.setInput(inputStream, "utf-8"); int type = xmlPullParser.getEventType(); T t = null; while(type != XmlPullParser.END_DOCUMENT){ switch(type){ case XmlPullParser.START_DOCUMENT: list = new ArrayList<T>(); break; case XmlPullParser.START_TAG: if(tagName.equals(xmlPullParser.getName())){ t = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for(Field field : fields){ String fieldName = field.getName(); for(int index = 0;index < xmlPullParser.getAttributeCount();index++){ if(fieldName.equals(xmlPullParser.getAttributeName(index))){ ReflectUtil.setFieldValue(t,field,fieldName,xmlPullParser.getAttributeValue(index)); } } } } break; case XmlPullParser.END_TAG: if(tagName.equals(xmlPullParser.getName())){ list.add(t); } break; case XmlPullParser.END_DOCUMENT: break; } type = xmlPullParser.next(); } }catch(Exception ex){ ex.printStackTrace(); } return list; } /** * 获取Xml文件中的属性值 * @param xml xml文件字符串 * @param tagName 标签名称 * @param attributeName 属性名称 * @return 返回获取的值,或者null */ public static String getTagAttribute(String xml, String tagName, String attributeName){ if(TextUtils.isEmpty(tagName) || TextUtils.isEmpty(attributeName)){ throw new IllegalArgumentException("请填写标签名称或属性名称"); } XmlPullParser xmlPullParser = Xml.newPullParser(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); try { xmlPullParser.setInput(inputStream, "utf-8"); int type = xmlPullParser.getEventType(); while(type != XmlPullParser.END_DOCUMENT){ switch(type){ case XmlPullParser.START_TAG: if(tagName.equals(xmlPullParser.getName())){ for(int i=0; i < xmlPullParser.getAttributeCount();i++){ if(attributeName.equals(xmlPullParser.getAttributeName(i))){ return xmlPullParser.getAttributeValue(i); } } } break; } type = xmlPullParser.next(); } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
9.手机组建调用工具类
public class PhoneUtil { private static long lastClickTime; private PhoneUtil() { throw new Error("Do not need instantiate!"); } /** * 调用系统发短信界面 * @param activity Activity * @param phoneNumber 手机号码 * @param smsContent 短信内容 */ public static void sendMessage(Context activity, String phoneNumber, String smsContent) { if (smsContent == null || phoneNumber.length() < 4) { return; } Uri uri = Uri.parse("smsto:" + phoneNumber); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", smsContent); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } /** * 判断是否为连击 * @return boolean */ public static boolean isFastDoubleClick() { long time = System.currentTimeMillis(); long timeD = time - lastClickTime; if (0 < timeD && timeD < 500) { return true; } lastClickTime = time; return false; } /** * 获取手机型号 * @param context 上下文 * @return String */ public static String getMobileModel(Context context) { try { String model = android.os.Build.MODEL; return model; } catch (Exception e) { return "未知!"; } } /** * 获取手机品牌 * @param context 上下文 * @return String */ public static String getMobileBrand(Context context) { try { // android系统版本号 String brand = android.os.Build.BRAND; return brand; } catch (Exception e) { return "未知"; } } /** *拍照打开照相机! * @param requestcode 返回值 * @param activity 上下文 * @param fileName 生成的图片文件的路径 */ public static void toTakePhoto(int requestcode, Activity activity,String fileName) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra("camerasensortype", 2);// 调用前置摄像头 intent.putExtra("autofocus", true);// 自动对焦 intent.putExtra("fullScreen", false);// 全屏 intent.putExtra("showActionIcons", false); try { //创建一个当前任务id的文件,然后里面存放任务的照片和路径!这主文件的名字是用uuid到时候再用任务id去查路径! File file = new File(fileName); //如果这个文件不存在就创建一个文件夹! if (!file.exists()) { file.mkdirs(); } Uri uri = Uri.fromFile(file); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); activity.startActivityForResult(intent, requestcode); } catch (Exception e) { e.printStackTrace(); } } /** *打开相册 * @param requestcode 响应码 * @param activity 上下文 */ public static void toTakePicture(int requestcode, Activity activity){ Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); activity.startActivityForResult(intent, requestcode); } }
10.string.xml中s%用法
在strings.xml中添加字符串 string name="text">Hello,%s!</string> 代码中使用 textView.setText(String.format(getResources().getString(R.string.text),"Android")); 输出结果:Hello,Android!
11.二维码工具类,需要zxing.jar类库支持
public class QrCodeUtils { /** * 传入字符串生成二维码 * @param str * @return * @throws WriterException */ public static Bitmap Create2DCode(String str) throws WriterException { // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败 BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 300, 300); int width = matrix.getWidth(); int height = matrix.getHeight(); // 二维矩阵转为一维像素数组,也就是一直横着排了 int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // 通过像素数组生成bitmap,具体参考api bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } }