安卓常用到的几个工具类(不定期更新)

来源:互联网 发布:电脑锣编程 编辑:程序博客网 时间:2024/06/03 20:16

自己做项目,用到的几个工具类,这里记一下,以后找到方便

1.一个double类型数据精准四则运算类Arith.java

import java.math.BigDecimal;public class Arith{    //默认除法运算精度    private static final int DEF_DIV_SCALE = 10;    //这个类不能实例化    private Arith(){        }     /**     * 提供精确的加法运算。     * @param v1 被加数     * @param v2 加数     * @return 两个参数的和     */    public static double add(double v1,double v2){        BigDecimal b1 = new BigDecimal(Double.toString(v1));        BigDecimal b2 = new BigDecimal(Double.toString(v2));        return b1.add(b2).doubleValue();    }    /**     * 提供精确的减法运算。     * @param v1 被减数     * @param v2 减数     * @return 两个参数的差     */    public static double sub(double v1,double v2){        BigDecimal b1 = new BigDecimal(Double.toString(v1));        BigDecimal b2 = new BigDecimal(Double.toString(v2));        return b1.subtract(b2).doubleValue();    }     /**     * 提供精确的乘法运算。     * @param v1 被乘数     * @param v2 乘数     * @return 两个参数的积     */    public static double mul(double v1,double v2){        BigDecimal b1 = new BigDecimal(Double.toString(v1));        BigDecimal b2 = new BigDecimal(Double.toString(v2));        return b1.multiply(b2).doubleValue();    }     /**     * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到     * 小数点以后10位,以后的数字四舍五入。     * @param v1 被除数     * @param v2 除数     * @return 两个参数的商     */    public static double div(double v1,double v2){        return div(v1,v2,DEF_DIV_SCALE);    }     /**     * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指     * 定精度,以后的数字四舍五入。     * @param v1 被除数     * @param v2 除数     * @param scale 表示表示需要精确到小数点以后几位。     * @return 两个参数的商     */    public static double div(double v1,double v2,int scale){        if(scale<0){            throw new IllegalArgumentException(                "The scale must be a positive integer or zero");        }        BigDecimal b1 = new BigDecimal(Double.toString(v1));        BigDecimal b2 = new BigDecimal(Double.toString(v2));        return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();    }     /**     * 提供精确的小数位四舍五入处理。     * @param v 需要四舍五入的数字     * @param scale 小数点后保留几位     * @return 四舍五入后的结果     */    public static double round(double v,int scale){        if(scale<0){            throw new IllegalArgumentException(                "The scale must be a positive integer or zero");        }        BigDecimal b = new BigDecimal(Double.toString(v));        BigDecimal one = new BigDecimal("1");        return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();    }}
2.PrefUtils.java

import android.content.Context;import android.content.SharedPreferences;public class PrefUtils {public static boolean getBoolean(Context context,String key,boolean defalt){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);Boolean b=sp.getBoolean(key, defalt);return b;}public  static void  setBoolean(Context context,String key,Boolean value) {SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);sp.edit().putBoolean(key, value).commit();}public static String getString(Context context,String key,String defalt){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);String s=sp.getString(key, defalt);return s;}public static void SetString(Context context,String key,String value){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);sp.edit().putString(key, value).commit();}public static int getInt(Context context,String key,int defalt){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);int l=sp.getInt(key, defalt);return l;}public static void SetInt(Context context,String key,int value){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);sp.edit().putInt(key, value).commit();}public static long getLong(Context context,String key,long defalt){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);long l=sp.getLong(key, defalt);return l;}public static void SetLong(Context context,String key,long value){SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);sp.edit().putLong(key, value).commit();}}
3.log日志打印L.java

