分享自己的一些android util 源文件
getStringList(JSONObject jsonObject, String key, List defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { List list = new ArrayList (); for (int i = 0; i < statusArray.length(); i++) { list.add(statusArray.getString(i)); } return list; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; } /** * get String list from jsonData * * @param jsonData * @param key * @param defaultValue * @return getStringList(String jsonData, String key, List defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getStringList(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return getMap(JSONObject jsonObject, String key) { return JSONUtils.parseKeyAndValueToMap(JSONUtils.getString(jsonObject, key, null)); } /** * get map from jsonData. * * @param jsonData key-value pairs string * @param key * @return getMap(String jsonData, String key) { if (jsonData == null) { return null; } if (jsonData.length() == 0) { return new HashMap (); } try { JSONObject jsonObject = new JSONObject(jsonData); return getMap(jsonObject, key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return null; } } /** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param sourceObj key-value pairs json * @return parseKeyAndValueToMap(JSONObject sourceObj) { if (sourceObj == null) { return null; } Map keyAndValueMap = new HashMap (); for (Iterator iter = sourceObj.keys(); iter.hasNext();) { String key = (String)iter.next(); MapUtils.putMapNotEmptyKey(keyAndValueMap, key, getString(sourceObj, key, "")); } return keyAndValueMap; } /** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param source key-value pairs json * @return parseKeyAndValueToMap(String source) { if (StringUtils.isEmpty(source)) { return null; } try { JSONObject jsonObject = new JSONObject(source); return parseKeyAndValueToMap(jsonObject); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return null; } }} in mainfest **/ StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ") .append(pmParams == null ? "" : pmParams).append(" ").append(filePath.replace(" ", "\\ ")); CommandResult commandResult = ShellUtils.execCommand(command.toString(), !isSystemApplication(context), true); if (commandResult.successMsg != null && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) { return INSTALL_SUCCEEDED; } Log.e(TAG, new StringBuilder().append("installSilent successMsg:").append(commandResult.successMsg) .append(", ErrorMsg:").append(commandResult.errorMsg).toString()); if (commandResult.errorMsg == null) { return INSTALL_FAILED_OTHER; } if (commandResult.errorMsg.contains("INSTALL_FAILED_ALREADY_EXISTS")) { return INSTALL_FAILED_ALREADY_EXISTS; } if (commandResult.errorMsg.contains("INSTALL_FAILED_INVALID_APK")) { return INSTALL_FAILED_INVALID_APK; } if (commandResult.errorMsg.contains("INSTALL_FAILED_INVALID_URI")) { return INSTALL_FAILED_INVALID_URI; } if (commandResult.errorMsg.contains("INSTALL_FAILED_INSUFFICIENT_STORAGE")) { return INSTALL_FAILED_INSUFFICIENT_STORAGE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_DUPLICATE_PACKAGE")) { return INSTALL_FAILED_DUPLICATE_PACKAGE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_NO_SHARED_USER")) { return INSTALL_FAILED_NO_SHARED_USER; } if (commandResult.errorMsg.contains("INSTALL_FAILED_UPDATE_INCOMPATIBLE")) { return INSTALL_FAILED_UPDATE_INCOMPATIBLE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE")) { return INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_MISSING_SHARED_LIBRARY")) { return INSTALL_FAILED_MISSING_SHARED_LIBRARY; } if (commandResult.errorMsg.contains("INSTALL_FAILED_REPLACE_COULDNT_DELETE")) { return INSTALL_FAILED_REPLACE_COULDNT_DELETE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_DEXOPT")) { return INSTALL_FAILED_DEXOPT; } if (commandResult.errorMsg.contains("INSTALL_FAILED_OLDER_SDK")) { return INSTALL_FAILED_OLDER_SDK; } if (commandResult.errorMsg.contains("INSTALL_FAILED_CONFLICTING_PROVIDER")) { return INSTALL_FAILED_CONFLICTING_PROVIDER; } if (commandResult.errorMsg.contains("INSTALL_FAILED_NEWER_SDK")) { return INSTALL_FAILED_NEWER_SDK; } if (commandResult.errorMsg.contains("INSTALL_FAILED_TEST_ONLY")) { return INSTALL_FAILED_TEST_ONLY; } if (commandResult.errorMsg.contains("INSTALL_FAILED_CPU_ABI_INCOMPATIBLE")) { return INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_MISSING_FEATURE")) { return INSTALL_FAILED_MISSING_FEATURE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_CONTAINER_ERROR")) { return INSTALL_FAILED_CONTAINER_ERROR; } if (commandResult.errorMsg.contains("INSTALL_FAILED_INVALID_INSTALL_LOCATION")) { return INSTALL_FAILED_INVALID_INSTALL_LOCATION; } if (commandResult.errorMsg.contains("INSTALL_FAILED_MEDIA_UNAVAILABLE")) { return INSTALL_FAILED_MEDIA_UNAVAILABLE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_VERIFICATION_TIMEOUT")) { return INSTALL_FAILED_VERIFICATION_TIMEOUT; } if (commandResult.errorMsg.contains("INSTALL_FAILED_VERIFICATION_FAILURE")) { return INSTALL_FAILED_VERIFICATION_FAILURE; } if (commandResult.errorMsg.contains("INSTALL_FAILED_PACKAGE_CHANGED")) { return INSTALL_FAILED_PACKAGE_CHANGED; } if (commandResult.errorMsg.contains("INSTALL_FAILED_UID_CHANGED")) { return INSTALL_FAILED_UID_CHANGED; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_NOT_APK")) { return INSTALL_PARSE_FAILED_NOT_APK; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_BAD_MANIFEST")) { return INSTALL_PARSE_FAILED_BAD_MANIFEST; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION")) { return INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_NO_CERTIFICATES")) { return INSTALL_PARSE_FAILED_NO_CERTIFICATES; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES")) { return INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING")) { return INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME")) { return INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID")) { return INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_MANIFEST_MALFORMED")) { return INSTALL_PARSE_FAILED_MANIFEST_MALFORMED; } if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_MANIFEST_EMPTY")) { return INSTALL_PARSE_FAILED_MANIFEST_EMPTY; } if (commandResult.errorMsg.contains("INSTALL_FAILED_INTERNAL_ERROR")) { return INSTALL_FAILED_INTERNAL_ERROR; } return INSTALL_FAILED_OTHER; } /** * uninstall according conditions *
发布日期:2021-06-29 15:24:36
浏览次数:3
分类:技术文章
本文共 104690 字,大约阅读时间需要 348 分钟。
ZipUtils.java 包含解压和压缩的接口。解决网上解压缺失文件的问题。 FileUtils.java 文件操作,删除文件,目录,创建等接口 CopyRawtodata.java 复制Raw文件到data区域 CheckPWD.java 检测密码强度,5等级 ScreenUtils.java 获取屏幕宽高 Log.java log相关 sharedPreferencesHelps.java 存储配置相关接口 commonUtil.java 常用的一些接口 packageutils.java 安装相关的工具 Randomutil.java 随机数 jsonUitl.java解析接口
package com.lxm.tools;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Collection;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipException;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;/** * Java utils ʵ�ֵ�Zip���� * * @author once */public class ZipUtils { private static final int BUFF_SIZE = 512 * 1024; // 1M/2 Byte /** * ����ѹ���ļ����У� * * @param resFileList * Ҫѹ�����ļ����У��б� * @param zipFile * ���ɵ�ѹ���ļ� * @throws IOException * ��ѹ�����̳���ʱ�׳� */ public static void zipFiles(CollectionresFileList, File zipFile) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.close(); } /** * ����ѹ���ļ����У� * * @param resFileList * Ҫѹ�����ļ����У��б� * @param zipFile * ���ɵ�ѹ���ļ� * @param comment * ѹ���ļ���ע�� * @throws IOException * ��ѹ�����̳���ʱ�׳� */ public static void zipFiles(Collection resFileList, File zipFile, String comment) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.setComment(comment); zipout.close(); } /** * ��ѹ��һ���ļ� * * @param zipFile * ѹ���ļ� * @param folderPath * ��ѹ����Ŀ��Ŀ¼ * @throws IOException * ����ѹ�����̳���ʱ�׳� */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry) entries.nextElement()); InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = str = new String(str.getBytes(), "utf-8"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.flush(); out.close(); } } /** * ��ѹ�ļ��������������ֵ��ļ� * * @param zipFile * ѹ���ļ� * @param folderPath * Ŀ���ļ��� * @param nameContains * ������ļ�ƥ���� * @throws ZipException * ѹ����ʽ����ʱ�׳� * @throws IOException * IO����ʱ�׳� */ public static ArrayList upZipSelectedFile(File zipFile, String folderPath, String nameContains) throws ZipException, IOException { ArrayList fileList = new ArrayList (); File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdir(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry) entries.nextElement()); if (entry.getName().contains(nameContains)) { InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes(), "utf-8"); // str.getBytes("GB2312"),"8859_1" ��� // str.getBytes("8859_1"),"GB2312" ���� File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); fileList.add(desFile); } } return fileList; } /** * ���ѹ���ļ����ļ��б� * * @param zipFile * ѹ���ļ� * @return ѹ���ļ����ļ����� * @throws ZipException * ѹ���ļ���ʽ����ʱ�׳� * @throws IOException * ����ѹ�����̳���ʱ�׳� */ public static int getEntriesNames(File zipFile) throws ZipException, IOException { int count=0; ArrayList entryNames = new ArrayList (); Enumeration entries = getEntriesEnumeration(zipFile); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry) entries.nextElement()); count+=1; } return count; } /** * ���ѹ���ļ���ѹ���ļ�������ȡ�������� * * @param zipFile * ѹ���ļ� * @return ����һ��ѹ���ļ��б� * @throws ZipException * ѹ���ļ���ʽ����ʱ�׳� * @throws IOException * IO��������ʱ�׳� */ public static Enumeration getEntriesEnumeration(File zipFile) throws ZipException, IOException { ZipFile zf = new ZipFile(zipFile); return zf.entries(); } /** * ȡ��ѹ���ļ������ע�� * * @param entry * ѹ���ļ����� * @return ѹ���ļ������ע�� * @throws UnsupportedEncodingException */ public static String getEntryComment(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getComment().getBytes("GB2312"), "8859_1"); } /** * ȡ��ѹ���ļ���������� * * @param entry * ѹ���ļ����� * @return ѹ���ļ���������� * @throws UnsupportedEncodingException */ public static String getEntryName(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getName().getBytes("GB2312"), "8859_1"); } /** * ѹ���ļ� * * @param resFile * ��Ҫѹ�����ļ����У� * @param zipout * ѹ����Ŀ���ļ� * @param rootpath * ѹ�����ļ�·�� * @throws FileNotFoundException * �Ҳ����ļ�ʱ�׳� * @throws IOException * ��ѹ�����̳���ʱ�׳� */ private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException { rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName(); rootpath = new String(rootpath.getBytes("8859_1"), "GB2312"); if (resFile.isDirectory()) { File[] fileList = resFile.listFiles(); for (File file : fileList) { zipFile(file, zipout, rootpath); } } else { byte buffer[] = new byte[BUFF_SIZE]; BufferedInputStream in = new BufferedInputStream( new FileInputStream(resFile), BUFF_SIZE); zipout.putNextEntry(new ZipEntry(rootpath)); int realLength; while ((realLength = in.read(buffer)) != -1) { zipout.write(buffer, 0, realLength); } in.close(); zipout.flush(); zipout.closeEntry(); } }}
package com.lxm.tools;import java.io.BufferedWriter;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.RandomAccessFile;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException;import android.util.Log;/** * File utilities */public class FileUtils { // Logging private static final String TAG = "FileUtils"; /** * It is not possible to instantiate this class */ private FileUtils() { } /** * Delete all the files in the specified folder and the folder itself. * * @param dir * The project path */ public static boolean deleteDir(File dir) { if (dir.isDirectory()) { final String[] children = dir.list(); for (int i = 0; i < children.length; i++) { final File f = new File(dir, children[i]); if (!deleteDir(f)) { Log.e(TAG, "File cannot be deleted: " + f.getAbsolutePath()); return false; } } } // The directory is now empty so delete it return dir.delete(); } public static boolean deleteFile(File file) { boolean del = false; if (file.exists() && file.isFile()) { del = file.delete(); } // The directory is now empty so delete it return del; } /** * Get the name of the file * * @param filename * The full path filename * @return The name of the file */ public static String getSimpleName(String filename) { final int index = filename.lastIndexOf('/'); if (index == -1) { return filename; } else { return filename.substring(index + 1); } } /** * �ж������ַ� * * @Title : FilterStr * @Type : FilterString * @date : 2014��2��28�� ����11:01:21 * @Description : �ж������ַ� * @param str * @return * @throws PatternSyntaxException */ public static String FilterStr(String str) throws PatternSyntaxException { /** * �����ַ� */ String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~��@#��%����&*��������+|{}������������������������_]"; /** * Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaab"); * boolean b = m.matches(); */ Pattern pat = Pattern.compile(regEx); Matcher mat = pat.matcher(str); /** * �����滻��� */ return mat.replaceAll("").trim(); } public static void writestr(String flpath, String str) { FileWriter fw = null; BufferedWriter bw = null; try { File s = new File(flpath); if(!s.exists()){ s.createNewFile(); } fw = new FileWriter(s, true);// // ����FileWriter��������д���ַ��� bw = new BufferedWriter(fw); // ��������ļ������ bw.write(str); // д���ļ� bw.newLine(); bw.flush(); // ˢ�¸����Ļ��� bw.close(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e1) { // TODO Auto-generated catch block } } } public static void writelog(String flpath, String str) { FileWriter fw = null; BufferedWriter bw = null; try { File s = new File(flpath); if(!s.exists()){ s.mkdir(); } String fn = flpath + "log.txt"; File s1 = new File(fn); if(!s1.exists()){ s1.createNewFile(); } fw = new FileWriter(s1, true);// // ����FileWriter��������д���ַ��� bw = new BufferedWriter(fw); // ��������ļ������ bw.write(str); // д���ļ� bw.newLine(); bw.flush(); // ˢ�¸����Ļ��� bw.close(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e1) { // TODO Auto-generated catch block } } } public static String readFileContentStr(String fullFilename) { String readOutStr = null; try { DataInputStream dis = new DataInputStream(new FileInputStream( fullFilename)); try { long len = new File(fullFilename).length(); if (len > Integer.MAX_VALUE) throw new IOException("File " + fullFilename + " too large, was " + len + " bytes."); byte[] bytes = new byte[(int) len]; dis.readFully(bytes); readOutStr = new String(bytes, "UTF-8"); } finally { dis.close(); } Log.d("readFileContentStr", "Successfully to read out string from file " + fullFilename); } catch (IOException e) { readOutStr = null; // e.printStackTrace(); Log.d("readFileContentStr", "Fail to read out string from file " + fullFilename); } return readOutStr; } public static void writeTxtToFile(String strcontent, String filePath, String fileName) { //�����ļ���֮���������ļ�����Ȼ����� makeFilePath(filePath, fileName); String strFilePath = filePath+fileName; // ÿ��д��ʱ��������д String strContent = strcontent + "\r\n"; try { File file = new File(strFilePath); if (!file.exists()) { Log.d("TestFile", "Create the file:" + strFilePath); file.getParentFile().mkdirs(); file.createNewFile(); } RandomAccessFile raf = new RandomAccessFile(file, "rwd"); raf.seek(file.length()); raf.write(strContent.getBytes()); raf.close(); } catch (Exception e) { Log.e("TestFile", "Error on write File:" + e); } } // �����ļ� public static File makeFilePath(String filePath, String fileName) { File file = null; makeRootDirectory(filePath); try { file = new File(filePath + fileName); if (!file.exists()) { file.createNewFile(); } } catch (Exception e) { e.printStackTrace(); } return file; } // �����ļ��� public static void makeRootDirectory(String filePath) { File file = null; try { file = new File(filePath); if (!file.exists()) { file.mkdir(); } } catch (Exception e) { Log.i("error:", e+""); } }}
package com.lxm.tools;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;final public class CopyRawtodata { public static boolean CopyRawtodata(String path,String DbName,Context context,int id,boolean IsRawData) { boolean dbExist=checkDataBase(path,DbName); if(!dbExist) { try{ copyDataBase(path,DbName,context,id,IsRawData); }catch(IOException e){ throw new Error("Error copying database"); } } return true; } private static boolean checkDataBase(String path,String DbName) { SQLiteDatabase checkDB = null; try{ String databaseFilename = path+"/"+DbName; checkDB =SQLiteDatabase.openDatabase(databaseFilename, null, SQLiteDatabase.OPEN_READONLY); }catch(SQLiteException e){ } if(checkDB!=null){ checkDB.close(); } return checkDB !=null?true:false; } private static void copyDataBase(String path,String DbName,Context context,int ResId,boolean IsRawData) throws IOException{ String databaseFilenames =path+"/"+DbName; InputStream is; File dir = new File(path+"/"); if(!dir.exists())//�ж��ļ����Ƿ���ڣ������ھ��½�һ�� dir.mkdir(); FileOutputStream os = null; try{ os = new FileOutputStream(databaseFilenames);//�õ����ݿ��ļ���д���� }catch(FileNotFoundException e){ e.printStackTrace(); } if(IsRawData) { is = context.getResources().openRawResource(ResId);//�õ����ݿ��ļ��������� } else { is = context.getResources().getAssets().open(DbName);//�õ����ݿ��ļ��������� } byte[] buffer = new byte[8192]; int count = 0; try{ while((count=is.read(buffer))>0){ os.write(buffer, 0, count); os.flush(); } }catch(IOException e){ } try{ is.close(); os.close(); }catch(IOException e){ e.printStackTrace(); } }}
package com.lxm.tools;import java.util.regex.Matcher;import java.util.regex.Pattern;public class CheckPWD { public static Safelevel checkPasswordStrength(String c) { Safelevel d = Safelevel.WEAK; if (isEmptyPassword(c)) { return d; } if (isTooShort(c)) { d = Safelevel.WEAK; } else { if (hasNum(c) && hasLetter(c) && hasSymbol(c)) { d = Safelevel.SECURE; } else { if (hasNum(c) && hasLetter(c)) { d = Safelevel.STRONG; } else { if (hasNum(c) && hasSymbol(c)) { d = Safelevel.STRONG; } else { if (hasSymbol(c) && hasLetter(c)) { d = Safelevel.STRONG; } else { if (isAllNum(c) || isAllLetter(c) || isAllSymbol(c)) { d = Safelevel.WEAK; } } } } } } return d; } public enum Safelevel { WEAK, /* 弱 */ STRONG, /* 强 */ SECURE, /* 安全 */ } public static boolean hasNum(String content) { boolean flag = false; Pattern p = Pattern.compile(".*\\d+.*"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean hasSymbol(String content) { boolean flag = false; Pattern p = Pattern.compile(".*[a-zA-Z0-9\\s<>;'\\\\]+.*"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean isAllSymbol(String content) { boolean flag = false; Pattern p = Pattern.compile("^[a-zA-Z0-9\\s<>;'\\\\]+$"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean hasSpace(String content) { boolean flag = false; Pattern p = Pattern.compile(".*\\s+.*"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean hasIllegalSymbol(String content) { boolean flag = false; Pattern p = Pattern.compile(".*[\\s<>;'\\\\].*"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean hasLetter(String content) { boolean flag = false; Pattern p = Pattern.compile(".*[a-zA-Z]+.*"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean isAllLetter(String content) { boolean flag = false; Pattern p = Pattern.compile("^[a-zA-Z]+$"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } private static boolean isEmptyPassword(String b) { return (b == null || b.length() == 0); } private static boolean isTooShort(String b) { return b.length() < 6; } public static boolean isAllNum(String content) { boolean flag = false; Pattern p = Pattern.compile("^\\d+$"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean hasRepeat6Chars(String content) { boolean flag = false; Pattern p = Pattern.compile(".*([0-9a-zA-Z])\\1{5}.*"); Matcher m = p.matcher(content); if (m.matches()) flag = true; return flag; } public static boolean hasIncrease6Chars(String g) { if (g == null || g.length() < 6) { return false; } char h = g.charAt(0); char i = 1; char j = 1; for (j = 1; j < g.length(); j++) { char f = g.charAt(j); if (f == h + 1) { i++; if (i >= 6) { return true; } } else { i = 1; } h = f; } return false; } public static boolean hasDecrease6Chars(String g) { if (g == null || g.length() < 6) { return false; } char h = g.charAt(0); char i = 1; char j = 1; for (j = 1; j < g.length(); j++) { char f = g.charAt(j); if (f == h - 1) { i++; if (i >= 6) { return true; } } else { i = 1; } h = f; } return false; } public static boolean hasAllIncreaseChars(String g) { if (g == null) { return false; } int i = g.length(); char h = g.charAt(0); char j = 1; char k = 1; for (k = 1; k < g.length(); k++) { char l = g.charAt(k); if (l == h + 1) { j++; if (j >= i) { return true; } } else { j = 1; } h = l; } return false; } public static boolean hasAllDecreaseChars(String g) { if (g == null) { return false; } int i = g.length(); char h = g.charAt(0); char j = 1; char k = 1; for (k = 1; k < i; k++) { char l = g.charAt(k); if (l == h - 1) { j++; if (j >= i) { return true; } } else { j = 1; } h = l; } return false; } public static boolean isAllSameChars(String content) { if (content == null || content.length() < 2) { return false; } char h = content.charAt(0); char e = 1; for (e = 1; e < content.length(); e++) { char f = content.charAt(e); if (f != h) { return false; } } return true; }}
package com.lxm.tools;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Rect;import android.util.DisplayMetrics;import android.view.View;import android.view.WindowManager;/** * 获得屏幕相关的辅助类 * * * */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; }}
package cn.trinea.android.common.util;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;/** * Json Utils * * @author Trinea 2012-5-12 */public class JSONUtils { public static boolean isPrintException = true; private JSONUtils() { throw new AssertionError(); } /** * get Long from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getLong(String)} exception, return defaultValue *
- return {@link JSONObject#getLong(String)} *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getLong(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getInt(String)} exception, return defaultValue *
- return {@link JSONObject#getInt(String)} *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getInt(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getDouble(String)} exception, return defaultValue *
- return {@link JSONObject#getDouble(String)} *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getDouble(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getString(String)} exception, return defaultValue *
- return {@link JSONObject#getString(String)} *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getString(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if keyArray is null or empty, return defaultValue *
- get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly *
- *
- if jsonData is null, return defaultValue *
- if keyArray is null or empty, return defaultValue *
- get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getJSONArray(String)} exception, return defaultValue *
- if {@link JSONArray#getString(int)} exception, return defaultValue *
- return string array *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getStringArray(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getJSONArray(String)} exception, return defaultValue *
- if {@link JSONArray#getString(int)} exception, return defaultValue *
- return string array *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getStringList(JSONObject, String, List)} *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getJSONObject(String)} exception, return defaultValue *
- return {@link JSONObject#getJSONObject(String)} *
- *
- if jsonData is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getJSONObject(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if keyArray is null or empty, return defaultValue *
- get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly *
- *
- if jsonData is null, return defaultValue *
- if keyArray is null or empty, return defaultValue *
- get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- if {@link JSONObject#getJSONArray(String)} exception, return defaultValue *
- return {@link JSONObject#getJSONArray(String)} *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getJSONArray(JSONObject, String, JSONObject)} *
- *
- if jsonObject is null, return defaultValue *
- if key is null or empty, return defaultValue *
- return {@link JSONObject#getBoolean(String)} *
- *
- if jsonObject is null, return defaultValue *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue *
- return {@link JSONUtils#getBoolean(JSONObject, String, Boolean)} *
- *
- if jsonObject is null, return null *
- return {@link JSONUtils#parseKeyAndValueToMap(String)} *
- *
- if jsonData is null, return null *
- if jsonData length is 0, return empty map *
- if jsonData {@link JSONObject#JSONObject(String)} exception, return null *
- return {@link JSONUtils#getMap(JSONObject, String)} *
- *
- if sourceObj is null, return null *
- else parse entry by {@link MapUtils#putMapNotEmptyKey(Map, String, String)} one by one *
- *
- if source is null or source's length is 0, return empty map *
- if source {@link JSONObject#JSONObject(String)} exception, return null *
- return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)} *
package com.eric.account.util;import android.content.Context;import android.content.SharedPreferences;public class SharedPreferencesHelper { Context context; SharedPreferences.Editor editor; SharedPreferences sp; public SharedPreferencesHelper(Context paramContext, String paramString) { this.context = paramContext; this.sp = this.context.getSharedPreferences(paramString, 0); this.editor = this.sp.edit(); } public SharedPreferences getSharedPreferences() { return this.sp; } public void putValue(String paramString1, String paramString2) { this.editor = this.sp.edit(); this.editor.putString(paramString1, paramString2); this.editor.commit(); } public void putValue(String paramString1, boolean paramString2) { this.editor = this.sp.edit(); this.editor.putBoolean(paramString1, paramString2); this.editor.commit(); } public String getStrValue(String paramString1) { return sp.getString(paramString1, ""); } public boolean getbooleanValue(String paramString1) { return sp.getBoolean(paramString1, false); }}/* * Location: C:\Users\Administrator\Desktop\classes_dex2jar.jar Qualified Name: * com.syc.sycmoblieframe.util.SharedPreferencesHelper JD-Core Version: 0.6.2 */
/** * Cobub Razor * * An open source analytics android sdk for mobile applications * * @package Cobub Razor * @author WBTECH Dev Team * @copyright Copyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd. * @license http://www.cobub.com/products/cobub-razor/license * @link http://www.cobub.com/products/cobub-razor/ * @since Version 0.1 * @filesource */package com.ada.utils;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.UUID;import android.app.ActivityManager;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.hardware.SensorManager;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.net.Uri;import android.provider.Settings;import android.telephony.TelephonyManager;import android.util.Log;public class CommonUtil { /** * checkPermissions * * @param context * @param permission * @return true or false */ public static boolean checkPermissions(Context context, String permission) { PackageManager localPackageManager = context.getPackageManager(); return localPackageManager.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED; } /** * Determine the current networking is WIFI * * @param context * @return */ public static boolean CurrentNoteworkTypeIsWIFI(Context context) { ConnectivityManager connectionManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); return connectionManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; } /** * Judge wifi is available * * @param inContext * @return */ public static boolean isWiFiActive(Context inContext) { if (checkPermissions(inContext, "android.permission.ACCESS_WIFI_STATE")) { Context context = inContext.getApplicationContext(); ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) { return true; } } } } return false; } else { if (UmsConstants.DebugMode) { Log.e("lost permission", "lost--->android.permission.ACCESS_WIFI_STATE"); } return false; } } /** * Testing equipment networking and networking WIFI * * @param context * @return true or false */ public static boolean isNetworkAvailable(Context context) { if (checkPermissions(context, "android.permission.INTERNET")) { ConnectivityManager cManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cManager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { return true; } else { if (UmsConstants.DebugMode) { Log.e("error", "Network error"); } return false; } } else { if (UmsConstants.DebugMode) { Log.e(" lost permission", "lost----> android.permission.INTERNET"); } return false; } } /** * Get the current time format yyyy-MM-dd HH:mm:ss * * @return */ public static String getTime() { Date date = new Date(); SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); return localSimpleDateFormat.format(date); } /** * get APPKEY * * @param context * @return appkey */ public static String getAppKey(Context paramContext) { String umsAppkey; try { PackageManager localPackageManager = paramContext .getPackageManager(); ApplicationInfo localApplicationInfo = localPackageManager .getApplicationInfo(paramContext.getPackageName(), 128); if (localApplicationInfo != null) { String str = localApplicationInfo.metaData .getString("UMS_APPKEY"); if (str != null) { umsAppkey = str; return umsAppkey.toString(); } if (UmsConstants.DebugMode) Log.e("UmsAgent", "Could not read UMS_APPKEY meta-data from AndroidManifest.xml."); } } catch (Exception localException) { if (UmsConstants.DebugMode) { Log.e("UmsAgent", "Could not read UMS_APPKEY meta-data from AndroidManifest.xml."); localException.printStackTrace(); } } return null; } /** * get currnet activity's name * * @param context * @return */ public static String getActivityName(Context context) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); if (checkPermissions(context, "android.permission.GET_TASKS")) { ComponentName cn = am.getRunningTasks(1).get(0).topActivity; return cn.getShortClassName(); } else { if (UmsConstants.DebugMode) { Log.e("lost permission", "android.permission.GET_TASKS"); } return null; } } /** * get PackageName * * @param context * @return */ public static String getPackageName(Context context) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); if (checkPermissions(context, "android.permission.GET_TASKS")) { ComponentName cn = am.getRunningTasks(1).get(0).topActivity; return cn.getPackageName(); } else { if (UmsConstants.DebugMode) { Log.e("lost permission", "android.permission.GET_TASKS"); } return null; } } /** * get OS number * * @param context * @return */ public static String getOsVersion(Context context) { String osVersion = ""; if (checkPhoneState(context)) { osVersion = android.os.Build.VERSION.RELEASE; if (UmsConstants.DebugMode) { printLog("android_osVersion", "OsVerson" + osVersion); } return osVersion; } else { if (UmsConstants.DebugMode) { Log.e("android_osVersion", "OsVerson get failed"); } return null; } } /** * get deviceid * * @param context * add* @return */ public static String getDeviceID(Context context) { if (checkPermissions(context, "android.permission.READ_PHONE_STATE")) { String deviceId = ""; if (checkPhoneState(context)) { TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); deviceId = tm.getDeviceId(); } if (deviceId != null) { if (UmsConstants.DebugMode) { printLog("commonUtil", "deviceId:" + deviceId); } return deviceId; } else { if (UmsConstants.DebugMode) { Log.e("commonUtil", "deviceId is null"); } return null; } } else { if (UmsConstants.DebugMode) { Log.e("lost permissioin", "lost----->android.permission.READ_PHONE_STATE"); } return ""; } } /** * 鑾峰彇璁剧疆鐨勫敮涓€id 濡傛灉娌℃湁闅忔満浜х敓涓€涓插瓧绗︼紝绋嬪簭涓嶅嵏杞戒竴鐩村瓨鍦? * @param context * @return */ public static String getAndroidID(Context context) { String androidId = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID); Log.i("ada", "" + androidId); if (androidId == null) { SharedPreferences sharedPreferences = context.getSharedPreferences( "setting", Context.MODE_PRIVATE); String id = sharedPreferences.getString("id",null); if(id==null){ id=UUID.randomUUID().toString().replace("-", "").toLowerCase(); sharedPreferences.edit().putString("id", id).commit(); } androidId=id; } return androidId; } /** * check phone _state is readied ; * * @param context * @return */ public static boolean checkPhoneState(Context context) { PackageManager packageManager = context.getPackageManager(); if (packageManager .checkPermission("android.permission.READ_PHONE_STATE", context.getPackageName()) != 0) { return false; } return true; } /** * get sdk number * * @param paramContext * @return */ public static String getSdkVersion(Context paramContext) { String osVersion = ""; if (!checkPhoneState(paramContext)) { osVersion = android.os.Build.VERSION.RELEASE; if (UmsConstants.DebugMode) { Log.e("android_osVersion", "OsVerson" + osVersion); } return osVersion; } else { if (UmsConstants.DebugMode) { Log.e("android_osVersion", "OsVerson get failed"); } return null; } } /** * Get the version number of the current program * * @param context * @return */ public static String getCurVersion(Context context) { String curversion = ""; try { // ---get the package info--- PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); curversion = pi.versionName; if (curversion == null || curversion.length() <= 0) { return ""; } } catch (Exception e) { if (UmsConstants.DebugMode) { Log.e("VersionInfo", "Exception", e); } } return curversion; } /** * Get the current send model * * @param context * @return */ public static int getReportPolicyMode(Context context) { String str = context.getPackageName(); SharedPreferences localSharedPreferences = context .getSharedPreferences("ums_agent_online_setting_" + str, 0); int type = localSharedPreferences.getInt("ums_local_report_policy", 0); return type; } /** * To determine whether it contains a gyroscope * * @return */ public static boolean isHaveGravity(Context context) { SensorManager manager = (SensorManager) context .getSystemService(Context.SENSOR_SERVICE); if (manager == null) { return false; } return true; } /** * Get the current networking * * @param context * @return WIFI or MOBILE */ public static String getNetworkType(Context context) { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int type = manager.getNetworkType(); String typeString = "UNKOWN"; if (type == TelephonyManager.NETWORK_TYPE_CDMA) { typeString = "CDMA"; } if (type == TelephonyManager.NETWORK_TYPE_EDGE) { typeString = "EDGE"; } if (type == TelephonyManager.NETWORK_TYPE_EVDO_0) { typeString = "EVDO_0"; } if (type == TelephonyManager.NETWORK_TYPE_EVDO_A) { typeString = "EVDO_A"; } if (type == TelephonyManager.NETWORK_TYPE_GPRS) { typeString = "GPRS"; } if (type == TelephonyManager.NETWORK_TYPE_HSDPA) { typeString = "HSDPA"; } if (type == TelephonyManager.NETWORK_TYPE_HSPA) { typeString = "HSPA"; } if (type == TelephonyManager.NETWORK_TYPE_HSUPA) { typeString = "HSUPA"; } if (type == TelephonyManager.NETWORK_TYPE_UMTS) { typeString = "UMTS"; } if (type == TelephonyManager.NETWORK_TYPE_UNKNOWN) { typeString = "UNKOWN"; } return typeString; } /** * Determine the current network type * * @param context * @return */ public static boolean isNetworkTypeWifi(Context context) { // TODO Auto-generated method stub if (checkPermissions(context, "android.permission.INTERNET")) { ConnectivityManager cManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cManager.getActiveNetworkInfo(); if (info != null && info.isAvailable() && info.getTypeName().equals("WIFI")) { return true; } else { if (UmsConstants.DebugMode) { Log.e("error", "Network not wifi"); } return false; } } else { if (UmsConstants.DebugMode) { Log.e(" lost permission", "lost----> android.permission.INTERNET"); } return false; } } /** * Get the current application version number * * @param context * @return */ public static String getVersion(Context context) { String versionName = ""; try { PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); versionName = pi.versionName; if (versionName == null || versionName.length() <= 0) { return ""; } } catch (Exception e) { if (UmsConstants.DebugMode) { Log.e("UmsAgent", "Exception", e); } } return versionName; } /** * Set the output log * * @param tag * @param log */ public static void printLog(String tag, String log) { if (UmsConstants.DebugMode == true) { Log.d(tag, log); } } /** * install apk * * @param url */ public static void installApk(Context context, File apkfile) { if (!apkfile.exists()) { return; } Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); context.startActivity(i); } /** * 鍒ゆ柇鎵嬫満鏄惁瀹夎浜嗘煇涓▼搴忥紝濡傛灉瀹夎浜嗘绋嬪簭锛屽垹闄ゅ畠銆? * * @param context * @param name */ public static void uninstallSoftware(Context context, String name) { final PackageManager packageManager = context.getPackageManager(); try { PackageInfo pInfo = packageManager.getPackageInfo(name, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); if (pInfo != null) { // 鍒犻櫎杞欢 Uri uri = Uri.parse("package:" + name); Intent intent = new Intent(Intent.ACTION_DELETE, uri); context.startActivity(intent); } } catch (NameNotFoundException e) { e.printStackTrace(); } } /** * 鍒ゆ柇鎵嬫満鏄惁瀹夎浜嗘煇涓▼搴忥紝濡傛灉瀹夎浜嗘绋嬪簭锛屽垹闄ゅ畠銆? * * @param context * @param name */ public static boolean isinstallSoftware(Context context, String name) { boolean isinstall = false; final PackageManager packageManager = context.getPackageManager(); try { PackageInfo pInfo = packageManager.getPackageInfo(name, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); if (pInfo != null) { isinstall = true; } } catch (NameNotFoundException e) { e.printStackTrace(); } return isinstall; } /** * 绯荤粺涓墍鏈夊畨瑁呰繃鐨勮蒋浠? * * @param context * @param name */ public static void isinstallSoftware1(Context context, String name) { final PackageManager packageManager = context.getPackageManager();// 鑾峰彇packagemanager List pinfo = packageManager.getInstalledPackages(0);// 鑾峰彇鎵€鏈夊凡瀹夎绋嬪簭鐨勫寘淇℃伅 if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { String packName = pinfo.get(i).packageName; Log.d("info", "-->" + packName); } } } /** * 鍒ゆ柇绋嬪簭鏄惁瀹夎鍒癝D鍗′笂 * * @param context * @param name */ public static void isInstallOnSd(Context context, String name) { PackageManager pm = context.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(name, 0); if ((appInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { // App on sdcard Log.d("info", "app on sd"); } } catch (NameNotFoundException e) { e.printStackTrace(); } }}
package cn.trinea.android.common.util;import java.io.File;import java.util.List;import android.app.ActivityManager;import android.app.ActivityManager.RunningTaskInfo;import android.content.Context;import android.content.Intent;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.net.Uri;import android.os.Build;import android.provider.Settings;import android.util.Log;import cn.trinea.android.common.util.ShellUtils.CommandResult;/** * PackageUtils *
- * Install package *
- {@link PackageUtils#installNormal(Context, String)} *
- {@link PackageUtils#installSilent(Context, String)} *
- {@link PackageUtils#install(Context, String)} *
- * Uninstall package *
- {@link PackageUtils#uninstallNormal(Context, String)} *
- {@link PackageUtils#uninstallSilent(Context, String)} *
- {@link PackageUtils#uninstall(Context, String)} *
- * Is system application *
- {@link PackageUtils#isSystemApplication(Context)} *
- {@link PackageUtils#isSystemApplication(Context, String)} *
- {@link PackageUtils#isSystemApplication(PackageManager, String)} *
- * Others *
- {@link PackageUtils#getInstallLocation()} get system install location *
- {@link PackageUtils#isTopActivity(Context, String)} whether the app whost package's name is packageName is on the * top of the stack *
- {@link PackageUtils#startInstalledAppDetails(Context, String)} start InstalledAppDetails Activity *
- *
- if system application or rooted, see {@link #installSilent(Context, String)} *
- else see {@link #installNormal(Context, String)} *
- * Attentions: *
- Don't call this on the ui thread, it may costs some times. *
- You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root * permission, if you are system app. *
- Default pm install params is "-r". *
- * Attentions: *
- Don't call this on the ui thread, it may costs some times. *
- You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root * permission, if you are system app. *
- *
- if system application or rooted, see {@link #uninstallSilent(Context, String)} *
- else see {@link #uninstallNormal(Context, String)} *
- * Attentions: *
- Don't call this on the ui thread, it may costs some times. *
- You should add android.permission.DELETE_PACKAGES in manifest, so no need to request root * permission, if you are system app. *
- *
- {@link #DELETE_SUCCEEDED} means uninstall success *
- {@link #DELETE_FAILED_INTERNAL_ERROR} means internal error *
- {@link #DELETE_FAILED_INVALID_PACKAGE} means package name error *
- {@link #DELETE_FAILED_PERMISSION_DENIED} means permission denied */ public static int uninstallSilent(Context context, String packageName, boolean isKeepData) { if (packageName == null || packageName.length() == 0) { return DELETE_FAILED_INVALID_PACKAGE; } /** * if context is system app, don't need root permission, but should add
- if packageManager is null, return false *
- if package name is null or is empty, return false *
- if package name not exit, return false *
- if package name exit, but not system app, return false *
- else return true *
- You should add android.permission.GET_TASKS in manifest *
- *
- * Attentions: *
package cn.trinea.android.common.util;import java.util.Random;/** * Random Utils *
- * Shuffling algorithm *
- {@link #shuffle(Object[])} Shuffling algorithm, Randomly permutes the specified array using a default source of * randomness *
- {@link #shuffle(Object[], int)} Shuffling algorithm, Randomly permutes the specified array *
- {@link #shuffle(int[])} Shuffling algorithm, Randomly permutes the specified int array using a default source of * randomness *
- {@link #shuffle(int[], int)} Shuffling algorithm, Randomly permutes the specified int array *
- * get random int *
- {@link #getRandom(int)} get random int between 0 and max *
- {@link #getRandom(int, int)} get random int between min and max *
- * get random numbers or letters *
- {@link #getRandomCapitalLetters(int)} get a fixed-length random string, its a mixture of uppercase letters *
- {@link #getRandomLetters(int)} get a fixed-length random string, its a mixture of uppercase and lowercase letters * *
- {@link #getRandomLowerCaseLetters(int)} get a fixed-length random string, its a mixture of lowercase letters *
- {@link #getRandomNumbers(int)} get a fixed-length random string, its a mixture of numbers *
- {@link #getRandomNumbersAndLetters(int)} get a fixed-length random string, its a mixture of uppercase, lowercase * letters and numbers *
- {@link #getRandom(String, int)} get a fixed-length random string, its a mixture of chars in source *
- {@link #getRandom(char[], int)} get a fixed-length random string, its a mixture of chars in sourceChar *
- *
- if source is null or empty, return null *
- else see {@link RandomUtils#getRandom(char[] sourceChar, int length)} *
- *
- if sourceChar is null or empty, return null *
- if length less than 0, return null *
- *
- if max <= 0, return 0 *
- else return random int between 0 and max *
- *
- if min > max, return 0 *
- if min == max, return min *
- else return random int between min and max *
package com.ada.utils;/* * Copyright (C) 2010 Michael Pardo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.util.ArrayList;import java.util.List;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager.NameNotFoundException;import android.os.Build;import com.ada.androidutils.BuildConfig;public class Log { private static final int DUMP_LENGTH = 4000; public static final int LEVEL_VERBOSE = 0; public static final int LEVEL_DEBUG = 1; public static final int LEVEL_INFO = 2; public static final int LEVEL_WARNING = 3; public static final int LEVEL_ERROR = 4; public static final int LEVEL_NONE = 5; private static String mTag = "AndroidUtils"; private static boolean mEnabled = false; private static String mRemoteUrl; private static String mPackageName; private static String mPackageVersion; public static void initialize(Context context) { initialize(context, null, null, BuildConfig.DEBUG); } public static void initialize(Context context, String tag, String url, boolean enabled) { if (tag != null) { mTag = tag; } mEnabled = enabled; mRemoteUrl = url; if (context != null) { try { PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); mPackageName = pi.packageName; mPackageVersion = pi.versionName; if (tag == null && pi.applicationInfo.labelRes > 0) { mTag = context.getString(pi.applicationInfo.labelRes); } } catch (NameNotFoundException e) { } } } public static int v(String msg) { if (mEnabled) { return android.util.Log.v(mTag, msg); } return 0; } public static int v(String tag, String msg) { if (mEnabled) { return android.util.Log.v(tag, msg); } return 0; } public static int v(String msg, Throwable tr) { if (mEnabled) { return android.util.Log.v(mTag, msg, tr); } return 0; } public static int v(String tag, String msg, Throwable tr) { if (mEnabled) { return android.util.Log.v(tag, msg, tr); } return 0; } public static int d(String msg) { if (mEnabled) { return android.util.Log.d(mTag, msg); } return 0; } public static int d(String tag, String msg) { if (mEnabled) { return android.util.Log.d(tag, msg); } return 0; } public static int d(String msg, Throwable tr) { if (mEnabled) { return android.util.Log.d(mTag, msg, tr); } return 0; } public static int d(String tag, String msg, Throwable tr) { if (mEnabled) { return android.util.Log.d(tag, msg, tr); } return 0; } public static int i(String msg) { if (mEnabled) { return android.util.Log.i(mTag, msg); } return 0; } public static int i(String tag, String msg) { if (mEnabled) { return android.util.Log.i(tag, msg); } return 0; } public static int i(String msg, Throwable tr) { if (mEnabled) { return android.util.Log.i(mTag, msg, tr); } return 0; } public static int i(String tag, String msg, Throwable tr) { if (mEnabled) { return android.util.Log.i(tag, msg, tr); } return 0; } public static int w(String msg) { if (mEnabled) { return android.util.Log.w(mTag, msg); } return 0; } public static int w(String tag, String msg) { if (mEnabled) { return android.util.Log.w(tag, msg); } return 0; } public static int w(String msg, Throwable tr) { if (mEnabled) { return android.util.Log.w(mTag, msg, tr); } return 0; } public static int w(String tag, String msg, Throwable tr) { if (mEnabled) { return android.util.Log.w(tag, msg, tr); } return 0; } public static int e(String msg) { if (mEnabled) { return android.util.Log.e(mTag, msg); } return 0; } public static int e(String tag, String msg) { if (mEnabled) { return android.util.Log.e(tag, msg); } return 0; } public static int e(String msg, Throwable tr) { if (mEnabled) { return android.util.Log.e(mTag, msg, tr); } return 0; } public static int e(String tag, String msg, Throwable tr) { if (mEnabled) { return android.util.Log.e(tag, msg, tr); } return 0; } public static int t(String msg, Object... args) { if (mEnabled) { return android.util.Log.v("test", String.format(msg, args)); } return 0; } public static void remote(final String msg) { if (mRemoteUrl == null) { return; } new Thread(new Runnable() { @Override public void run() { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(mRemoteUrl); Listparams = new ArrayList (); params.add(new BasicNameValuePair("package_name", mPackageName)); params.add(new BasicNameValuePair("package_version", mPackageVersion)); params.add(new BasicNameValuePair("phone_model", Build.MODEL)); params.add(new BasicNameValuePair("sdk_version", Build.VERSION.RELEASE)); params.add(new BasicNameValuePair("message", msg)); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpClient.execute(httpPost); } catch (Exception e) { } } }).start(); } public static void dump(String longMsg) { dump(mTag, longMsg, LEVEL_INFO); } public static void dump(String longMsg, int level) { dump(mTag, longMsg, level); } public static void dump(String tag, String longMsg) { dump(tag, longMsg, LEVEL_INFO); } public static void dump(String tag, String longMsg, int level) { int len = longMsg.length(); String curr; for (int a = 0; a < len; a += DUMP_LENGTH) { if (a + DUMP_LENGTH < len) { curr = longMsg.substring(a, a + DUMP_LENGTH); } else { curr = longMsg.substring(a); } switch (level) { case LEVEL_ERROR: Log.e(tag, curr); break; case LEVEL_WARNING: Log.w(tag, curr); break; case LEVEL_INFO: Log.i(tag, curr); break; case LEVEL_DEBUG: Log.d(tag, curr); break; case LEVEL_VERBOSE: default: Log.v(tag, curr); break; } } }}
转载地址:https://codegg.blog.csdn.net/article/details/50110819 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月15日 04时05分01秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
在STM32价格疯长下,哪些国产32可以替代?
2019-04-29
半导体芯片原厂涨价及调价声明新增了这些!
2019-04-29
为什么你学C++这么难?
2019-04-29
无人机破巡检难题,秒变电网卫士
2019-04-29
五年,我成为了一名嵌入式工程师。
2019-04-29
2020年电赛题目,命题专家们怎么看?
2019-04-29
PCB元器件摆放不可忽略的10个技巧
2019-04-29
掌握AI核心技术没有秘籍,能自己创造就是王道
2019-04-29
大学老师的月薪多少?实话实说:4万多一点……
2019-04-29
2020年电赛题目,命题专家权威解析!
2019-04-29
写论文,这个神器不能少!
2019-04-29
现在做硬件工程师还有前途吗?
2019-04-29
华为被超越!这家公司成中国最大智能手机制造商,不是小米!
2019-04-29
芯片为什么持续缺货?
2019-04-29
美国无人机在火星首飞成功,创造历史,3米飞行高度悬停30秒
2019-04-29
缺货涨价很久的MCU的国产和国外厂家汇总!(80家)
2019-04-29
华为重磅反击,鸿蒙来了!
2019-04-29
常用电子接口大全,遇到不认识的,就翻出来对照辨认!
2019-04-29
芯片IC附近为啥要放0.1uF的电容?
2019-04-29
电赛 | 19年全国一等奖,北航学子回忆录。
2019-04-29