我想知道是否有可能从我在手机上下载的上一个安装的应用程序中获得图标(以png形式)?
我正在编写一个应用程序,我可以在我的手机上,它将提取最后安装的应用程序的软件包名称,公共名称,和图标(在png形式)。我得到了包名和通用名称,但现在我正在尝试获取图标文件。这是我在网上读到的关于如何做这件事的代码,但我似乎遗漏了一些东西。我提取图标的所有代码都在"try“语句中。
public class NewInstallReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("NewInstallReceiver", "Intent: " + intent.getAction());
final PackageManager pm = context.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo( intent.getData().getSchemeSpecificPart(), 0);
Log.d("PACKAGE NAME","Intent" + ai);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
Log.d("Application NAME", "Intent: " + applicationName);
// http://www.carbonrider.com/2016/01/01/extract-app-icon-in-android/
try {
Drawable icon = context.getPackageManager().getApplicationIcon(ai);
Log.d("ICON BITMAPDRAWABLE", "Intent: " + icon);
BitmapDrawable bitmapIcon = (BitmapDrawable)icon;
Log.d("ICON 11111", "Intent: " + bitmapIcon);
FileOutputStream fosIcon = context.openFileOutput(ai + ".png", Context.MODE_PRIVATE);
Log.d("ICON 22222", "Intent: " + fosIcon);
bitmapIcon.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
InputStream inputStream = context.openFileInput(ai + ".png");
Log.d("ICON NAME 33333", "Intent: " + inputStream);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Log.d("ICON bitmap 44444", "Intent: " + bitmap);
Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
Log.d("ICON drawable 55555", "Intent: " + drawable);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
catch (Exception e){
Log.d("CATCH", "CATCH ");
}
}
}发布于 2016-04-19 13:44:31
Context#openFilesInput()打开的文件目录与Context#getFilesDir()返回的私有目录相同。你将无法打开这个文件夹通过亚行,除非你的手机是根。但是,您可以通过这样做来检索File对象:
File imageFile = new File(context.getFilesDir(), "imgName.png");
值得注意的是,当前您正在以任何ApplicationInfo#toString()返回的名称命名图像。您可能想用applicationName + ".png打开文件。或者因为这是最新安装的应用程序,所以您可以将它保存为"latestApp.png“或一些独特的东西。
https://stackoverflow.com/questions/36681603
复制相似问题