public class L  {        private L()      {          /* cannot be instantiated */          throw new UnsupportedOperationException("cannot be instantiated");      }        public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化      private static final String TAG = "way";        // 下面四个是默认tag的函数      public static void i(String msg)      {          if (isDebug)              Log.i(TAG, msg);      }        public static void d(String msg)      {          if (isDebug)              Log.d(TAG, msg);      }        public static void e(String msg)      {          if (isDebug)              Log.e(TAG, msg);      }        public static void v(String msg)      {          if (isDebug)              Log.v(TAG, msg);      }        // 下面是传入自定义tag的函数      public static void i(String tag, String msg)      {          if (isDebug)              Log.i(tag, msg);      }        public static void d(String tag, String msg)      {          if (isDebug)              Log.i(tag, msg);      }        public static void e(String tag, String msg)      {          if (isDebug)              Log.i(tag, msg);      }        public static void v(String tag, String msg)      {          if (isDebug)              Log.i(tag, msg);      }  }

4.单位转换的工具类DensityUtils

public class DensityUtils  {      private DensityUtils()      {          /* cannot be instantiated */          throw new UnsupportedOperationException("cannot be instantiated");      }        /**      * dp转px      *       * @param context      * @param val      * @return      */      public static int dp2px(Context context, float dpVal)      {          return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,                  dpVal, context.getResources().getDisplayMetrics());      }        /**      * sp转px      *       * @param context      * @param val      * @return      */      public static int sp2px(Context context, float spVal)      {          return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,                  spVal, context.getResources().getDisplayMetrics());      }        /**      * px转dp      *       * @param context      * @param pxVal      * @return      */      public static float px2dp(Context context, float pxVal)      {          final float scale = context.getResources().getDisplayMetrics().density;          return (pxVal / scale);      }        /**      * px转sp      *       * @param fontScale      * @param pxVal      * @return      */      public static float px2sp(Context context, float pxVal)      {          return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);      }    }  
5.屏幕读取类ScreenUtils

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;        }    }  
6.文件操作类FileUtil.java

