分享自己的一些android util 源文件
来源:互联网 发布:淘宝乐高回力车 编辑:程序博客网 时间:2024/06/11 16:08
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
包含解压和压缩的接口。解决网上解压缺失文件的问题。
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(Collection<File> resFileList, 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<File> 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<File> upZipSelectedFile(File zipFile,String folderPath, String nameContains) throws ZipException,IOException {ArrayList<File> fileList = new ArrayList<File>();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<String> entryNames = new ArrayList<String>();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 {// Loggingprivate 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 itreturn 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 itreturn 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 blocke.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 blocke.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 <a href="http://www.trinea.cn" target="_blank">Trinea</a> 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 <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getLong(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getLong(String)}</li> * </ul> */ public static Long getLong(JSONObject jsonObject, String key, Long defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getLong(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Long from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getLong(JSONObject, String, JSONObject)}</li> * </ul> */ public static Long getLong(String jsonData, String key, Long defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getLong(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getLong(JSONObject, String, Long) */ public static long getLong(JSONObject jsonObject, String key, long defaultValue) { return getLong(jsonObject, key, (Long)defaultValue); } /** * @param jsonData * @param key * @param defaultValue * @return * @see JSONUtils#getLong(String, String, Long) */ public static long getLong(String jsonData, String key, long defaultValue) { return getLong(jsonData, key, (Long)defaultValue); } /** * get Int from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getInt(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getInt(String)}</li> * </ul> */ public static Integer getInt(JSONObject jsonObject, String key, Integer defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getInt(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Int from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getInt(JSONObject, String, JSONObject)}</li> * </ul> */ public static Integer getInt(String jsonData, String key, Integer defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getInt(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getInt(JSONObject, String, Integer) */ public static int getInt(JSONObject jsonObject, String key, int defaultValue) { return getInt(jsonObject, key, (Integer)defaultValue); } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getInt(String, String, Integer) */ public static int getInt(String jsonData, String key, int defaultValue) { return getInt(jsonData, key, (Integer)defaultValue); } /** * get Double from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getDouble(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getDouble(String)}</li> * </ul> */ public static Double getDouble(JSONObject jsonObject, String key, Double defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getDouble(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Double from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getDouble(JSONObject, String, JSONObject)}</li> * </ul> */ public static Double getDouble(String jsonData, String key, Double defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getDouble(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getDouble(JSONObject, String, Double) */ public static double getDouble(JSONObject jsonObject, String key, double defaultValue) { return getDouble(jsonObject, key, (Double)defaultValue); } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getDouble(String, String, Double) */ public static double getDouble(String jsonData, String key, double defaultValue) { return getDouble(jsonData, key, (Double)defaultValue); } /** * get String from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getString(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getString(String)}</li> * </ul> */ public static String getString(JSONObject jsonObject, String key, String defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getString(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get String from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getString(JSONObject, String, JSONObject)}</li> * </ul> */ public static String getString(String jsonData, String key, String defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getString(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get String from jsonObject * * @param jsonObject * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static String getStringCascade(JSONObject jsonObject, String defaultValue, String... keyArray) { if (jsonObject == null || ArrayUtils.isEmpty(keyArray)) { return defaultValue; } String data = jsonObject.toString(); for (String key : keyArray) { data = getStringCascade(data, key, defaultValue); if (data == null) { return defaultValue; } } return data; } /** * get String from jsonData * * @param jsonData * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonData is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static String getStringCascade(String jsonData, String defaultValue, String... keyArray) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } String data = jsonData; for (String key : keyArray) { data = getString(data, key, defaultValue); if (data == null) { return defaultValue; } } return data; } /** * get String array from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li> * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li> * <li>return string array</li> * </ul> */ public static String[] getStringArray(JSONObject jsonObject, String key, String[] defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { String[] value = new String[statusArray.length()]; for (int i = 0; i < statusArray.length(); i++) { value[i] = statusArray.getString(i); } return value; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; } /** * get String array from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getStringArray(JSONObject, String, JSONObject)}</li> * </ul> */ public static String[] getStringArray(String jsonData, String key, String[] defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getStringArray(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get String list from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li> * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li> * <li>return string array</li> * </ul> */ public static List<String> getStringList(JSONObject jsonObject, String key, List<String> defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { List<String> list = new ArrayList<String>(); 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 <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getStringList(JSONObject, String, List)}</li> * </ul> */ public static List<String> getStringList(String jsonData, String key, List<String> 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 <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getJSONObject(String)}</li> * </ul> */ public static JSONObject getJSONObject(JSONObject jsonObject, String key, JSONObject defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getJSONObject(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonData is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getJSONObject(JSONObject, String, JSONObject)}</li> * </ul> */ public static JSONObject getJSONObject(String jsonData, String key, JSONObject defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONObject(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonObject * * @param jsonObject * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static JSONObject getJSONObjectCascade(JSONObject jsonObject, JSONObject defaultValue, String... keyArray) { if (jsonObject == null || ArrayUtils.isEmpty(keyArray)) { return defaultValue; } JSONObject js = jsonObject; for (String key : keyArray) { js = getJSONObject(js, key, defaultValue); if (js == null) { return defaultValue; } } return js; } /** * get JSONObject from jsonData * * @param jsonData * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonData is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static JSONObject getJSONObjectCascade(String jsonData, JSONObject defaultValue, String... keyArray) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONObjectCascade(jsonObject, defaultValue, keyArray); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONArray from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getJSONArray(String)}</li> * </ul> */ public static JSONArray getJSONArray(JSONObject jsonObject, String key, JSONArray defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getJSONArray(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONArray from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getJSONArray(JSONObject, String, JSONObject)}</li> * </ul> */ public static JSONArray getJSONArray(String jsonData, String key, JSONArray defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONArray(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Boolean from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>return {@link JSONObject#getBoolean(String)}</li> * </ul> */ public static boolean getBoolean(JSONObject jsonObject, String key, Boolean defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getBoolean(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Boolean from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getBoolean(JSONObject, String, Boolean)}</li> * </ul> */ public static boolean getBoolean(String jsonData, String key, Boolean defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getBoolean(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get map from jsonObject. * * @param jsonObject key-value pairs json * @param key * @return <ul> * <li>if jsonObject is null, return null</li> * <li>return {@link JSONUtils#parseKeyAndValueToMap(String)}</li> * </ul> */ public static Map<String, String> 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 <ul> * <li>if jsonData is null, return null</li> * <li>if jsonData length is 0, return empty map</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return null</li> * <li>return {@link JSONUtils#getMap(JSONObject, String)}</li> * </ul> */ public static Map<String, String> getMap(String jsonData, String key) { if (jsonData == null) { return null; } if (jsonData.length() == 0) { return new HashMap<String, String>(); } 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 <ul> * <li>if sourceObj is null, return null</li> * <li>else parse entry by {@link MapUtils#putMapNotEmptyKey(Map, String, String)} one by one</li> * </ul> */ @SuppressWarnings("rawtypes") public static Map<String, String> parseKeyAndValueToMap(JSONObject sourceObj) { if (sourceObj == null) { return null; } Map<String, String> keyAndValueMap = new HashMap<String, String>(); 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 <ul> * <li>if source is null or source's length is 0, return empty map</li> * <li>if source {@link JSONObject#JSONObject(String)} exception, return null</li> * <li>return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)}</li> * </ul> */ public static Map<String, String> 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; } }}
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 * * @packageCobub Razor * @authorWBTECH Dev Team * @copyrightCopyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd. * @licensehttp://www.cobub.com/products/cobub-razor/license * @linkhttp://www.cobub.com/products/cobub-razor/ * @sinceVersion 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 <uses-permission android:name="READ_PHONE_STATE" /> * @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 stubif (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();// 鑾峰彇packagemanagerList<PackageInfo> 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 sdcardLog.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 * <ul> * <strong>Install package</strong> * <li>{@link PackageUtils#installNormal(Context, String)}</li> * <li>{@link PackageUtils#installSilent(Context, String)}</li> * <li>{@link PackageUtils#install(Context, String)}</li> * </ul> * <ul> * <strong>Uninstall package</strong> * <li>{@link PackageUtils#uninstallNormal(Context, String)}</li> * <li>{@link PackageUtils#uninstallSilent(Context, String)}</li> * <li>{@link PackageUtils#uninstall(Context, String)}</li> * </ul> * <ul> * <strong>Is system application</strong> * <li>{@link PackageUtils#isSystemApplication(Context)}</li> * <li>{@link PackageUtils#isSystemApplication(Context, String)}</li> * <li>{@link PackageUtils#isSystemApplication(PackageManager, String)}</li> * </ul> * <ul> * <strong>Others</strong> * <li>{@link PackageUtils#getInstallLocation()} get system install location</li> * <li>{@link PackageUtils#isTopActivity(Context, String)} whether the app whost package's name is packageName is on the * top of the stack</li> * <li>{@link PackageUtils#startInstalledAppDetails(Context, String)} start InstalledAppDetails Activity</li> * </ul> * * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-5-15 */public class PackageUtils { public static final String TAG = "PackageUtils"; private PackageUtils() { throw new AssertionError(); } /** * App installation location settings values, same to {@link #PackageHelper} */ public static final int APP_INSTALL_AUTO = 0; public static final int APP_INSTALL_INTERNAL = 1; public static final int APP_INSTALL_EXTERNAL = 2; /** * install according conditions * <ul> * <li>if system application or rooted, see {@link #installSilent(Context, String)}</li> * <li>else see {@link #installNormal(Context, String)}</li> * </ul> * * @param context * @param filePath * @return */ public static final int install(Context context, String filePath) { if (PackageUtils.isSystemApplication(context) || ShellUtils.checkRootPermission()) { return installSilent(context, filePath); } return installNormal(context, filePath) ? INSTALL_SUCCEEDED : INSTALL_FAILED_INVALID_URI; } /** * install package normal by system intent * * @param context * @param filePath file path of package * @return whether apk exist */ public static boolean installNormal(Context context, String filePath) { Intent i = new Intent(Intent.ACTION_VIEW); File file = new File(filePath); if (file == null || !file.exists() || !file.isFile() || file.length() <= 0) { return false; } i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); return true; } /** * install package silent by root * <ul> * <strong>Attentions:</strong> * <li>Don't call this on the ui thread, it may costs some times.</li> * <li>You should add <strong>android.permission.INSTALL_PACKAGES</strong> in manifest, so no need to request root * permission, if you are system app.</li> * <li>Default pm install params is "-r".</li> * </ul> * * @param context * @param filePath file path of package * @return {@link PackageUtils#INSTALL_SUCCEEDED} means install success, other means failed. details see * {@link PackageUtils}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_* * @see #installSilent(Context, String, String) */ public static int installSilent(Context context, String filePath) { return installSilent(context, filePath, " -r " + getInstallLocationParams()); } /** * install package silent by root * <ul> * <strong>Attentions:</strong> * <li>Don't call this on the ui thread, it may costs some times.</li> * <li>You should add <strong>android.permission.INSTALL_PACKAGES</strong> in manifest, so no need to request root * permission, if you are system app.</li> * </ul> * * @param context * @param filePath file path of package * @param pmParams pm install params * @return {@link PackageUtils#INSTALL_SUCCEEDED} means install success, other means failed. details see * {@link PackageUtils}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_* */ public static int installSilent(Context context, String filePath, String pmParams) { if (filePath == null || filePath.length() == 0) { return INSTALL_FAILED_INVALID_URI; } File file = new File(filePath); if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) { return INSTALL_FAILED_INVALID_URI; } /** * if context is system app, don't need root permission, but should add <uses-permission * android:name="android.permission.INSTALL_PACKAGES" /> 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 * <ul> * <li>if system application or rooted, see {@link #uninstallSilent(Context, String)}</li> * <li>else see {@link #uninstallNormal(Context, String)}</li> * </ul> * * @param context * @param packageName package name of app * @return whether package name is empty * @return */ public static final int uninstall(Context context, String packageName) { if (PackageUtils.isSystemApplication(context) || ShellUtils.checkRootPermission()) { return uninstallSilent(context, packageName); } return uninstallNormal(context, packageName) ? DELETE_SUCCEEDED : DELETE_FAILED_INVALID_PACKAGE; } /** * uninstall package normal by system intent * * @param context * @param packageName package name of app * @return whether package name is empty */ public static boolean uninstallNormal(Context context, String packageName) { if (packageName == null || packageName.length() == 0) { return false; } Intent i = new Intent(Intent.ACTION_DELETE, Uri.parse(new StringBuilder(32).append("package:") .append(packageName).toString())); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); return true; } /** * uninstall package and clear data of app silent by root * * @param context * @param packageName package name of app * @return * @see #uninstallSilent(Context, String, boolean) */ public static int uninstallSilent(Context context, String packageName) { return uninstallSilent(context, packageName, true); } /** * uninstall package silent by root * <ul> * <strong>Attentions:</strong> * <li>Don't call this on the ui thread, it may costs some times.</li> * <li>You should add <strong>android.permission.DELETE_PACKAGES</strong> in manifest, so no need to request root * permission, if you are system app.</li> * </ul> * * @param context file path of package * @param packageName package name of app * @param isKeepData whether keep the data and cache directories around after package removal * @return <ul> * <li>{@link #DELETE_SUCCEEDED} means uninstall success</li> * <li>{@link #DELETE_FAILED_INTERNAL_ERROR} means internal error</li> * <li>{@link #DELETE_FAILED_INVALID_PACKAGE} means package name error</li> * <li>{@link #DELETE_FAILED_PERMISSION_DENIED} means permission denied</li> */ 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 <uses-permission * android:name="android.permission.DELETE_PACKAGES" /> in mainfest **/ StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall") .append(isKeepData ? " -k " : " ").append(packageName.replace(" ", "\\ ")); CommandResult commandResult = ShellUtils.execCommand(command.toString(), !isSystemApplication(context), true); if (commandResult.successMsg != null && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) { return DELETE_SUCCEEDED; } Log.e(TAG, new StringBuilder().append("uninstallSilent successMsg:").append(commandResult.successMsg) .append(", ErrorMsg:").append(commandResult.errorMsg).toString()); if (commandResult.errorMsg == null) { return DELETE_FAILED_INTERNAL_ERROR; } if (commandResult.errorMsg.contains("Permission denied")) { return DELETE_FAILED_PERMISSION_DENIED; } return DELETE_FAILED_INTERNAL_ERROR; } /** * whether context is system application * * @param context * @return */ public static boolean isSystemApplication(Context context) { if (context == null) { return false; } return isSystemApplication(context, context.getPackageName()); } /** * whether packageName is system application * * @param context * @param packageName * @return */ public static boolean isSystemApplication(Context context, String packageName) { if (context == null) { return false; } return isSystemApplication(context.getPackageManager(), packageName); } /** * whether packageName is system application * * @param packageManager * @param packageName * @return <ul> * <li>if packageManager is null, return false</li> * <li>if package name is null or is empty, return false</li> * <li>if package name not exit, return false</li> * <li>if package name exit, but not system app, return false</li> * <li>else return true</li> * </ul> */ public static boolean isSystemApplication(PackageManager packageManager, String packageName) { if (packageManager == null || packageName == null || packageName.length() == 0) { return false; } try { ApplicationInfo app = packageManager.getApplicationInfo(packageName, 0); return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0); } catch (NameNotFoundException e) { e.printStackTrace(); } return false; } /** * whether the app whost package's name is packageName is on the top of the stack * <ul> * <strong>Attentions:</strong> * <li>You should add <strong>android.permission.GET_TASKS</strong> in manifest</li> * </ul> * * @param context * @param packageName * @return if params error or task stack is null, return null, otherwise retun whether the app is on the top of * stack */ public static Boolean isTopActivity(Context context, String packageName) { if (context == null || StringUtils.isEmpty(packageName)) { return null; } ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1); if (ListUtils.isEmpty(tasksInfo)) { return null; } try { return packageName.equals(tasksInfo.get(0).topActivity.getPackageName()); } catch (Exception e) { e.printStackTrace(); return false; } } /** * get app version code * * @param context * @return */ public static int getAppVersionCode(Context context) { if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { PackageInfo pi; try { pi = pm.getPackageInfo(context.getPackageName(), 0); if (pi != null) { return pi.versionCode; } } catch (NameNotFoundException e) { e.printStackTrace(); } } } return -1; } /** * get system install location<br/> * can be set by System Menu Setting->Storage->Prefered install location * * @return * @see {@link IPackageManager#getInstallLocation()} */ public static int getInstallLocation() { CommandResult commandResult = ShellUtils.execCommand( "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm get-install-location", false, true); if (commandResult.result == 0 && commandResult.successMsg != null && commandResult.successMsg.length() > 0) { try { int location = Integer.parseInt(commandResult.successMsg.substring(0, 1)); switch (location) { case APP_INSTALL_INTERNAL: return APP_INSTALL_INTERNAL; case APP_INSTALL_EXTERNAL: return APP_INSTALL_EXTERNAL; } } catch (NumberFormatException e) { e.printStackTrace(); Log.e(TAG, "pm get-install-location error"); } } return APP_INSTALL_AUTO; } /** * get params for pm install location * * @return */ private static String getInstallLocationParams() { int location = getInstallLocation(); switch (location) { case APP_INSTALL_INTERNAL: return "-f"; case APP_INSTALL_EXTERNAL: return "-s"; } return ""; } /** * start InstalledAppDetails Activity * * @param context * @param packageName */ public static void startInstalledAppDetails(Context context, String packageName) { Intent intent = new Intent(); int sdkVersion = Build.VERSION.SDK_INT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.fromParts("package", packageName, null)); } else { intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra((sdkVersion == Build.VERSION_CODES.FROYO ? "pkg" : "com.android.settings.ApplicationPkgName"), packageName); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } /** * Installation return code<br/> * install success. */ public static final int INSTALL_SUCCEEDED = 1; /** * Installation return code<br/> * the package is already installed. */ public static final int INSTALL_FAILED_ALREADY_EXISTS = -1; /** * Installation return code<br/> * the package archive file is invalid. */ public static final int INSTALL_FAILED_INVALID_APK = -2; /** * Installation return code<br/> * the URI passed in is invalid. */ public static final int INSTALL_FAILED_INVALID_URI = -3; /** * Installation return code<br/> * the package manager service found that the device didn't have enough storage space to install the app. */ public static final int INSTALL_FAILED_INSUFFICIENT_STORAGE = -4; /** * Installation return code<br/> * a package is already installed with the same name. */ public static final int INSTALL_FAILED_DUPLICATE_PACKAGE = -5; /** * Installation return code<br/> * the requested shared user does not exist. */ public static final int INSTALL_FAILED_NO_SHARED_USER = -6; /** * Installation return code<br/> * a previously installed package of the same name has a different signature than the new package (and the old * package's data was not removed). */ public static final int INSTALL_FAILED_UPDATE_INCOMPATIBLE = -7; /** * Installation return code<br/> * the new package is requested a shared user which is already installed on the device and does not have matching * signature. */ public static final int INSTALL_FAILED_SHARED_USER_INCOMPATIBLE = -8; /** * Installation return code<br/> * the new package uses a shared library that is not available. */ public static final int INSTALL_FAILED_MISSING_SHARED_LIBRARY = -9; /** * Installation return code<br/> * the new package uses a shared library that is not available. */ public static final int INSTALL_FAILED_REPLACE_COULDNT_DELETE = -10; /** * Installation return code<br/> * the new package failed while optimizing and validating its dex files, either because there was not enough storage * or the validation failed. */ public static final int INSTALL_FAILED_DEXOPT = -11; /** * Installation return code<br/> * the new package failed because the current SDK version is older than that required by the package. */ public static final int INSTALL_FAILED_OLDER_SDK = -12; /** * Installation return code<br/> * the new package failed because it contains a content provider with the same authority as a provider already * installed in the system. */ public static final int INSTALL_FAILED_CONFLICTING_PROVIDER = -13; /** * Installation return code<br/> * the new package failed because the current SDK version is newer than that required by the package. */ public static final int INSTALL_FAILED_NEWER_SDK = -14; /** * Installation return code<br/> * the new package failed because it has specified that it is a test-only package and the caller has not supplied * the {@link #INSTALL_ALLOW_TEST} flag. */ public static final int INSTALL_FAILED_TEST_ONLY = -15; /** * Installation return code<br/> * the package being installed contains native code, but none that is compatible with the the device's CPU_ABI. */ public static final int INSTALL_FAILED_CPU_ABI_INCOMPATIBLE = -16; /** * Installation return code<br/> * the new package uses a feature that is not available. */ public static final int INSTALL_FAILED_MISSING_FEATURE = -17; /** * Installation return code<br/> * a secure container mount point couldn't be accessed on external media. */ public static final int INSTALL_FAILED_CONTAINER_ERROR = -18; /** * Installation return code<br/> * the new package couldn't be installed in the specified install location. */ public static final int INSTALL_FAILED_INVALID_INSTALL_LOCATION = -19; /** * Installation return code<br/> * the new package couldn't be installed in the specified install location because the media is not available. */ public static final int INSTALL_FAILED_MEDIA_UNAVAILABLE = -20; /** * Installation return code<br/> * the new package couldn't be installed because the verification timed out. */ public static final int INSTALL_FAILED_VERIFICATION_TIMEOUT = -21; /** * Installation return code<br/> * the new package couldn't be installed because the verification did not succeed. */ public static final int INSTALL_FAILED_VERIFICATION_FAILURE = -22; /** * Installation return code<br/> * the package changed from what the calling program expected. */ public static final int INSTALL_FAILED_PACKAGE_CHANGED = -23; /** * Installation return code<br/> * the new package is assigned a different UID than it previously held. */ public static final int INSTALL_FAILED_UID_CHANGED = -24; /** * Installation return code<br/> * if the parser was given a path that is not a file, or does not end with the expected '.apk' extension. */ public static final int INSTALL_PARSE_FAILED_NOT_APK = -100; /** * Installation return code<br/> * if the parser was unable to retrieve the AndroidManifest.xml file. */ public static final int INSTALL_PARSE_FAILED_BAD_MANIFEST = -101; /** * Installation return code<br/> * if the parser encountered an unexpected exception. */ public static final int INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION = -102; /** * Installation return code<br/> * if the parser did not find any certificates in the .apk. */ public static final int INSTALL_PARSE_FAILED_NO_CERTIFICATES = -103; /** * Installation return code<br/> * if the parser found inconsistent certificates on the files in the .apk. */ public static final int INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES = -104; /** * Installation return code<br/> * if the parser encountered a CertificateEncodingException in one of the files in the .apk. */ public static final int INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING = -105; /** * Installation return code<br/> * if the parser encountered a bad or missing package name in the manifest. */ public static final int INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME = -106; /** * Installation return code<br/> * if the parser encountered a bad shared user id name in the manifest. */ public static final int INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID = -107; /** * Installation return code<br/> * if the parser encountered some structural problem in the manifest. */ public static final int INSTALL_PARSE_FAILED_MANIFEST_MALFORMED = -108; /** * Installation return code<br/> * if the parser did not find any actionable tags (instrumentation or application) in the manifest. */ public static final int INSTALL_PARSE_FAILED_MANIFEST_EMPTY = -109; /** * Installation return code<br/> * if the system failed to install the package because of system issues. */ public static final int INSTALL_FAILED_INTERNAL_ERROR = -110; /** * Installation return code<br/> * other reason */ public static final int INSTALL_FAILED_OTHER = -1000000; /** * Uninstall return code<br/> * uninstall success. */ public static final int DELETE_SUCCEEDED = 1; /** * Uninstall return code<br/> * uninstall fail if the system failed to delete the package for an unspecified reason. */ public static final int DELETE_FAILED_INTERNAL_ERROR = -1; /** * Uninstall return code<br/> * uninstall fail if the system failed to delete the package because it is the active DevicePolicy manager. */ public static final int DELETE_FAILED_DEVICE_POLICY_MANAGER = -2; /** * Uninstall return code<br/> * uninstall fail if pcakge name is invalid */ public static final int DELETE_FAILED_INVALID_PACKAGE = -3; /** * Uninstall return code<br/> * uninstall fail if permission denied */ public static final int DELETE_FAILED_PERMISSION_DENIED = -4;}
package cn.trinea.android.common.util;import java.util.Random;/** * Random Utils * <ul> * Shuffling algorithm * <li>{@link #shuffle(Object[])} Shuffling algorithm, Randomly permutes the specified array using a default source of * randomness</li> * <li>{@link #shuffle(Object[], int)} Shuffling algorithm, Randomly permutes the specified array</li> * <li>{@link #shuffle(int[])} Shuffling algorithm, Randomly permutes the specified int array using a default source of * randomness</li> * <li>{@link #shuffle(int[], int)} Shuffling algorithm, Randomly permutes the specified int array</li> * </ul> * <ul> * get random int * <li>{@link #getRandom(int)} get random int between 0 and max</li> * <li>{@link #getRandom(int, int)} get random int between min and max</li> * </ul> * <ul> * get random numbers or letters * <li>{@link #getRandomCapitalLetters(int)} get a fixed-length random string, its a mixture of uppercase letters</li> * <li>{@link #getRandomLetters(int)} get a fixed-length random string, its a mixture of uppercase and lowercase letters * </li> * <li>{@link #getRandomLowerCaseLetters(int)} get a fixed-length random string, its a mixture of lowercase letters</li> * <li>{@link #getRandomNumbers(int)} get a fixed-length random string, its a mixture of numbers</li> * <li>{@link #getRandomNumbersAndLetters(int)} get a fixed-length random string, its a mixture of uppercase, lowercase * letters and numbers</li> * <li>{@link #getRandom(String, int)} get a fixed-length random string, its a mixture of chars in source</li> * <li>{@link #getRandom(char[], int)} get a fixed-length random string, its a mixture of chars in sourceChar</li> * </ul> * * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2012-5-12 */public class RandomUtils { public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String NUMBERS = "0123456789"; public static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; private RandomUtils() { throw new AssertionError(); } /** * get a fixed-length random string, its a mixture of uppercase, lowercase letters and numbers * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomNumbersAndLetters(int length) { return getRandom(NUMBERS_AND_LETTERS, length); } /** * get a fixed-length random string, its a mixture of numbers * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomNumbers(int length) { return getRandom(NUMBERS, length); } /** * get a fixed-length random string, its a mixture of uppercase and lowercase letters * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomLetters(int length) { return getRandom(LETTERS, length); } /** * get a fixed-length random string, its a mixture of uppercase letters * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomCapitalLetters(int length) { return getRandom(CAPITAL_LETTERS, length); } /** * get a fixed-length random string, its a mixture of lowercase letters * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomLowerCaseLetters(int length) { return getRandom(LOWER_CASE_LETTERS, length); } /** * get a fixed-length random string, its a mixture of chars in source * * @param source * @param length * @return <ul> * <li>if source is null or empty, return null</li> * <li>else see {@link RandomUtils#getRandom(char[] sourceChar, int length)}</li> * </ul> */ public static String getRandom(String source, int length) { return StringUtils.isEmpty(source) ? null : getRandom(source.toCharArray(), length); } /** * get a fixed-length random string, its a mixture of chars in sourceChar * * @param sourceChar * @param length * @return <ul> * <li>if sourceChar is null or empty, return null</li> * <li>if length less than 0, return null</li> * </ul> */ public static String getRandom(char[] sourceChar, int length) { if (sourceChar == null || sourceChar.length == 0 || length < 0) { return null; } StringBuilder str = new StringBuilder(length); Random random = new Random(); for (int i = 0; i < length; i++) { str.append(sourceChar[random.nextInt(sourceChar.length)]); } return str.toString(); } /** * get random int between 0 and max * * @param max * @return <ul> * <li>if max <= 0, return 0</li> * <li>else return random int between 0 and max</li> * </ul> */ public static int getRandom(int max) { return getRandom(0, max); } /** * get random int between min and max * * @param min * @param max * @return <ul> * <li>if min > max, return 0</li> * <li>if min == max, return min</li> * <li>else return random int between min and max</li> * </ul> */ public static int getRandom(int min, int max) { if (min > max) { return 0; } if (min == max) { return min; } return min + new Random().nextInt(max - min); } /** * Shuffling algorithm, Randomly permutes the specified array using a default source of randomness * * @param objArray * @return */ public static boolean shuffle(Object[] objArray) { if (objArray == null) { return false; } return shuffle(objArray, getRandom(objArray.length)); } /** * Shuffling algorithm, Randomly permutes the specified array * * @param objArray * @param shuffleCount * @return */ public static boolean shuffle(Object[] objArray, int shuffleCount) { int length; if (objArray == null || shuffleCount < 0 || (length = objArray.length) < shuffleCount) { return false; } for (int i = 1; i <= shuffleCount; i++) { int random = getRandom(length - i); Object temp = objArray[length - i]; objArray[length - i] = objArray[random]; objArray[random] = temp; } return true; } /** * Shuffling algorithm, Randomly permutes the specified int array using a default source of randomness * * @param intArray * @return */ public static int[] shuffle(int[] intArray) { if (intArray == null) { return null; } return shuffle(intArray, getRandom(intArray.length)); } /** * Shuffling algorithm, Randomly permutes the specified int array * * @param intArray * @param shuffleCount * @return */ public static int[] shuffle(int[] intArray, int shuffleCount) { int length; if (intArray == null || shuffleCount < 0 || (length = intArray.length) < shuffleCount) { return null; } int[] out = new int[shuffleCount]; for (int i = 1; i <= shuffleCount; i++) { int random = getRandom(length - i); out[i - 1] = intArray[random]; int temp = intArray[length - i]; intArray[length - i] = intArray[random]; intArray[random] = temp; } return out; }}
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() {@Overridepublic void run() {try {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(mRemoteUrl);List<NameValuePair> params = new ArrayList<NameValuePair>();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;}}}}
0 0
- 分享自己的一些android util 源文件
- Android Studio 自己常用的一些快捷键分享
- 分享一些自己的学习方法
- 分享一些自己的学习方法
- Android的一些分享
- 自己学android收集 的 一些 资料,便于自己查询,也分享给大家
- 自己常用的一些shell脚本分享
- 初来乍到,分享一些自己写的源码!
- 分享自己找工作的一些经历心得
- 分享自己在项目中对android文件系统的一些认识
- 分享一些本人自己收藏实用的Android OpenGL 书籍文档
- html5的Input Type : Number,分享自己的一些认识!
- android分享自己的app 和仅仅蓝牙分享
- 总结&分享一下自己最近的一些收获
- 分享一下自己的一些事情,呵呵,别见笑哦
- 分享一些自己的学习历程和学习方法
- 分享一些自己的学习历程和学习方法
- 分享一些自己的学习过程和学习方法
- mysql无法启动ERROR! MySQL is running but PID file could not be found ?
- hibernate一对多
- 《统计学习方法》学习笔记(三)——K近邻法
- NJUPT 微机 中断系统 日时钟中断之替换1CH实现字符串动态显示
- 如果你是IT技术人员,请思考这15个问题
- 分享自己的一些android util 源文件
- 1085. Perfect Sequence
- iOS9下App Store新应用提审攻略
- Android 蓝牙BLE (蓝牙成长之路)1
- 千万级到10亿+的疯涨,搜狗商业平台服务化体系实践之路
- samba简单配置
- ScrollView拉到尽头时出现阴影的解决方法
- Android Activity 启动
- [Javascript Practice] 数组扁平化处理