概述
Android代码集锦 SD卡相关
1. 检测Sdcard是否可用:
- public static boolean sdCardIsAvailable() {
- String status = Environment.getExternalStorageState();
- if (!status.equals(Environment.MEDIA_MOUNTED)) {
- return false;
- }
- return true;
- }
2. 获得程序在sd卡上的cahce目录:
- private static boolean hasExternalCacheDir() {
- return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
- }
- /**
- * @param context 上下文
- * @return The external cache dir SD卡路径
- */
- private static String getExternalCacheDir(Context context) {
- // android 2.2 以后才支持的特性
- if (hasExternalCacheDir()) {
- return context.getExternalCacheDir().getPath() + File.separator + "gesture";
- }
- // Before Froyo we need to construct the external cache dir ourselves
- // 2.2以前我们需要自己构造
- final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/gesture/";
- return Environment.getExternalStorageDirectory().getPath() + cacheDir;
- }
3. 获取Sdcard的实际空间大小:
- public static long getRealSizeOnSdcard() {
- File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
- StatFs stat = new StatFs(path.getPath());
- long blockSize = stat.getBlockSize();
- long availableBlocks = stat.getAvailableBlocks();
- return availableBlocks * blockSize;
- }
- /**
- * @param updateSize 指定的检测空间大小
- * @return True 空间足够返回true,不足返回false
- */
- public static boolean enoughSpaceOnSdCard(long updateSize) {
- String status = Environment.getExternalStorageState();
- if (!status.equals(Environment.MEDIA_MOUNTED))
- return false;
- return (updateSize < getRealSizeOnSdcard());
- }
4. 获取手机的存储大小:
- public static long getRealSizeOnPhone() {
- File path = Environment.getDataDirectory();
- StatFs stat = new StatFs(path.getPath());
- long blockSize = stat.getBlockSize();
- long availableBlocks = stat.getAvailableBlocks();
- long realSize = blockSize * availableBlocks;
- return realSize;
- }
- /**
- * @param updateSize 指定的检测空间大小
- * @return 空间足够返回true,不足返回false
- */
- public static boolean enoughSpaceOnPhone(long updateSize) {
- return getRealSizeOnPhone() > updateSize;
- }
附带点很久之前的记忆小赠品:
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转化为字符串:
- /**
- * @param 位图
- * @return 转化成的字符串
- */
- public static String bitmapToString(Bitmap bitmap) {
- // 将Bitmap转换成字符串
- String string = null;
- ByteArrayOutputStream bStream = new ByteArrayOutputStream();
- bitmap.compress(CompressFormat.PNG, 100, bStream);
- byte[] bytes = bStream.toByteArray();
- string = Base64.encodeToString(bytes, Base64.DEFAULT);
- return string;
- }
2.字符串转化为Bitmap:
- /**
- * @param string 字符串
- * @return 转化成的位图
- */
- public static Bitmap stringToBitmap(String string) {
- // 将字符串转换成Bitmap类型
- Bitmap bitmap = null;
- try {
- byte[] bitmapArray;
- bitmapArray = Base64.decode(string, Base64.DEFAULT);
- bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return bitmap;
- }
3.Bitmap转化为Drawable:
- /**
- * @param bitmap Bitmap位图图像
- * @return Drawable 转换后的Drawable对象
- */
- public static Drawable bitmapToDrawable(Bitmap bitmap) {
- if (bitmap == null)
- return null;
- if (160 != bitmap.getDensity()) {
- bitmap.setDensity(160);
- }
- return new BitmapDrawable(bitmap);
- }
根据图片资源ID获取Drawable对象:
- /**
- * @param context 上下文
- * @param id 图片的资源ID
- * @return Drawable对象
- */
- public static Drawable resourceToDrawable(Context context,int id) {
- return null == context ? null : bitmapToDrawable(BitmapFactory.decodeResource(context.getResources(), id));
- }
byte数组转换Drawble对象:
- /**
- * @param bytes byte数组
- * @return drawble对象
- */
- public static Drawable byteArrayToDrawable(byte[] bytes) {
- return null == bytes ? null : bitmapToDrawable(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
- }
4.Drawable转化为bitmap:
- /**
- * Drawble对象转Bitmap对象
- * @param drawable drawble对象
- * @return bitmap对象
- */
- public static Bitmap drawableToBitmap(Drawable drawable) {
- return null == drawable ? null : ((BitmapDrawable) drawable).getBitmap();
- }
5.byte数组转换Bitmap对象:
- /**
- * @param bytes byte数组
- * @return bitmap对象
- */
- public static Bitmap byteArrayToBitmap(byte[] bytes) {
- return null == bytes ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
- }
6.图片去色,返回灰度图片(老式图片):
- /**
- * @param bitmap 传入的bitmap
- * @return 去色后的图片Bitmap对象
- */
- public static Bitmap toGrayscale(Bitmap bitmap) {
- int width,height;
- height = bitmap.getHeight();
- width = bitmap.getWidth();
- Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
- Canvas c = new Canvas(bmpGrayscale);
- Paint paint = new Paint();
- ColorMatrix cm = new ColorMatrix();
- cm.setSaturation(0);
- ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
- paint.setColorFilter(f);
- c.drawBitmap(bitmap, 0, 0, paint);
- return bmpGrayscale;
- }
7.对图片进行缩放:
- /**
- * @param url 图片的路径
- * @param requireSize 缩放的尺寸
- * @return 缩放后的图片Bitmap对象
- */
- public static Bitmap getScaleImage(String url,int requireSize) {
- BitmapFactory.Options o = new BitmapFactory.Options();
- // 此属性表示图片不加载到内存,只是读取图片的属性,包括图片的高宽
- o.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(url, o);
- int width_tmp = o.outWidth,height_tmp = o.outHeight;
- int scale = 1;
- while (true) {
- if (width_tmp / 2 < requireSize || height_tmp / 2 < requireSize)
- break;
- width_tmp /= 2;
- height_tmp /= 2;
- scale *= 2;
- }
- BitmapFactory.Options o2 = new BitmapFactory.Options();
- o2.inSampleSize = scale;
- Bitmap bmp = BitmapFactory.decodeFile(url, o2);
- return bmp;
- }
8.获得图片的倒影,同时倒影渐变效果:
- /**
- * @param bitmap 图片源
- * @return 处理后的图片Bitmap对象
- */
- public static Bitmap createMirro(Bitmap bitmap) {
- int width = bitmap.getWidth();
- int height = bitmap.getHeight();
- int shadow_height = 15;
- int[] pixels = new int[width * height];
- bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
- // shadow effect
- int alpha = 0x00000000;
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- int index = y * width + x;
- int r = (pixels[index] >> 16) & 0xff;
- int g = (pixels[index] >> 8) & 0xff;
- int b = pixels[index] & 0xff;
- pixels[index] = alpha | (r << 16) | (g << 8) | b;
- }
- if (y >= (height - shadow_height)) {
- alpha = alpha + 0x1F000000;
- }
- }
- // invert effect
- Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
- for (int y = 0; y < height; y++) {
- bm.setPixels(pixels, y * width, width, 0, height - y - 1, width, 1);
- }
- return Bitmap.createBitmap(bm, 0, 0, width, shadow_height);
- }
9.保存图片到SDCard:
- /**
- * @param imagePath 图片保存路径
- * @param bm 被保存的bitmap对象
- */
- public static void saveImgToLocal(String imagePath, Bitmap bm) {
- if (bm == null || imagePath == null || "".equals(imagePath)) {
- return;
- }
- File f = new File(imagePath);
- if (f.exists()) {
- return;
- } else {
- try {
- File parentFile = f.getParentFile();
- if (!parentFile.exists()) {
- parentFile.mkdirs();
- }
- f.createNewFile();
- FileOutputStream fos;
- fos = new FileOutputStream(f);
- bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
- fos.close();
- } catch (FileNotFoundException e) {
- f.delete();
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- f.delete();
- }
- }
- }
10.从SDCard中获取图片:
- /**
- * @param imagePath 图片在SDCard中保存的路径
- * @return 返回保存的bitmap对象
- */
- public static Bitmap getImageFromLocal(String imagePath) {
- File file = new File(imagePath);
- if (file.exists()) {
- Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
- file.setLastModified(System.currentTimeMillis());
- return bitmap;
- }
- return null;
- }
11.图片压缩处理:
- /**
- * 对图片进行压缩,主要是为了解决控件显示过大图片占用内存造成OOM问题。
- * 一般压缩后的图片大小应该和用来展示它的控件大小相近。
- * @param context 上下文
- * @param resId 图片资源Id
- * @param reqWidth 期望压缩的宽度
- * @param reqHeight 期望压缩的高度
- * @return 压缩后的图片
- */
- public static Bitmap compressBitmapFromResourse(Context context, int resId, int reqWidth, int reqHeight) {
- final BitmapFactory.Options options = new BitmapFactory.Options();
- /*
- * 第一次解析时,inJustDecodeBounds设置为true,
- * 禁止为bitmap分配内存,虽然bitmap返回值为空,但可以获取图片大小
- */
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeResource(context.getResources(), resId, options);
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
- if (height > reqHeight || width > reqWidth) {
- final int heightRatio = Math.round((float) height / (float) reqHeight);
- final int widthRatio = Math.round((float) width / (float) reqWidth);
- inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
- }
- options.inSampleSize = inSampleSize;
- //使用计算得到的inSampleSize值再次解析图片
- options.inJustDecodeBounds = false;
- return BitmapFactory.decodeResource(context.getResources(), resId, options);
- }
12. 获取可用内存的最大值(App使用内存超出这个值会引起OutOfMemory异常):
- private int getMaxMemoryForApp() {
- int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
- return maxMemory;
- }
最后
以上就是阳光路人为你收集整理的android强大的工具类的全部内容,希望文章能够帮你解决android强大的工具类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复