标签:
需求:
将手机中的所有应用图标,以应用名称命名,后缀为jpg,存放在SD卡中
思路:
1.通过getPackageManager().getInstalledPackages(0)获取已安装的包的信息PackageInfo
2.通过包信息PackageInfo获取包名、版本名、版本号、当然还有应用图标Drawable对象
3.将Drawable对象转换成Bitmap对象再存储即可(。。。目前只能这样了,暂时不知道如何对Drawable进行处理)
代码:
1 package com.example.utils; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.util.List; 6 7 import android.app.Activity; 8 import android.content.pm.PackageInfo; 9 import android.graphics.Bitmap; 10 import android.graphics.Canvas; 11 import android.graphics.PixelFormat; 12 import android.graphics.drawable.Drawable; 13 import android.os.Bundle; 14 15 public class MainActivity extends Activity { 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 22 // 获取PackageInfo 23 List<PackageInfo> packages = getPackageManager().getInstalledPackages(0); 24 25 // 获取需要的信息并存储(当然这里可以用增强for循环) 26 for (int i = 0; i < packages.size(); i++) { 27 PackageInfo packageInfo = packages.get(i); 28 String appName = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString(); 29 Drawable appIcon = packageInfo.applicationInfo.loadIcon(getPackageManager()); 30 31 // 将drawable转成Bitmap对象 32 Bitmap bm = drawableToBitmap(appIcon); 33 34 // 指定存储路径以及存储文件名格式 35 File dir = new File("/sdcard/Pictures/"); 36 File outputImg = new File(dir, appName + ".jpg"); 37 38 // Bitmap存储过程 39 try { 40 FileOutputStream out = new FileOutputStream(outputImg); 41 bm.compress(Bitmap.CompressFormat.PNG, 90, out); 42 out.flush(); 43 out.close(); 44 LogUtil.e("test", "已经保存" + i); 45 } catch (Exception e) { 46 // 不处理异常了 47 } 48 49 } 50 } 51 52 /** 53 * 将Drawable转成Bitmap 54 * @param drawable 55 * @return 56 */ 57 public Bitmap drawableToBitmap(Drawable drawable) { 58 59 Bitmap bitmap = Bitmap.createBitmap( 60 61 drawable.getIntrinsicWidth(), 62 63 drawable.getIntrinsicHeight(), 64 65 drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 66 67 : Bitmap.Config.RGB_565); 68 69 Canvas canvas = new Canvas(bitmap); 70 71 // canvas.setBitmap(bitmap); 72 73 drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), 74 drawable.getIntrinsicHeight()); 75 76 drawable.draw(canvas); 77 78 return bitmap; 79 80 } 81 }
注意需要声明权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
参考:http://www.cnblogs.com/mainroadlee/archive/2011/05/23/android_get_installed_app.html
标签:
原文地址:http://www.cnblogs.com/erhai/p/5010774.html