android强大的工具类

来源:互联网 发布:lte信令源码详解 编辑:程序博客网 时间:2024/05/12 14:45

Android代码集锦 SD卡相关  

1. 检测Sdcard是否可用:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static boolean sdCardIsAvailable() {  
  2.         String status = Environment.getExternalStorageState();  
  3.         if (!status.equals(Environment.MEDIA_MOUNTED)) {  
  4.             return false;  
  5.         }  
  6.         return true;  
  7.     }  

   2. 获得程序在sd卡上的cahce目录:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private static boolean hasExternalCacheDir() {  
  2.         return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;  
  3.     }  
  4.   
  5. /** 
  6.      * @param context  上下文 
  7.      * @return The external cache dir  SD卡路径 
  8.      */  
  9.     private static String getExternalCacheDir(Context context) {  
  10.         // android 2.2 以后才支持的特性  
  11.         if (hasExternalCacheDir()) {  
  12.             return context.getExternalCacheDir().getPath() + File.separator + "gesture";  
  13.         }  
  14.   
  15.         // Before Froyo we need to construct the external cache dir ourselves  
  16.         // 2.2以前我们需要自己构造  
  17.         final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/gesture/";  
  18.         return Environment.getExternalStorageDirectory().getPath() + cacheDir;  
  19.     }  

   3. 获取Sdcard的实际空间大小:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static long getRealSizeOnSdcard() {  
  2.         File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());  
  3.         StatFs stat = new StatFs(path.getPath());  
  4.         long blockSize = stat.getBlockSize();  
  5.         long availableBlocks = stat.getAvailableBlocks();  
  6.         return availableBlocks * blockSize;  
  7.     }  
        ----->检测Sdcard是否有足够的空间:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param updateSize  指定的检测空间大小 
  3.      * @return True 空间足够返回true,不足返回false 
  4.      */  
  5.     public static boolean enoughSpaceOnSdCard(long updateSize) {  
  6.         String status = Environment.getExternalStorageState();  
  7.         if (!status.equals(Environment.MEDIA_MOUNTED))  
  8.             return false;  
  9.         return (updateSize < getRealSizeOnSdcard());  
  10.     }  

   4. 获取手机的存储大小:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static long getRealSizeOnPhone() {  
  2.         File path = Environment.getDataDirectory();  
  3.         StatFs stat = new StatFs(path.getPath());  
  4.         long blockSize = stat.getBlockSize();  
  5.         long availableBlocks = stat.getAvailableBlocks();  
  6.         long realSize = blockSize * availableBlocks;  
  7.         return realSize;  
  8.     }  
      ---->检测手机存储是否有足够的空间: 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param updateSize 指定的检测空间大小 
  3.      * @return 空间足够返回true,不足返回false 
  4.      */  
  5.     public static boolean enoughSpaceOnPhone(long updateSize) {  
  6.         return getRealSizeOnPhone() > updateSize;  
  7.     }  

 附带点很久之前的记忆小赠品:

    1. 在Android.mk中加入LOCAL_CERTIFICATE := platform就可以使用系统隐藏api(@hide)。


 2.Activity的启动模式总结:
  1). standard:
          堆栈(task):与应用程序的其他已启动过的Activity在同一个堆栈
 实例创建:每次启动都会创建新的实例

  2). singleTop:
          堆栈(task):与应用程序的其他已启动过的Activity在同一个堆栈
 实例创建:启动时,检查是否有该Activity的实例在当前的栈顶(启动过的记录)。若有,则不再创建新实例,若无,则重新创建新实例,置于栈顶。

  3). singleTask:
          堆栈(task): 与应用程序的其他已启动过的Activity在同一个堆栈
 实例创建:启动时,检查task中是否有该Activity的实例。若有,则将task中在该Activity实例之上的所有其他Activity实例统统出栈(pop),
 使其在栈顶。若无,则重新创建该Activity实例,置于栈顶。

  4). singleInstance:
          堆栈(task):与另外其他三种模式不同,会新建一个task,将Acitvity放置于这个新的task中,并保证不再有其他Activity实例进入.
 实例创建:第一次创建时,会新建一个task,将其至于新的task中。若实例已存在,在启动时,无需再创建新实例,复用之前已创建的实例。


  3.设置Activity的背景为手机桌面的背景:
   在setContentView方法之前添加getWindow().setFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER),
   然后在AndroidManifest.xml文件中添加android:theme="@android:style/Theme.Translucent"属性,实现将该Activity设置为透明。


  4.查看手机内存空间代码long freeMemory = Runtime.getRuntime().freeMemory();


  5.关于Android主线程:
   android中的主线程是UI线程,它是针对android中的UI组件操作的线程,而android中UI组件操作要求是非线程安全的,
   毕竟UI组件的更新操作要求快速响应,如果更新时考虑线程安全,同步锁等待响应之类的,那么UI组件的更新响应就有可能会延迟,
   这样话就不符合Android要求尽可能规避的ANR异常。


  6.Android4.4系统发布了一个ART运行时,准备用来替换掉之前一直使用的Dalvik虚拟机,希望籍此解决饱受诟病的性能问题。


  7. 引用相关:
   SoftReference<T>:软引用-->当虚拟机内存不足时,将会回收它指向的对象;需要获取对象时,可以调用get方法。
   WeakReference<T>:弱引用-->随时可能会被垃圾回收器回收。
   softReference多用作来实现cache机制,weakReference一般用来防止内存泄漏,要保证内存被VM回收 .


  8.TCP和UDP
  由于面向连接的TCP协议在发生数据丢包时,会要求重传,这会
  影响视频的实时性。UDP由于其是面向事务的,且简单不可靠的传输协议,
  在传输视频数据当中具有快捷,消耗资源小的特点,简单的传输过程中产生的
  丢包和乱序是可以在视频接收端处理的。所以一般采用UDP协议作为多媒体通信的传输层协议。


  9.内存相关:
   1). 一个进程的内存可以由2个部分组成:java 使用内存 ,C 使用内存 ,
   这两个内存的和必须小于16M(16M是怎么来的?算是实验来的吧,每个机型不一样,模拟器不同版本也不一样,可以通过:
Runtime.getMaxMemory() 来查看。),不然就会出现大家熟悉的OOM,这个就是第一种OOM的情况。
   2). 更加奇怪的是这个:一旦内存分配给Java后,以后这块内存即使释放后,也只能给Java的使用,这个估计跟java虚拟机里把内存分成好几块进行缓存的原因有关,反正C就别想用到这块的内存了。


