分享自己的一些android util 源文件
发布日期:2021-06-29 15:24:36 浏览次数:3 分类:技术文章

本文共 104690 字,大约阅读时间需要 348 分钟。

ZipUtils.java
包含解压和压缩的接口。解决网上解压缺失文件的问题。
FileUtils.java
文件操作,删除文件,目录,创建等接口
CopyRawtodata.java
复制Raw文件到data区域
CheckPWD.java
检测密码强度,5等级
ScreenUtils.java
获取屏幕宽高
Log.java
log相关
sharedPreferencesHelps.java
存储配置相关接口
commonUtil.java
常用的一些接口
packageutils.java
安装相关的工具
Randomutil.java
随机数
jsonUitl.java

解析接口

package com.lxm.tools;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Collection;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipException;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;/** * Java utils ʵ�ֵ�Zip���� *  * @author once */public class ZipUtils {	private static final int BUFF_SIZE = 512 * 1024; // 1M/2 Byte	/**	 * ����ѹ���ļ����У�	 * 	 * @param resFileList	 *            Ҫѹ�����ļ����У��б�	 * @param zipFile	 *            ���ɵ�ѹ���ļ�	 * @throws IOException	 *             ��ѹ�����̳���ʱ�׳�	 */	public static void zipFiles(Collection
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
resFileList, File zipFile, String comment) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.setComment(comment); zipout.close(); } /** * ��ѹ��һ���ļ� * * @param zipFile * ѹ���ļ� * @param folderPath * ��ѹ����Ŀ��Ŀ¼ * @throws IOException * ����ѹ�����̳���ʱ�׳� */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration
entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry) entries.nextElement()); InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = str = new String(str.getBytes(), "utf-8"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.flush(); out.close(); } } /** * ��ѹ�ļ��������������ֵ��ļ� * * @param zipFile * ѹ���ļ� * @param folderPath * Ŀ���ļ��� * @param nameContains * ������ļ�ƥ���� * @throws ZipException * ѹ����ʽ����ʱ�׳� * @throws IOException * IO����ʱ�׳� */ public static ArrayList
upZipSelectedFile(File zipFile, String folderPath, String nameContains) throws ZipException, IOException { ArrayList
fileList = new ArrayList
(); File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdir(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration
entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry) entries.nextElement()); if (entry.getName().contains(nameContains)) { InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes(), "utf-8"); // str.getBytes("GB2312"),"8859_1" ��� // str.getBytes("8859_1"),"GB2312" ���� File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); fileList.add(desFile); } } return fileList; } /** * ���ѹ���ļ����ļ��б� * * @param zipFile * ѹ���ļ� * @return ѹ���ļ����ļ����� * @throws ZipException * ѹ���ļ���ʽ����ʱ�׳� * @throws IOException * ����ѹ�����̳���ʱ�׳� */ public static int getEntriesNames(File zipFile) throws ZipException, IOException { int count=0; ArrayList
entryNames = new ArrayList
(); Enumeration
entries = getEntriesEnumeration(zipFile); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry) entries.nextElement()); count+=1; } return count; } /** * ���ѹ���ļ���ѹ���ļ�������ȡ�������� * * @param zipFile * ѹ���ļ� * @return ����һ��ѹ���ļ��б� * @throws ZipException * ѹ���ļ���ʽ����ʱ�׳� * @throws IOException * IO��������ʱ�׳� */ public static Enumeration
getEntriesEnumeration(File zipFile) throws ZipException, IOException { ZipFile zf = new ZipFile(zipFile); return zf.entries(); } /** * ȡ��ѹ���ļ������ע�� * * @param entry * ѹ���ļ����� * @return ѹ���ļ������ע�� * @throws UnsupportedEncodingException */ public static String getEntryComment(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getComment().getBytes("GB2312"), "8859_1"); } /** * ȡ��ѹ���ļ���������� * * @param entry * ѹ���ļ����� * @return ѹ���ļ���������� * @throws UnsupportedEncodingException */ public static String getEntryName(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getName().getBytes("GB2312"), "8859_1"); } /** * ѹ���ļ� * * @param resFile * ��Ҫѹ�����ļ����У� * @param zipout * ѹ����Ŀ���ļ� * @param rootpath * ѹ�����ļ�·�� * @throws FileNotFoundException * �Ҳ����ļ�ʱ�׳� * @throws IOException * ��ѹ�����̳���ʱ�׳� */ private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException { rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName(); rootpath = new String(rootpath.getBytes("8859_1"), "GB2312"); if (resFile.isDirectory()) { File[] fileList = resFile.listFiles(); for (File file : fileList) { zipFile(file, zipout, rootpath); } } else { byte buffer[] = new byte[BUFF_SIZE]; BufferedInputStream in = new BufferedInputStream( new FileInputStream(resFile), BUFF_SIZE); zipout.putNextEntry(new ZipEntry(rootpath)); int realLength; while ((realLength = in.read(buffer)) != -1) { zipout.write(buffer, 0, realLength); } in.close(); zipout.flush(); zipout.closeEntry(); } }}
package com.lxm.tools;import java.io.BufferedWriter;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.RandomAccessFile;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException;import android.util.Log;/** * File utilities */public class FileUtils {	// Logging	private static final String TAG = "FileUtils";	/**	 * It is not possible to instantiate this class	 */	private FileUtils() {	}	/**	 * Delete all the files in the specified folder and the folder itself.	 * 	 * @param dir	 *            The project path	 */	public static boolean deleteDir(File dir) {		if (dir.isDirectory()) {			final String[] children = dir.list();			for (int i = 0; i < children.length; i++) {				final File f = new File(dir, children[i]);				if (!deleteDir(f)) {					Log.e(TAG, "File cannot be deleted: " + f.getAbsolutePath());					return false;				}			}		}		// The directory is now empty so delete it		return dir.delete();	}	public static boolean deleteFile(File file) {		boolean del = false;		if (file.exists() && file.isFile()) {			del = file.delete();		}		// The directory is now empty so delete it		return del;	}	/**	 * Get the name of the file	 * 	 * @param filename	 *            The full path filename	 * @return The name of the file	 */	public static String getSimpleName(String filename) {		final int index = filename.lastIndexOf('/');		if (index == -1) {			return filename;		} else {			return filename.substring(index + 1);		}	}	/**	 * �ж������ַ�	 * 	 * @Title : FilterStr	 * @Type : FilterString	 * @date : 2014��2��28�� ����11:01:21	 * @Description : �ж������ַ�	 * @param str	 * @return	 * @throws PatternSyntaxException	 */	public static String FilterStr(String str) throws PatternSyntaxException {		/**		 * �����ַ�		 */		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~��@#��%����&*��������+|{}������������������������_]";		/**		 * Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaab");		 * boolean b = m.matches();		 */		Pattern pat = Pattern.compile(regEx);		Matcher mat = pat.matcher(str);		/**		 * �����滻���		 */		return mat.replaceAll("").trim();	}	public static void writestr(String flpath, String str) {		FileWriter fw = null;		BufferedWriter bw = null;		try {            File s = new File(flpath);            if(!s.exists()){            	s.createNewFile();            }			fw = new FileWriter(s, true);//			// ����FileWriter��������д���ַ���			bw = new BufferedWriter(fw); // ��������ļ������			bw.write(str); // д���ļ�			bw.newLine();			bw.flush(); // ˢ�¸����Ļ���			bw.close();			fw.close();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();			try {				if (bw != null) {					bw.close();				}				if (fw != null) {					fw.close();				}			} catch (IOException e1) {				// TODO Auto-generated catch block			}		}	}	public static void writelog(String flpath, String str) {		FileWriter fw = null;		BufferedWriter bw = null;		try {            File s = new File(flpath);            if(!s.exists()){            	s.mkdir();            }            String fn = flpath + "log.txt";            File s1 = new File(fn);            if(!s1.exists()){            	s1.createNewFile();            }			fw = new FileWriter(s1, true);//			// ����FileWriter��������д���ַ���			bw = new BufferedWriter(fw); // ��������ļ������			bw.write(str); // д���ļ�			bw.newLine();			bw.flush(); // ˢ�¸����Ļ���			bw.close();			fw.close();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();			try {				if (bw != null) {					bw.close();				}				if (fw != null) {					fw.close();				}			} catch (IOException e1) {				// TODO Auto-generated catch block			}		}	}		public static String readFileContentStr(String fullFilename) {		String readOutStr = null;		try {			DataInputStream dis = new DataInputStream(new FileInputStream(					fullFilename));			try {				long len = new File(fullFilename).length();				if (len > Integer.MAX_VALUE)					throw new IOException("File " + fullFilename							+ " too large, was " + len + " bytes.");				byte[] bytes = new byte[(int) len];				dis.readFully(bytes);				readOutStr = new String(bytes, "UTF-8");			} finally {				dis.close();			}			Log.d("readFileContentStr",					"Successfully to read out string from file " + fullFilename);		} catch (IOException e) {			readOutStr = null;			// e.printStackTrace();			Log.d("readFileContentStr", "Fail to read out string from file "					+ fullFilename);		}		return readOutStr;	}		public static void writeTxtToFile(String strcontent, String filePath, String fileName) {	    //�����ļ���֮���������ļ�����Ȼ�����	    makeFilePath(filePath, fileName);	    	    String strFilePath = filePath+fileName;	    // ÿ��д��ʱ��������д	    String strContent = strcontent + "\r\n";	    try {	        File file = new File(strFilePath);	        if (!file.exists()) {	            Log.d("TestFile", "Create the file:" + strFilePath);	            file.getParentFile().mkdirs();	            file.createNewFile();	        }	        RandomAccessFile raf = new RandomAccessFile(file, "rwd");	        raf.seek(file.length());	        raf.write(strContent.getBytes());	        raf.close();	    } catch (Exception e) {	        Log.e("TestFile", "Error on write File:" + e);	    }	}	 	// �����ļ�	public static File makeFilePath(String filePath, String fileName) {	    File file = null;	    makeRootDirectory(filePath);	    try {	        file = new File(filePath + fileName);	        if (!file.exists()) {	            file.createNewFile();	        }	    } catch (Exception e) {	        e.printStackTrace();	    }	    return file;	}	 	// �����ļ���	public static void makeRootDirectory(String filePath) {	    File file = null;	    try {	        file = new File(filePath);	        if (!file.exists()) {	            file.mkdir();	        }	    } catch (Exception e) {	        Log.i("error:", e+"");	    }	}}
package com.lxm.tools;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;final public class CopyRawtodata {	public static boolean CopyRawtodata(String path,String DbName,Context context,int id,boolean IsRawData)	{		boolean dbExist=checkDataBase(path,DbName);		if(!dbExist)		{        	try{        		copyDataBase(path,DbName,context,id,IsRawData);        	}catch(IOException e){        		throw new Error("Error copying database");        	}		}		return true;	}	private static boolean checkDataBase(String path,String DbName)	{    	SQLiteDatabase checkDB = null;    	try{    		String databaseFilename = path+"/"+DbName;    		checkDB =SQLiteDatabase.openDatabase(databaseFilename, null,    				SQLiteDatabase.OPEN_READONLY);    	}catch(SQLiteException e){    		    	}    	if(checkDB!=null){    		checkDB.close();    	}    	return checkDB !=null?true:false;	}	private static  void copyDataBase(String path,String DbName,Context context,int ResId,boolean IsRawData) throws IOException{	    	String databaseFilenames =path+"/"+DbName;	    	InputStream is;	    	File dir = new File(path+"/");	    	if(!dir.exists())//�ж��ļ����Ƿ���ڣ������ھ��½�һ��	    		dir.mkdir();	    	FileOutputStream os = null;	    	try{	    		os = new FileOutputStream(databaseFilenames);//�õ����ݿ��ļ���д����	    	}catch(FileNotFoundException e){	    		e.printStackTrace();	    	}	    	if(IsRawData)	    	{	    		 is = context.getResources().openRawResource(ResId);//�õ����ݿ��ļ���������	    	}	    	else	    	{	    		is = context.getResources().getAssets().open(DbName);//�õ����ݿ��ļ���������	    	}		        byte[] buffer = new byte[8192];	        int count = 0;	        try{	        		        	while((count=is.read(buffer))>0){	        		os.write(buffer, 0, count);	        		os.flush();	        	}	        }catch(IOException e){	        		        }	        try{	        	is.close();	        	os.close();	        }catch(IOException e){	        	e.printStackTrace();	        }	    }}
package com.lxm.tools;import java.util.regex.Matcher;import java.util.regex.Pattern;public class CheckPWD {	public static Safelevel checkPasswordStrength(String c) {		Safelevel d = Safelevel.WEAK;		if (isEmptyPassword(c)) {			return d;		}		if (isTooShort(c)) {			d = Safelevel.WEAK;		} else {			if (hasNum(c) && hasLetter(c) && hasSymbol(c)) {				d = Safelevel.SECURE;			} else {				if (hasNum(c) && hasLetter(c)) {					d = Safelevel.STRONG;				} else {					if (hasNum(c) && hasSymbol(c)) {						d = Safelevel.STRONG;					} else {						if (hasSymbol(c) && hasLetter(c)) {							d = Safelevel.STRONG;						} else {							if (isAllNum(c) || isAllLetter(c) || isAllSymbol(c)) {								d = Safelevel.WEAK;							}						}					}				}			}		}		return d;	}	public enum Safelevel {		WEAK, /* 弱 */		STRONG, /* 强 */		SECURE, /* 安全 */	}	public static boolean hasNum(String content) {		boolean flag = false;		Pattern p = Pattern.compile(".*\\d+.*");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean hasSymbol(String content) {		boolean flag = false;		Pattern p = Pattern.compile(".*[a-zA-Z0-9\\s<>;'\\\\]+.*");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean isAllSymbol(String content) {		boolean flag = false;		Pattern p = Pattern.compile("^[a-zA-Z0-9\\s<>;'\\\\]+$");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean hasSpace(String content) {		boolean flag = false;		Pattern p = Pattern.compile(".*\\s+.*");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean hasIllegalSymbol(String content) {		boolean flag = false;		Pattern p = Pattern.compile(".*[\\s<>;'\\\\].*");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean hasLetter(String content) {		boolean flag = false;		Pattern p = Pattern.compile(".*[a-zA-Z]+.*");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean isAllLetter(String content) {		boolean flag = false;		Pattern p = Pattern.compile("^[a-zA-Z]+$");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	private static boolean isEmptyPassword(String b) {		return (b == null || b.length() == 0);	}	private static boolean isTooShort(String b) {		return b.length() < 6;	}	public static boolean isAllNum(String content) {		boolean flag = false;		Pattern p = Pattern.compile("^\\d+$");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean hasRepeat6Chars(String content) {		boolean flag = false;		Pattern p = Pattern.compile(".*([0-9a-zA-Z])\\1{5}.*");		Matcher m = p.matcher(content);		if (m.matches())			flag = true;		return flag;	}	public static boolean hasIncrease6Chars(String g) {		if (g == null || g.length() < 6) {			return false;		}		char h = g.charAt(0);		char i = 1;		char j = 1;		for (j = 1; j < g.length(); j++) {			char f = g.charAt(j);			if (f == h + 1) {				i++;				if (i >= 6) {					return true;				}			} else {				i = 1;			}			h = f;		}		return false;	}	public static boolean hasDecrease6Chars(String g) {		if (g == null || g.length() < 6) {			return false;		}		char h = g.charAt(0);		char i = 1;		char j = 1;		for (j = 1; j < g.length(); j++) {			char f = g.charAt(j);			if (f == h - 1) {				i++;				if (i >= 6) {					return true;				}			} else {				i = 1;			}			h = f;		}		return false;	}	public static boolean hasAllIncreaseChars(String g) {		if (g == null) {			return false;		}		int i = g.length();		char h = g.charAt(0);		char j = 1;		char k = 1;		for (k = 1; k < g.length(); k++) {			char l = g.charAt(k);			if (l == h + 1) {				j++;				if (j >= i) {					return true;				}			} else {				j = 1;			}			h = l;		}		return false;	}	public static boolean hasAllDecreaseChars(String g) {		if (g == null) {			return false;		}		int i = g.length();		char h = g.charAt(0);		char j = 1;		char k = 1;		for (k = 1; k < i; k++) {			char l = g.charAt(k);			if (l == h - 1) {				j++;				if (j >= i) {					return true;				}			} else {				j = 1;			}			h = l;		}		return false;	}	public static boolean isAllSameChars(String content) {		if (content == null || content.length() < 2) {			return false;		}		char h = content.charAt(0);		char e = 1;		for (e = 1; e < content.length(); e++) {			char f = content.charAt(e);			if (f != h) {				return false;			}		}		return true;	}}
package com.lxm.tools;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Rect;import android.util.DisplayMetrics;import android.view.View;import android.view.WindowManager;/** * 获得屏幕相关的辅助类 *  *  *  */public class ScreenUtils {	private ScreenUtils() {		/* cannot be instantiated */		throw new UnsupportedOperationException("cannot be instantiated");	}	/**	 * 获得屏幕高度	 * 	 * @param context	 * @return	 */	public static int getScreenWidth(Context context) {		WindowManager wm = (WindowManager) context				.getSystemService(Context.WINDOW_SERVICE);		DisplayMetrics outMetrics = new DisplayMetrics();		wm.getDefaultDisplay().getMetrics(outMetrics);		return outMetrics.widthPixels;	}	/**	 * 获得屏幕宽度	 * 	 * @param context	 * @return	 */	public static int getScreenHeight(Context context) {		WindowManager wm = (WindowManager) context				.getSystemService(Context.WINDOW_SERVICE);		DisplayMetrics outMetrics = new DisplayMetrics();		wm.getDefaultDisplay().getMetrics(outMetrics);		return outMetrics.heightPixels;	}	/**	 * 获得状态栏的高度	 * 	 * @param context	 * @return	 */	public static int getStatusHeight(Context context) {		int statusHeight = -1;		try {			Class
clazz = Class.forName("com.android.internal.R$dimen"); Object object = clazz.newInstance(); int height = Integer.parseInt(clazz.getField("status_bar_height") .get(object).toString()); statusHeight = context.getResources().getDimensionPixelSize(height); } catch (Exception e) { e.printStackTrace(); } return statusHeight; } /** * 获取当前屏幕截图,包含状态栏 * * @param activity * @return */ public static Bitmap snapShotWithStatusBar(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bp = null; bp = Bitmap.createBitmap(bmp, 0, 0, width, height); view.destroyDrawingCache(); return bp; } /** * 获取当前屏幕截图,不包含状态栏 * * @param activity * @return */ public static Bitmap snapShotWithoutStatusBar(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bp = null; bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return bp; }}
package cn.trinea.android.common.util;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;/** * Json Utils *  * @author Trinea 2012-5-12 */public class JSONUtils {    public static boolean isPrintException = true;    private JSONUtils() {        throw new AssertionError();    }    /**     * get Long from jsonObject     *      * @param jsonObject     * @param key     * @param defaultValue     * @return 
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getLong(String)} exception, return defaultValue
  • *
  • return {@link JSONObject#getLong(String)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getLong(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getInt(String)} exception, return defaultValue
  • *
  • return {@link JSONObject#getInt(String)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getInt(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getDouble(String)} exception, return defaultValue
  • *
  • return {@link JSONObject#getDouble(String)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getDouble(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getString(String)} exception, return defaultValue
  • *
  • return {@link JSONObject#getString(String)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getString(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if keyArray is null or empty, return defaultValue
  • *
  • get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly
  • *
*/ 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
    *
  • if jsonData is null, return defaultValue
  • *
  • if keyArray is null or empty, return defaultValue
  • *
  • get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getJSONArray(String)} exception, return defaultValue
  • *
  • if {@link JSONArray#getString(int)} exception, return defaultValue
  • *
  • return string array
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getStringArray(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getJSONArray(String)} exception, return defaultValue
  • *
  • if {@link JSONArray#getString(int)} exception, return defaultValue
  • *
  • return string array
  • *
*/ public static List
getStringList(JSONObject jsonObject, String key, List
defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { List
list = new ArrayList
(); for (int i = 0; i < statusArray.length(); i++) { list.add(statusArray.getString(i)); } return list; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; } /** * get String list from jsonData * * @param jsonData * @param key * @param defaultValue * @return
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getStringList(JSONObject, String, List)}
  • *
*/ public static List
getStringList(String jsonData, String key, List
defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getStringList(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getJSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONObject#getJSONObject(String)}
  • *
*/ 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
    *
  • if jsonData is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getJSONObject(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if keyArray is null or empty, return defaultValue
  • *
  • get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly
  • *
*/ 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
    *
  • if jsonData is null, return defaultValue
  • *
  • if keyArray is null or empty, return defaultValue
  • *
  • get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • if {@link JSONObject#getJSONArray(String)} exception, return defaultValue
  • *
  • return {@link JSONObject#getJSONArray(String)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getJSONArray(JSONObject, String, JSONObject)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if key is null or empty, return defaultValue
  • *
  • return {@link JSONObject#getBoolean(String)}
  • *
*/ 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
    *
  • if jsonObject is null, return defaultValue
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue
  • *
  • return {@link JSONUtils#getBoolean(JSONObject, String, Boolean)}
  • *
*/ 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
    *
  • if jsonObject is null, return null
  • *
  • return {@link JSONUtils#parseKeyAndValueToMap(String)}
  • *
*/ public static Map
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
    *
  • if jsonData is null, return null
  • *
  • if jsonData length is 0, return empty map
  • *
  • if jsonData {@link JSONObject#JSONObject(String)} exception, return null
  • *
  • return {@link JSONUtils#getMap(JSONObject, String)}
  • *
*/ public static Map
getMap(String jsonData, String key) { if (jsonData == null) { return null; } if (jsonData.length() == 0) { return new HashMap
(); } try { JSONObject jsonObject = new JSONObject(jsonData); return getMap(jsonObject, key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return null; } } /** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param sourceObj key-value pairs json * @return
    *
  • if sourceObj is null, return null
  • *
  • else parse entry by {@link MapUtils#putMapNotEmptyKey(Map, String, String)} one by one
  • *
*/ @SuppressWarnings("rawtypes") public static Map
parseKeyAndValueToMap(JSONObject sourceObj) { if (sourceObj == null) { return null; } Map
keyAndValueMap = new HashMap
(); for (Iterator iter = sourceObj.keys(); iter.hasNext();) { String key = (String)iter.next(); MapUtils.putMapNotEmptyKey(keyAndValueMap, key, getString(sourceObj, key, "")); } return keyAndValueMap; } /** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param source key-value pairs json * @return
    *
  • if source is null or source's length is 0, return empty map
  • *
  • if source {@link JSONObject#JSONObject(String)} exception, return null
  • *
  • return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)}
  • *
*/ public static Map
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 * * @package		Cobub Razor * @author		WBTECH Dev Team * @copyright	Copyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd. * @license		http://www.cobub.com/products/cobub-razor/license * @link		http://www.cobub.com/products/cobub-razor/ * @since		Version 0.1 * @filesource */package com.ada.utils;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.UUID;import android.app.ActivityManager;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.hardware.SensorManager;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.net.Uri;import android.provider.Settings;import android.telephony.TelephonyManager;import android.util.Log;public class CommonUtil {	/**	 * checkPermissions	 * 	 * @param context	 * @param permission	 * @return true or false	 */	public static boolean checkPermissions(Context context, String permission) {		PackageManager localPackageManager = context.getPackageManager();		return localPackageManager.checkPermission(permission,				context.getPackageName()) == PackageManager.PERMISSION_GRANTED;	}	/**	 * Determine the current networking is WIFI	 * 	 * @param context	 * @return	 */	public static boolean CurrentNoteworkTypeIsWIFI(Context context) {		ConnectivityManager connectionManager = (ConnectivityManager) context				.getSystemService(Context.CONNECTIVITY_SERVICE);		return connectionManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;	}	/**	 * Judge wifi is available	 * 	 * @param inContext	 * @return	 */	public static boolean isWiFiActive(Context inContext) {		if (checkPermissions(inContext, "android.permission.ACCESS_WIFI_STATE")) {			Context context = inContext.getApplicationContext();			ConnectivityManager connectivity = (ConnectivityManager) context					.getSystemService(Context.CONNECTIVITY_SERVICE);			if (connectivity != null) {				NetworkInfo[] info = connectivity.getAllNetworkInfo();				if (info != null) {					for (int i = 0; i < info.length; i++) {						if (info[i].getTypeName().equals("WIFI")								&& info[i].isConnected()) {							return true;						}					}				}			}			return false;		} else {			if (UmsConstants.DebugMode) {				Log.e("lost permission",						"lost--->android.permission.ACCESS_WIFI_STATE");			}			return false;		}	}	/**	 * Testing equipment networking and networking WIFI	 * 	 * @param context	 * @return true or false	 */	public static boolean isNetworkAvailable(Context context) {		if (checkPermissions(context, "android.permission.INTERNET")) {			ConnectivityManager cManager = (ConnectivityManager) context					.getSystemService(Context.CONNECTIVITY_SERVICE);			NetworkInfo info = cManager.getActiveNetworkInfo();			if (info != null && info.isAvailable()) {				return true;			} else {				if (UmsConstants.DebugMode) {					Log.e("error", "Network error");				}				return false;			}		} else {			if (UmsConstants.DebugMode) {				Log.e(" lost  permission",						"lost----> android.permission.INTERNET");			}			return false;		}	}	/**	 * Get the current time format yyyy-MM-dd HH:mm:ss	 * 	 * @return	 */	public static String getTime() {		Date date = new Date();		SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(				"yyyy-MM-dd HH:mm:ss");		return localSimpleDateFormat.format(date);	}	/**	 * get APPKEY	 * 	 * @param context	 * @return appkey	 */	public static String getAppKey(Context paramContext) {		String umsAppkey;		try {			PackageManager localPackageManager = paramContext					.getPackageManager();			ApplicationInfo localApplicationInfo = localPackageManager					.getApplicationInfo(paramContext.getPackageName(), 128);			if (localApplicationInfo != null) {				String str = localApplicationInfo.metaData						.getString("UMS_APPKEY");				if (str != null) {					umsAppkey = str;					return umsAppkey.toString();				}				if (UmsConstants.DebugMode)					Log.e("UmsAgent",							"Could not read UMS_APPKEY meta-data from AndroidManifest.xml.");			}		} catch (Exception localException) {			if (UmsConstants.DebugMode) {				Log.e("UmsAgent",						"Could not read UMS_APPKEY meta-data from AndroidManifest.xml.");				localException.printStackTrace();			}		}		return null;	}	/**	 * get currnet activity's name	 * 	 * @param context	 * @return	 */	public static String getActivityName(Context context) {		ActivityManager am = (ActivityManager) context				.getSystemService(Context.ACTIVITY_SERVICE);		if (checkPermissions(context, "android.permission.GET_TASKS")) {			ComponentName cn = am.getRunningTasks(1).get(0).topActivity;			return cn.getShortClassName();		} else {			if (UmsConstants.DebugMode) {				Log.e("lost permission", "android.permission.GET_TASKS");			}			return null;		}	}	/**	 * get PackageName	 * 	 * @param context	 * @return	 */	public static String getPackageName(Context context) {		ActivityManager am = (ActivityManager) context				.getSystemService(Context.ACTIVITY_SERVICE);		if (checkPermissions(context, "android.permission.GET_TASKS")) {			ComponentName cn = am.getRunningTasks(1).get(0).topActivity;			return cn.getPackageName();		} else {			if (UmsConstants.DebugMode) {				Log.e("lost permission", "android.permission.GET_TASKS");			}			return null;		}	}	/**	 * get OS number	 * 	 * @param context	 * @return	 */	public static String getOsVersion(Context context) {		String osVersion = "";		if (checkPhoneState(context)) {			osVersion = android.os.Build.VERSION.RELEASE;			if (UmsConstants.DebugMode) {				printLog("android_osVersion", "OsVerson" + osVersion);			}			return osVersion;		} else {			if (UmsConstants.DebugMode) {				Log.e("android_osVersion", "OsVerson get failed");			}			return null;		}	}	/**	 * get deviceid	 * 	 * @param context	 *            add 
* @return */ public static String getDeviceID(Context context) { if (checkPermissions(context, "android.permission.READ_PHONE_STATE")) { String deviceId = ""; if (checkPhoneState(context)) { TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); deviceId = tm.getDeviceId(); } if (deviceId != null) { if (UmsConstants.DebugMode) { printLog("commonUtil", "deviceId:" + deviceId); } return deviceId; } else { if (UmsConstants.DebugMode) { Log.e("commonUtil", "deviceId is null"); } return null; } } else { if (UmsConstants.DebugMode) { Log.e("lost permissioin", "lost----->android.permission.READ_PHONE_STATE"); } return ""; } } /** * 鑾峰彇璁剧疆鐨勫敮涓€id 濡傛灉娌℃湁闅忔満浜х敓涓€涓插瓧绗︼紝绋嬪簭涓嶅嵏杞戒竴鐩村瓨鍦? * @param context * @return */ public static String getAndroidID(Context context) { String androidId = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID); Log.i("ada", "" + androidId); if (androidId == null) { SharedPreferences sharedPreferences = context.getSharedPreferences( "setting", Context.MODE_PRIVATE); String id = sharedPreferences.getString("id",null); if(id==null){ id=UUID.randomUUID().toString().replace("-", "").toLowerCase(); sharedPreferences.edit().putString("id", id).commit(); } androidId=id; } return androidId; } /** * check phone _state is readied ; * * @param context * @return */ public static boolean checkPhoneState(Context context) { PackageManager packageManager = context.getPackageManager(); if (packageManager .checkPermission("android.permission.READ_PHONE_STATE", context.getPackageName()) != 0) { return false; } return true; } /** * get sdk number * * @param paramContext * @return */ public static String getSdkVersion(Context paramContext) { String osVersion = ""; if (!checkPhoneState(paramContext)) { osVersion = android.os.Build.VERSION.RELEASE; if (UmsConstants.DebugMode) { Log.e("android_osVersion", "OsVerson" + osVersion); } return osVersion; } else { if (UmsConstants.DebugMode) { Log.e("android_osVersion", "OsVerson get failed"); } return null; } } /** * Get the version number of the current program * * @param context * @return */ public static String getCurVersion(Context context) { String curversion = ""; try { // ---get the package info--- PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); curversion = pi.versionName; if (curversion == null || curversion.length() <= 0) { return ""; } } catch (Exception e) { if (UmsConstants.DebugMode) { Log.e("VersionInfo", "Exception", e); } } return curversion; } /** * Get the current send model * * @param context * @return */ public static int getReportPolicyMode(Context context) { String str = context.getPackageName(); SharedPreferences localSharedPreferences = context .getSharedPreferences("ums_agent_online_setting_" + str, 0); int type = localSharedPreferences.getInt("ums_local_report_policy", 0); return type; } /** * To determine whether it contains a gyroscope * * @return */ public static boolean isHaveGravity(Context context) { SensorManager manager = (SensorManager) context .getSystemService(Context.SENSOR_SERVICE); if (manager == null) { return false; } return true; } /** * Get the current networking * * @param context * @return WIFI or MOBILE */ public static String getNetworkType(Context context) { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int type = manager.getNetworkType(); String typeString = "UNKOWN"; if (type == TelephonyManager.NETWORK_TYPE_CDMA) { typeString = "CDMA"; } if (type == TelephonyManager.NETWORK_TYPE_EDGE) { typeString = "EDGE"; } if (type == TelephonyManager.NETWORK_TYPE_EVDO_0) { typeString = "EVDO_0"; } if (type == TelephonyManager.NETWORK_TYPE_EVDO_A) { typeString = "EVDO_A"; } if (type == TelephonyManager.NETWORK_TYPE_GPRS) { typeString = "GPRS"; } if (type == TelephonyManager.NETWORK_TYPE_HSDPA) { typeString = "HSDPA"; } if (type == TelephonyManager.NETWORK_TYPE_HSPA) { typeString = "HSPA"; } if (type == TelephonyManager.NETWORK_TYPE_HSUPA) { typeString = "HSUPA"; } if (type == TelephonyManager.NETWORK_TYPE_UMTS) { typeString = "UMTS"; } if (type == TelephonyManager.NETWORK_TYPE_UNKNOWN) { typeString = "UNKOWN"; } return typeString; } /** * Determine the current network type * * @param context * @return */ public static boolean isNetworkTypeWifi(Context context) { // TODO Auto-generated method stub if (checkPermissions(context, "android.permission.INTERNET")) { ConnectivityManager cManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cManager.getActiveNetworkInfo(); if (info != null && info.isAvailable() && info.getTypeName().equals("WIFI")) { return true; } else { if (UmsConstants.DebugMode) { Log.e("error", "Network not wifi"); } return false; } } else { if (UmsConstants.DebugMode) { Log.e(" lost permission", "lost----> android.permission.INTERNET"); } return false; } } /** * Get the current application version number * * @param context * @return */ public static String getVersion(Context context) { String versionName = ""; try { PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); versionName = pi.versionName; if (versionName == null || versionName.length() <= 0) { return ""; } } catch (Exception e) { if (UmsConstants.DebugMode) { Log.e("UmsAgent", "Exception", e); } } return versionName; } /** * Set the output log * * @param tag * @param log */ public static void printLog(String tag, String log) { if (UmsConstants.DebugMode == true) { Log.d(tag, log); } } /** * install apk * * @param url */ public static void installApk(Context context, File apkfile) { if (!apkfile.exists()) { return; } Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); context.startActivity(i); } /** * 鍒ゆ柇鎵嬫満鏄惁瀹夎浜嗘煇涓▼搴忥紝濡傛灉瀹夎浜嗘绋嬪簭锛屽垹闄ゅ畠銆? * * @param context * @param name */ public static void uninstallSoftware(Context context, String name) { final PackageManager packageManager = context.getPackageManager(); try { PackageInfo pInfo = packageManager.getPackageInfo(name, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); if (pInfo != null) { // 鍒犻櫎杞欢 Uri uri = Uri.parse("package:" + name); Intent intent = new Intent(Intent.ACTION_DELETE, uri); context.startActivity(intent); } } catch (NameNotFoundException e) { e.printStackTrace(); } } /** * 鍒ゆ柇鎵嬫満鏄惁瀹夎浜嗘煇涓▼搴忥紝濡傛灉瀹夎浜嗘绋嬪簭锛屽垹闄ゅ畠銆? * * @param context * @param name */ public static boolean isinstallSoftware(Context context, String name) { boolean isinstall = false; final PackageManager packageManager = context.getPackageManager(); try { PackageInfo pInfo = packageManager.getPackageInfo(name, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); if (pInfo != null) { isinstall = true; } } catch (NameNotFoundException e) { e.printStackTrace(); } return isinstall; } /** * 绯荤粺涓墍鏈夊畨瑁呰繃鐨勮蒋浠? * * @param context * @param name */ public static void isinstallSoftware1(Context context, String name) { final PackageManager packageManager = context.getPackageManager();// 鑾峰彇packagemanager List
pinfo = packageManager.getInstalledPackages(0);// 鑾峰彇鎵€鏈夊凡瀹夎绋嬪簭鐨勫寘淇℃伅 if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { String packName = pinfo.get(i).packageName; Log.d("info", "-->" + packName); } } } /** * 鍒ゆ柇绋嬪簭鏄惁瀹夎鍒癝D鍗′笂 * * @param context * @param name */ public static void isInstallOnSd(Context context, String name) { PackageManager pm = context.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(name, 0); if ((appInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { // App on sdcard Log.d("info", "app on sd"); } } catch (NameNotFoundException e) { e.printStackTrace(); } }}
package cn.trinea.android.common.util;import java.io.File;import java.util.List;import android.app.ActivityManager;import android.app.ActivityManager.RunningTaskInfo;import android.content.Context;import android.content.Intent;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.net.Uri;import android.os.Build;import android.provider.Settings;import android.util.Log;import cn.trinea.android.common.util.ShellUtils.CommandResult;/** * PackageUtils * 
    *
    Install package *
  • {@link PackageUtils#installNormal(Context, String)}
  • *
  • {@link PackageUtils#installSilent(Context, String)}
  • *
  • {@link PackageUtils#install(Context, String)}
  • *
*
    *
    Uninstall package *
  • {@link PackageUtils#uninstallNormal(Context, String)}
  • *
  • {@link PackageUtils#uninstallSilent(Context, String)}
  • *
  • {@link PackageUtils#uninstall(Context, String)}
  • *
*
    *
    Is system application *
  • {@link PackageUtils#isSystemApplication(Context)}
  • *
  • {@link PackageUtils#isSystemApplication(Context, String)}
  • *
  • {@link PackageUtils#isSystemApplication(PackageManager, String)}
  • *
*
    *
    Others *
  • {@link PackageUtils#getInstallLocation()} get system install location
  • *
  • {@link PackageUtils#isTopActivity(Context, String)} whether the app whost package's name is packageName is on the * top of the stack
  • *
  • {@link PackageUtils#startInstalledAppDetails(Context, String)} start InstalledAppDetails Activity
  • *
* * @author Trinea 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 *
    *
  • if system application or rooted, see {@link #installSilent(Context, String)}
  • *
  • else see {@link #installNormal(Context, String)}
  • *
* * @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 *
    *
    Attentions: *
  • Don't call this on the ui thread, it may costs some times.
  • *
  • You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root * permission, if you are system app.
  • *
  • Default pm install params is "-r".
  • *
* * @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 *
    *
    Attentions: *
  • Don't call this on the ui thread, it may costs some times.
  • *
  • You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root * permission, if you are system app.
  • *
* * @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
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 *
    *
  • if system application or rooted, see {@link #uninstallSilent(Context, String)}
  • *
  • else see {@link #uninstallNormal(Context, String)}
  • *
* * @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 *
    *
    Attentions: *
  • Don't call this on the ui thread, it may costs some times.
  • *
  • You should add android.permission.DELETE_PACKAGES in manifest, so no need to request root * permission, if you are system app.
  • *
* * @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
    *
  • {@link #DELETE_SUCCEEDED} means uninstall success
  • *
  • {@link #DELETE_FAILED_INTERNAL_ERROR} means internal error
  • *
  • {@link #DELETE_FAILED_INVALID_PACKAGE} means package name error
  • *
  • {@link #DELETE_FAILED_PERMISSION_DENIED} means permission denied
  • */ public static int uninstallSilent(Context context, String packageName, boolean isKeepData) { if (packageName == null || packageName.length() == 0) { return DELETE_FAILED_INVALID_PACKAGE; } /** * if context is system app, don't need root permission, but should add
    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
      *
    • if packageManager is null, return false
    • *
    • if package name is null or is empty, return false
    • *
    • if package name not exit, return false
    • *
    • if package name exit, but not system app, return false
    • *
    • else return true
    • *
    */ 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 *
      *
      Attentions: *
    • You should add android.permission.GET_TASKS in manifest
    • *
    * * @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
    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
    * 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
    * install success. */ public static final int INSTALL_SUCCEEDED = 1; /** * Installation return code
    * the package is already installed. */ public static final int INSTALL_FAILED_ALREADY_EXISTS = -1; /** * Installation return code
    * the package archive file is invalid. */ public static final int INSTALL_FAILED_INVALID_APK = -2; /** * Installation return code
    * the URI passed in is invalid. */ public static final int INSTALL_FAILED_INVALID_URI = -3; /** * Installation return code
    * 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
    * a package is already installed with the same name. */ public static final int INSTALL_FAILED_DUPLICATE_PACKAGE = -5; /** * Installation return code
    * the requested shared user does not exist. */ public static final int INSTALL_FAILED_NO_SHARED_USER = -6; /** * Installation return code
    * 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
    * 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
    * the new package uses a shared library that is not available. */ public static final int INSTALL_FAILED_MISSING_SHARED_LIBRARY = -9; /** * Installation return code
    * the new package uses a shared library that is not available. */ public static final int INSTALL_FAILED_REPLACE_COULDNT_DELETE = -10; /** * Installation return code
    * 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
    * 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
    * 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
    * 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
    * 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
    * 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
    * the new package uses a feature that is not available. */ public static final int INSTALL_FAILED_MISSING_FEATURE = -17; /** * Installation return code
    * a secure container mount point couldn't be accessed on external media. */ public static final int INSTALL_FAILED_CONTAINER_ERROR = -18; /** * Installation return code
    * 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
    * 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
    * the new package couldn't be installed because the verification timed out. */ public static final int INSTALL_FAILED_VERIFICATION_TIMEOUT = -21; /** * Installation return code
    * 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
    * the package changed from what the calling program expected. */ public static final int INSTALL_FAILED_PACKAGE_CHANGED = -23; /** * Installation return code
    * the new package is assigned a different UID than it previously held. */ public static final int INSTALL_FAILED_UID_CHANGED = -24; /** * Installation return code
    * 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
    * if the parser was unable to retrieve the AndroidManifest.xml file. */ public static final int INSTALL_PARSE_FAILED_BAD_MANIFEST = -101; /** * Installation return code
    * if the parser encountered an unexpected exception. */ public static final int INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION = -102; /** * Installation return code
    * if the parser did not find any certificates in the .apk. */ public static final int INSTALL_PARSE_FAILED_NO_CERTIFICATES = -103; /** * Installation return code
    * 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
    * 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
    * 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
    * 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
    * if the parser encountered some structural problem in the manifest. */ public static final int INSTALL_PARSE_FAILED_MANIFEST_MALFORMED = -108; /** * Installation return code
    * 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
    * if the system failed to install the package because of system issues. */ public static final int INSTALL_FAILED_INTERNAL_ERROR = -110; /** * Installation return code
    * other reason */ public static final int INSTALL_FAILED_OTHER = -1000000; /** * Uninstall return code
    * uninstall success. */ public static final int DELETE_SUCCEEDED = 1; /** * Uninstall return code
    * 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
    * 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
    * uninstall fail if pcakge name is invalid */ public static final int DELETE_FAILED_INVALID_PACKAGE = -3; /** * Uninstall return code
    * 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 * 
    * Shuffling algorithm *
  • {@link #shuffle(Object[])} Shuffling algorithm, Randomly permutes the specified array using a default source of * randomness
  • *
  • {@link #shuffle(Object[], int)} Shuffling algorithm, Randomly permutes the specified array
  • *
  • {@link #shuffle(int[])} Shuffling algorithm, Randomly permutes the specified int array using a default source of * randomness
  • *
  • {@link #shuffle(int[], int)} Shuffling algorithm, Randomly permutes the specified int array
  • *
*
    * get random int *
  • {@link #getRandom(int)} get random int between 0 and max
  • *
  • {@link #getRandom(int, int)} get random int between min and max
  • *
*
    * get random numbers or letters *
  • {@link #getRandomCapitalLetters(int)} get a fixed-length random string, its a mixture of uppercase letters
  • *
  • {@link #getRandomLetters(int)} get a fixed-length random string, its a mixture of uppercase and lowercase letters *
  • *
  • {@link #getRandomLowerCaseLetters(int)} get a fixed-length random string, its a mixture of lowercase letters
  • *
  • {@link #getRandomNumbers(int)} get a fixed-length random string, its a mixture of numbers
  • *
  • {@link #getRandomNumbersAndLetters(int)} get a fixed-length random string, its a mixture of uppercase, lowercase * letters and numbers
  • *
  • {@link #getRandom(String, int)} get a fixed-length random string, its a mixture of chars in source
  • *
  • {@link #getRandom(char[], int)} get a fixed-length random string, its a mixture of chars in sourceChar
  • *
* * @author Trinea 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
    *
  • if source is null or empty, return null
  • *
  • else see {@link RandomUtils#getRandom(char[] sourceChar, int length)}
  • *
*/ 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
    *
  • if sourceChar is null or empty, return null
  • *
  • if length less than 0, return null
  • *
*/ 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
    *
  • if max <= 0, return 0
  • *
  • else return random int between 0 and max
  • *
*/ public static int getRandom(int max) { return getRandom(0, max); } /** * get random int between min and max * * @param min * @param max * @return
    *
  • if min > max, return 0
  • *
  • if min == max, return min
  • *
  • else return random int between min and max
  • *
*/ 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() {			@Override			public void run() {				try {					DefaultHttpClient httpClient = new DefaultHttpClient();					HttpPost httpPost = new HttpPost(mRemoteUrl);					List
params = new ArrayList
(); params.add(new BasicNameValuePair("package_name", mPackageName)); params.add(new BasicNameValuePair("package_version", mPackageVersion)); params.add(new BasicNameValuePair("phone_model", Build.MODEL)); params.add(new BasicNameValuePair("sdk_version", Build.VERSION.RELEASE)); params.add(new BasicNameValuePair("message", msg)); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpClient.execute(httpPost); } catch (Exception e) { } } }).start(); } public static void dump(String longMsg) { dump(mTag, longMsg, LEVEL_INFO); } public static void dump(String longMsg, int level) { dump(mTag, longMsg, level); } public static void dump(String tag, String longMsg) { dump(tag, longMsg, LEVEL_INFO); } public static void dump(String tag, String longMsg, int level) { int len = longMsg.length(); String curr; for (int a = 0; a < len; a += DUMP_LENGTH) { if (a + DUMP_LENGTH < len) { curr = longMsg.substring(a, a + DUMP_LENGTH); } else { curr = longMsg.substring(a); } switch (level) { case LEVEL_ERROR: Log.e(tag, curr); break; case LEVEL_WARNING: Log.w(tag, curr); break; case LEVEL_INFO: Log.i(tag, curr); break; case LEVEL_DEBUG: Log.d(tag, curr); break; case LEVEL_VERBOSE: default: Log.v(tag, curr); break; } } }}

转载地址:https://codegg.blog.csdn.net/article/details/50110819 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:一个记账易app开发
下一篇:android RootTooles 分享

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月15日 04时05分01秒