public class FileUtil {private static FileUtil util;public static FileUtil init() { // 单例,个人习惯用Init,标准是getInstanceif (util == null)util = new FileUtil();return util;}private FileUtil() {}private Context context = null;public void setContext(Context c){this.context = c;}public Context getContext(){return context;}/** *  * @param path传入路径字符串 * @return File */public File creatFileIfNotExist(String path) {System.out.println("cr");File file = new File(path);if (!file.exists()) {try {new File(path.substring(0, path.lastIndexOf(File.separator))).mkdirs();file.createNewFile();} catch (IOException e) {e.printStackTrace();}}return file;}/** *  * @param path传入路径字符串 * @return File */public File creatDirIfNotExist(String path) {File file = new File(path);if (!file.exists()) {try {file.mkdirs();} catch (Exception e) {e.printStackTrace();}}return file;}/** *  * @param path * @return */public boolean IsExist(String path) {File file = new File(path);if (!file.exists())return false;elsereturn true;}/** * 创建新的文件,如果有旧文件,先删除再创建 *  * @param path * @return */public File creatNewFile(String path) {File file = new File(path);if (IsExist(path))file.delete();creatFileIfNotExist(path);return file;}/** * 删除文件 *  * @param path * @return */public boolean deleteFile(String path) {File file = new File(path);if (IsExist(path))file.delete();return true;}// 删除一个目录public boolean deleteFileDir(String path) {boolean flag = false;File file = new File(path);if (!IsExist(path)) {return flag;}if (!file.isDirectory()) {file.delete();return true;}String[] filelist = file.list();File temp = null;for (int i = 0; i < filelist.length; i++) {if (path.endsWith(File.separator)) {temp = new File(path + filelist[i]);} else {temp = new File(path + File.separator + filelist[i]);}if (temp.isFile()) {temp.delete();}if (temp.isDirectory()) {deleteFileDir(path + "/" + filelist[i]);// 先删除文件夹里面的文件}}file.delete();flag = true;return flag;}// 删除文件夹// param folderPath 文件夹完整绝对路径public void delFolder(String folderPath) {try {delAllFile(folderPath); // 删除完里面所有内容String filePath = folderPath;filePath = filePath.toString();java.io.File myFilePath = new java.io.File(filePath);myFilePath.delete(); // 删除空文件夹} catch (Exception e) {e.printStackTrace();}}// 删除指定文件夹下所有文件// param path 文件夹完整绝对路径public boolean delAllFile(String path) {boolean flag = false;File file = new File(path);if (!file.exists()) {return flag;}if (!file.isDirectory()) {return flag;}String[] tempList = file.list();File temp = null;for (int i = 0; i < tempList.length; i++) {if (path.endsWith(File.separator)) {temp = new File(path + tempList[i]);} else {temp = new File(path + File.separator + tempList[i]);}if (temp.isFile()) {temp.delete();}if (temp.isDirectory()) {delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件delFolder(path + "/" + tempList[i]);// 再删除空文件夹flag = true;}}return flag;}public String[] getFlieName(String rootpath) {File root = new File(rootpath);File[] filesOrDirs = root.listFiles();if (filesOrDirs != null) {String[] dir = new String[filesOrDirs.length];int num = 0;for (int i = 0; i < filesOrDirs.length; i++) {if (filesOrDirs[i].isDirectory()) {dir[i] = filesOrDirs[i].getName();num++;}}String[] dir_r = new String[num];num = 0;for (int i = 0; i < dir.length; i++) {if (dir[i] != null && !dir[i].equals("")) {dir_r[num] = dir[i];num++;}}return dir_r;} elsereturn null;}/** * //获得流 *  * @param path * @return * @throws FileNotFoundException * @throws UnsupportedEncodingException */public BufferedWriter getWriter(String path) throws FileNotFoundException,UnsupportedEncodingException {FileOutputStream fileout = null;fileout = new FileOutputStream(new File(path));OutputStreamWriter writer = null;writer = new OutputStreamWriter(fileout, "UTF-8");BufferedWriter w = new BufferedWriter(writer); // 缓冲区return w;}public InputStream getInputStream(String path) throws FileNotFoundException {// if(Comments.DEBUG) System.out.println("path:"+path);FileInputStream filein = null;// if(Comments.DEBUG) System.out.println("2");// File file = creatFileIfNotExist(path);File file = new File(path);filein = new FileInputStream(file);BufferedInputStream in = null;if (filein != null)in = new BufferedInputStream(filein);return in;}public boolean StateXmlControl(String path) {File f = new File(path);if (!f.exists())return false;if (f.length() == 0)return false;return true;}/** * 将InputStream转换成byte数组 *  * @param in *            InputStream * @return byte[] * @throws IOException */public static byte[] InputStreamTOByte(InputStream in) throws IOException {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] data = new byte[6 * 1024];int count = -1;while ((count = in.read(data, 0, 4 * 1024)) != -1)outStream.write(data, 0, count);data = null;return outStream.toByteArray();}/** * 将OutputStream转换成byte数组 *  * @param in *            OutputStream * @return byte[] * @throws IOException */public static byte[] OutputStreamTOByte(OutputStream out)throws IOException {byte[] data = new byte[6 * 1024];out.write(data);return data;}/** * 将byte数组转换成InputStream *  * @param in * @return * @throws Exception */public static InputStream byteTOInputStream(byte[] in) {ByteArrayInputStream is = new ByteArrayInputStream(in);return is;}/** * 将byte数组转换成OutputStream *  * @param in * @return * @throws IOException * @throws Exception */public static OutputStream byteTOOutputStream(byte[] in) throws IOException {ByteArrayOutputStream out = new ByteArrayOutputStream();out.write(in);return out;}/** * 把输入流中的数据输入到Path里的文件里 *  * @param path * @param fileName * @param inputStream * @return */public File writeFromInputToSD(String path, InputStream inputStream) {File file = null;OutputStream output = null;try {file = creatFileIfNotExist(path);output = new FileOutputStream(file);byte[] buffer = new byte[4 * 1024];int temp;while ((temp = inputStream.read(buffer)) != -1) {output.write(buffer, 0, temp);}output.flush();} catch (Exception e) {e.printStackTrace();} finally {try {output.close();} catch (Exception e) {e.printStackTrace();}}return file;}/** * 把数据输入到Path里的文件里 *  * @param path * @param fileName * @param inputStream * @return */public File writeFromInputToSD(String path, byte[] b) {File file = null;OutputStream output = null;try {file = creatFileIfNotExist(path);output = new FileOutputStream(file);output.write(b);output.flush();} catch (Exception e) {e.printStackTrace();} finally {try {output.close();} catch (Exception e) {e.printStackTrace();}}return file;}/** * 方法:把一段文本保存到给定的路径中. */public void saveTxtFile(String filePath, String text) {try {// 首先构建一个文件输出流,用于向文件中写入数据.creatFileIfNotExist(filePath);String txt = readTextLine(filePath);text = text + txt;FileOutputStream out = new FileOutputStream(filePath);// 构建一个写入器,用于向流中写入字符数据OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");writer.write(text);// 关闭Writer,关闭输出流writer.close();out.close();} catch (Exception e) {String ext = e.getLocalizedMessage();// Toast.makeText(this, ext, Toast.LENGTH_LONG).show();}}public void clearTxtFile(String filePath) {try {// 首先构建一个文件输出流,用于向文件中写入数据.String text = "";FileOutputStream out = new FileOutputStream(filePath);// 构建一个写入器,用于向流中写入字符数据OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");writer.write(text);// 关闭Writer,关闭输出流writer.close();out.close();} catch (Exception e) {String ext = e.getLocalizedMessage();// Toast.makeText(this, ext, Toast.LENGTH_LONG).show();}}// 读取一个给定的文本文件内容,并把内容以一个字符串的形式返回public String readTextLine(String textFile) {try {// 首先构建一个文件输入流,该流用于从文本文件中读取数据FileInputStream input = new FileInputStream(textFile);// 为了能够从流中读取文本数据,我们首先要构建一个特定的Reader的实例,// 因为我们是从一个输入流中读取数据,所以这里适合使用InputStreamReader.InputStreamReader streamReader = new InputStreamReader(input,"gb2312");// 为了能够实现一次读取一行文本的功能,我们使用了 LineNumberReader类,// 要构建LineNumberReader的实例,必须要传一个Reader实例做参数,// 我们传入前面已经构建好的Reder.LineNumberReader reader = new LineNumberReader(streamReader);// 字符串line用来保存每次读取到的一行文本.String line = null;// 这里我们使用一个StringBuilder来存储读取到的每一行文本,// 之所以不用String,是因为它每次修改都会产生一个新的实例,// 所以浪费空间,效率低.StringBuilder allLine = new StringBuilder();// 每次读取到一行,直到读取完成while ((line = reader.readLine()) != null) {allLine.append(line);// 这里每一行后面,加上一个换行符,LINUX中换行是”\n”,// windows中换行是”\r\n”.allLine.append("\n");}// 把Reader和Stream关闭streamReader.close();reader.close();input.close();// 把读取的字符串返回return allLine.toString();} catch (Exception e) {// Toast.makeText(this, e.getLocalizedMessage(),// Toast.LENGTH_LONG).show();return "";}}// 转换dip为pxpublic int convertDipOrPx(Context context, int dip) {float scale = context.getResources().getDisplayMetrics().density;return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));}// 转换px为dippublic int convertPxOrDip(Context context, int px) {float scale = context.getResources().getDisplayMetrics().density;return (int) (px / scale + 0.5f * (px >= 0 ? 1 : -1));}/** * 将px值转换为sp值,保证文字大小不变 *  * @param pxValue * @param fontScale *            (DisplayMetrics类中属性scaledDensity) * @return */public int px2sp(Context context, float pxValue) {float fontScale = context.getResources().getDisplayMetrics().scaledDensity;return (int) (pxValue / fontScale + 0.5f);}/** * 将sp值转换为px值,保证文字大小不变 *  * @param spValue * @param fontScale *            (DisplayMetrics类中属性scaledDensity) * @return */public int sp2px(Context context, float spValue) {float fontScale = context.getResources().getDisplayMetrics().scaledDensity;return (int) (spValue * fontScale + 0.5f);}// 把字加长,使其可以滚动,在音乐界面public String dealString(String st, int size) {int value = size;if (st.length() >= value)return "  " + st + "  ";else {int t = (value - st.length()) / 2;for (int i = 0; i < t; i++) {st = " " + st + "  ";}return st;}}public String getTimeByFormat(String format) {SimpleDateFormat formatter = new SimpleDateFormat(format);Date curDate = new Date(System.currentTimeMillis());// 获取当前时间String str = formatter.format(curDate);return str;}public String getDateTimeBylong(long time_data, String dateformat_batt) {java.util.Date date = new java.util.Date(time_data);SimpleDateFormat format = new SimpleDateFormat(dateformat_batt);return format.format(date);}// 取前面的名字 "."public String getNameByFlag(String source, String flag) {// String[] source_spli = source.split(flag);String s = source.toLowerCase().replace(flag, "");return s.trim();}/** * 取Asset文件夹下文件 * @param paramContext * @param paramString * @return * @throws IOException */public InputStream getAssetsInputStream(Context paramContext,String paramString) throws IOException {return paramContext.getResources().getAssets().open(paramString);}//以省内存的方式读取图片public Bitmap getBitmap(InputStream is){   BitmapFactory.Options opt = new BitmapFactory.Options();           opt.inPreferredConfig = Bitmap.Config.RGB_565;           opt.inPurgeable = true;          opt.inInputShareable = true;        opt.inSampleSize = 4;          //获取资源图片          //InputStream is = mContext.getResources().openRawResource(resId);              return BitmapFactory.decodeStream(is,null,opt);   }}

7.软键盘操作KeyBoardUtils.java

public class KeyBoardUtils  {      /**      * 打卡软键盘      *       * @param mEditText      *            输入框      * @param mContext      *            上下文      */      public static void openKeybord(EditText mEditText, Context mContext)      {          InputMethodManager imm = (InputMethodManager) mContext                  .getSystemService(Context.INPUT_METHOD_SERVICE);          imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);          imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,                  InputMethodManager.HIDE_IMPLICIT_ONLY);      }        /**      * 关闭软键盘      *       * @param mEditText      *            输入框      * @param mContext      *            上下文      */      public static void closeKeybord(EditText mEditText, Context mContext)      {          InputMethodManager imm = (InputMethodManager) mContext                  .getSystemService(Context.INPUT_METHOD_SERVICE);            imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);      }  }  
8.网络连接类NetUtils.java
public class NetUtils  {      private NetUtils()      {          /* cannot be instantiated */          throw new UnsupportedOperationException("cannot be instantiated");      }        /**      * 判断网络是否连接      *       * @param context      * @return      */      public static boolean isConnected(Context context)      {            ConnectivityManager connectivity = (ConnectivityManager) context                  .getSystemService(Context.CONNECTIVITY_SERVICE);            if (null != connectivity)          {                NetworkInfo info = connectivity.getActiveNetworkInfo();              if (null != info && info.isConnected())              {                  if (info.getState() == NetworkInfo.State.CONNECTED)                  {                      return true;                  }              }          }          return false;      }        /**      * 判断是否是wifi连接      */      public static boolean isWifi(Context context)      {          ConnectivityManager cm = (ConnectivityManager) context                  .getSystemService(Context.CONNECTIVITY_SERVICE);            if (cm == null)              return false;          return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;        }        /**      * 打开网络设置界面      */      public static void openSetting(Activity activity)      {          Intent intent = new Intent("/");          ComponentName cm = new ComponentName("com.android.settings",                  "com.android.settings.WirelessSettings");          intent.setComponent(cm);          intent.setAction("android.intent.action.VIEW");          activity.startActivityForResult(intent, 0);      }    }  
9.检测某程序是否安装
public static boolean isInstalledApp(Context context, String packageName)    {        Boolean flag = false;        try        {            PackageManager pm = context.getPackageManager();            List<PackageInfo> pkgs = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);            for (PackageInfo pkg : pkgs)            {                // 当找到了名字和该包名相同的时候,返回                if ((pkg.packageName).equals(packageName))                {                    return flag = true;                }            }        }        catch (Exception e)        {            // TODO Auto-generated catch block            e.printStackTrace();        }        return flag;    }

10.安装apk文件

/**     * 安装.apk文件     *      * @param context     */    public void install(Context context, String fileName)    {        if (TextUtils.isEmpty(fileName) || context == null)        {            return;        }        try        {            Intent intent = new Intent(Intent.ACTION_VIEW);            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            intent.setAction(android.content.Intent.ACTION_VIEW);            intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");            context.startActivity(intent);        }        catch (Exception e)        {            e.printStackTrace();        }    }    /**     * 安装.apk文件     *      * @param context     */    public void install(Context context, File file)    {        try        {            Intent intent = new Intent(Intent.ACTION_VIEW);            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");            context.startActivity(intent);        }        catch (Exception e)        {            e.printStackTrace();        }    }

11.string.xml中%s的用法

在strings.xml中添加字符串string name="text">Hello,%s!</string>代码中使用textView.setText(String.format(getResources().getString(R.string.text),"Android"));输出结果:Hello,Android!

12.根据mac地址+deviceid获取设备唯一编码

private static String DEVICEKEY = "";    /**     * 根据mac地址+deviceid     * 获取设备唯一编码     * @return     */    public static String getDeviceKey()    {        if ("".equals(DEVICEKEY))        {            String macAddress = "";            WifiManager wifiMgr = (WifiManager)MainApplication.getIns().getSystemService(MainApplication.WIFI_SERVICE);            WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());            if (null != info)            {                macAddress = info.getMacAddress();            }            TelephonyManager telephonyManager =                (TelephonyManager)MainApplication.getIns().getSystemService(MainApplication.TELEPHONY_SERVICE);            String deviceId = telephonyManager.getDeviceId();            DEVICEKEY = MD5Util.toMD5("android" + Constant.APPKEY + Constant.APPPWD + macAddress + deviceId);        }        return DEVICEKEY;    }
13.获取手机及SIM卡相关信息
/**     * 获取手机及SIM卡相关信息     * @param context     * @return     */    public static Map<String, String> getPhoneInfo(Context context) {        Map<String, String> map = new HashMap<String, String>();        TelephonyManager tm = (TelephonyManager) context                .getSystemService(Context.TELEPHONY_SERVICE);        String imei = tm.getDeviceId();        String imsi = tm.getSubscriberId();        String phoneMode = android.os.Build.MODEL;         String phoneSDk = android.os.Build.VERSION.RELEASE;        map.put("imei", imei);        map.put("imsi", imsi);        map.put("phoneMode", phoneMode+"##"+phoneSDk);        map.put("model", phoneMode);        map.put("sdk", phoneSDk);        return map;    }

12.二维码工具类,需要zxing.jar类库支持

import android.graphics.Bitmap;import com.google.zxing.BarcodeFormat;import com.google.zxing.MultiFormatWriter;import com.google.zxing.WriterException;import com.google.zxing.common.BitMatrix;/**  * 二维码工具类  */public class QrCodeUtils {/** * 传入字符串生成二维码 * @param str * @return * @throws WriterException */public static Bitmap Create2DCode(String str) throws WriterException {// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败BitMatrix matrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, 300, 300);int width = matrix.getWidth();int height = matrix.getHeight();// 二维矩阵转为一维像素数组,也就是一直横着排了int[] pixels = new int[width * height];for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {if (matrix.get(x, y)) {pixels[y * width + x] = 0xff000000;}}}Bitmap bitmap = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);// 通过像素数组生成bitmap,具体参考apibitmap.setPixels(pixels, 0, width, 0, 0, width, height);return bitmap;}}





1 1
原创粉丝点击