Android代码集锦 图片处理相关


1. Bitmap转化为字符串:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * @param  位图 
  3.  * @return 转化成的字符串 
  4.  */  
  5. public static String bitmapToString(Bitmap bitmap) {  
  6.     // 将Bitmap转换成字符串  
  7.     String string = null;  
  8.     ByteArrayOutputStream bStream = new ByteArrayOutputStream();  
  9.     bitmap.compress(CompressFormat.PNG, 100, bStream);  
  10.     byte[] bytes = bStream.toByteArray();  
  11.     string = Base64.encodeToString(bytes, Base64.DEFAULT);  
  12.     return string;  
  13. }  
   

  2.字符串转化为Bitmap:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param string  字符串 
  3.      * @return 转化成的位图 
  4.      */  
  5.     public static Bitmap stringToBitmap(String string) {  
  6.         // 将字符串转换成Bitmap类型  
  7.         Bitmap bitmap = null;  
  8.         try {  
  9.             byte[] bitmapArray;  
  10.             bitmapArray = Base64.decode(string, Base64.DEFAULT);  
  11.             bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);  
  12.         } catch (Exception e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.         return bitmap;  
  16.     }  
    

   3.Bitmap转化为Drawable:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.  /** 
  2.  * @param bitmap    Bitmap位图图像  
  3.  * @return Drawable 转换后的Drawable对象  
  4.  */  
  5. public static Drawable bitmapToDrawable(Bitmap bitmap) {  
  6.     if (bitmap == null)  
  7.         return null;  
  8.     if (160 != bitmap.getDensity()) {  
  9.         bitmap.setDensity(160);  
  10.     }  
  11.     return new BitmapDrawable(bitmap);  
  12. }  

         根据图片资源ID获取Drawable对象:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * @param context   上下文 
  3.  * @param id        图片的资源ID  
  4.  * @return Drawable对象  
  5.  */  
  6. public static Drawable resourceToDrawable(Context context,int id) {  
  7.     return null == context ? null : bitmapToDrawable(BitmapFactory.decodeResource(context.getResources(), id));  
  8. }  

         byte数组转换Drawble对象:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * @param bytes byte数组  
  3.  * @return  drawble对象  
  4.  */  
  5. public static Drawable byteArrayToDrawable(byte[] bytes) {  
  6.     return null == bytes ? null : bitmapToDrawable(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));  
  7. }  

     4.Drawable转化为bitmap:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * Drawble对象转Bitmap对象 
  3.      * @param drawable  drawble对象  
  4.      * @return  bitmap对象  
  5.      */   
  6.     public static Bitmap drawableToBitmap(Drawable drawable) {  
  7.         return null == drawable ? null : ((BitmapDrawable) drawable).getBitmap();  
  8.     }  

    5.byte数组转换Bitmap对象:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param bytes byte数组  
  3.      * @return  bitmap对象  
  4.      */  
  5.     public static Bitmap byteArrayToBitmap(byte[] bytes) {  
  6.         return null == bytes ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
  7.     }  

     6.图片去色,返回灰度图片(老式图片):
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param bitmap  传入的bitmap 
  3.      * @return 去色后的图片Bitmap对象  
  4.      */  
  5.     public static Bitmap toGrayscale(Bitmap bitmap) {  
  6.         int width,height;  
  7.         height = bitmap.getHeight();  
  8.         width = bitmap.getWidth();  
  9.   
  10.         Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
  11.         Canvas c = new Canvas(bmpGrayscale);  
  12.         Paint paint = new Paint();  
  13.         ColorMatrix cm = new ColorMatrix();  
  14.         cm.setSaturation(0);  
  15.         ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);  
  16.         paint.setColorFilter(f);  
  17.         c.drawBitmap(bitmap, 00, paint);  
  18.         return bmpGrayscale;  
  19.     }  
    

    7.对图片进行缩放:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param url           图片的路径  
  3.      * @param requireSize   缩放的尺寸 
  4.      * @return 缩放后的图片Bitmap对象  
  5.      */  
  6.     public static Bitmap getScaleImage(String url,int requireSize) {  
  7.         BitmapFactory.Options o = new BitmapFactory.Options();  
  8.         // 此属性表示图片不加载到内存,只是读取图片的属性,包括图片的高宽  
  9.         o.inJustDecodeBounds = true;   
  10.         BitmapFactory.decodeFile(url, o);  
  11.         int width_tmp = o.outWidth,height_tmp = o.outHeight;  
  12.         int scale = 1;  
  13.         while (true) {  
  14.             if (width_tmp / 2 < requireSize || height_tmp / 2 < requireSize)  
  15.                 break;  
  16.             width_tmp /= 2;  
  17.             height_tmp /= 2;  
  18.             scale *= 2;  
  19.         }  
  20.         BitmapFactory.Options o2 = new BitmapFactory.Options();  
  21.         o2.inSampleSize = scale;  
  22.         Bitmap bmp = BitmapFactory.decodeFile(url, o2);  
  23.         return bmp;  
  24.     }  

     

     8.获得图片的倒影,同时倒影渐变效果:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param bitmap 图片源  
  3.      * @return  处理后的图片Bitmap对象  
  4.      */  
  5.     public static Bitmap createMirro(Bitmap bitmap) {  
  6.         int width = bitmap.getWidth();  
  7.         int height = bitmap.getHeight();  
  8.         int shadow_height = 15;   
  9.         int[] pixels = new int[width * height];  
  10.         bitmap.getPixels(pixels, 0, width, 00, width, height);  
  11.         // shadow effect  
  12.         int alpha = 0x00000000;  
  13.         for (int y = 0; y < height; y++) {  
  14.             for (int x = 0; x < width; x++) {  
  15.                 int index = y * width + x;  
  16.                 int r = (pixels[index] >> 16) & 0xff;  
  17.                 int g = (pixels[index] >> 8) & 0xff;  
  18.                 int b = pixels[index] & 0xff;  
  19.   
  20.                 pixels[index] = alpha | (r << 16) | (g << 8) | b;  
  21.             }  
  22.             if (y >= (height - shadow_height)) {  
  23.                 alpha = alpha + 0x1F000000;  
  24.             }  
  25.         }  
  26.         // invert effect  
  27.         Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);  
  28.         for (int y = 0; y < height; y++) {  
  29.             bm.setPixels(pixels, y * width, width, 0, height - y - 1, width, 1);  
  30.         }  
  31.         return Bitmap.createBitmap(bm, 00, width, shadow_height);  
  32.     }  

    9.保存图片到SDCard:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * @param imagePath 图片保存路径 
  3.      * @param bm 被保存的bitmap对象 
  4.      */  
  5.     public static void saveImgToLocal(String imagePath, Bitmap bm) {  
  6.   
  7.         if (bm == null || imagePath == null || "".equals(imagePath)) {  
  8.             return;  
  9.         }  
  10.   
  11.         File f = new File(imagePath);  
  12.         if (f.exists()) {  
  13.             return;  
  14.         } else {  
  15.             try {  
  16.                 File parentFile = f.getParentFile();  
  17.                 if (!parentFile.exists()) {  
  18.                     parentFile.mkdirs();  
  19.                 }  
  20.                 f.createNewFile();  
  21.                 FileOutputStream fos;  
  22.                 fos = new FileOutputStream(f);  
  23.                 bm.compress(Bitmap.CompressFormat.PNG, 100, fos);  
  24.                 fos.close();  
  25.             } catch (FileNotFoundException e) {  
  26.                 f.delete();  
  27.                 e.printStackTrace();  
  28.             } catch (IOException e) {  
  29.                 e.printStackTrace();  
  30.                 f.delete();  
  31.             }  
  32.         }  
  33.     }  

   

