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

时间:2016-04-17 20:05:57

标签: java android bitmap broadcastreceiver imageicon

我想知道是否有可能从我在手机上下载的上一个安装的应用程序中获取图标(以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 ");
    }


}



}

1 个答案:

答案 0 :(得分:0)

Context#openFilesInput()打开的文件目录与Context#getFilesDir()返回的私有目录相同。除非您的手机已植根,否则您将无法通过ADB打开此文件夹。您可以通过以下方式检索File对象:

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

重要的是要注意,目前你在ApplicationInfo#toString()返回之后命名图像。您可能希望使用applicationName + ".png打开文件。或者由于这是最新安装的应用程序,因此您将其另存为“latestApp.png”或其他独特内容。