如何为上次安装的应用程序的图标提取 png 文件

how to extract a png file for the icon of the last installed app

我想知道是否可以从我 phone 下载的上次安装的应用程序中获取图标(png 格式)?

我正在编写一个可以放在 phone 上的应用程序,它将提取上次安装的应用程序的包名称、通用名称和图标(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 ");
    }


}



}

Context#openFilesInput()打开的文件目录与Context#getFilesDir()returns是同一个私有目录。除非您的 phone 已 root,否则您将无法通过 ADB 打开此文件夹。不过,您可以通过这样做来检索 File 对象:

File imageFile = new File(context.getFilesDir(), "imgName.png");

重要的是要注意,目前您正在以任何 ApplicationInfo#toString() returns 命名图像。您可能希望使用 applicationName + ".png 打开文件。或者由于这是最新安装的应用程序,您将其保存为 "latestApp.png" 或其他独特的名称。