10.从SDCard中获取图片:

[java] view plaincopy
  1. /** 
  2.      * @param imagePath 图片在SDCard中保存的路径 
  3.      * @return  返回保存的bitmap对象 
  4.      */  
  5.     public static Bitmap getImageFromLocal(String imagePath) {  
  6.         File file = new File(imagePath);  
  7.         if (file.exists()) {  
  8.             Bitmap bitmap = BitmapFactory.decodeFile(imagePath);  
  9.             file.setLastModified(System.currentTimeMillis());  
  10.             return bitmap;  
  11.         }  
  12.         return null;  
  13.     }  

    11.图片压缩处理:

[java] view plaincopy
  1. /** 
  2.      * 对图片进行压缩,主要是为了解决控件显示过大图片占用内存造成OOM问题。 
  3.      * 一般压缩后的图片大小应该和用来展示它的控件大小相近。 
  4.      * @param context 上下文 
  5.      * @param resId 图片资源Id 
  6.      * @param reqWidth 期望压缩的宽度 
  7.      * @param reqHeight 期望压缩的高度 
  8.      * @return  压缩后的图片 
  9.      */  
  10.     public static Bitmap compressBitmapFromResourse(Context context, int resId, int reqWidth, int reqHeight) {  
  11.         final BitmapFactory.Options options = new BitmapFactory.Options();  
  12.         /* 
  13.          * 第一次解析时,inJustDecodeBounds设置为true, 
  14.          * 禁止为bitmap分配内存,虽然bitmap返回值为空,但可以获取图片大小 
  15.          */  
  16.         options.inJustDecodeBounds = true;  
  17.         BitmapFactory.decodeResource(context.getResources(), resId, options);  
  18.           
  19.         final int height = options.outHeight;  
  20.         final int width = options.outWidth;  
  21.         int inSampleSize = 1;  
  22.         if (height > reqHeight || width > reqWidth) {  
  23.             final int heightRatio = Math.round((float) height / (float) reqHeight);    
  24.             final int widthRatio = Math.round((float) width / (float) reqWidth);    
  25.             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;   
  26.         }  
  27.         options.inSampleSize = inSampleSize;  
  28.        //使用计算得到的inSampleSize值再次解析图片    
  29.        options.inJustDecodeBounds = false;    
  30.        return BitmapFactory.decodeResource(context.getResources(), resId, options);    
  31.     }  


   12.  获取可用内存的最大值(App使用内存超出这个值会引起OutOfMemory异常):

[java] view plaincopy
  1. private int getMaxMemoryForApp() {  
  2.         int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);  
  3.         return maxMemory;  
  4.     }  
0 0
原创粉丝点击