如何获取已安装或删除的应用程序的名称?

时间:2018-01-05 09:35:51

标签: android broadcastreceiver

我编写了一个广播接收器来检测安装和删除应用程序。 但我也希望获得已安装或删除的应用程序的名称。 我怎么能这样做?

这是我的BroadcastReceiver:

public class PackageReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        switch(intent.getAction())
        {
            case Intent.ACTION_PACKAGE_ADDED:
                String replaced = "";
                if(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    replaced = "replaced";
                }
                Log.e("application", "installed " + replaced);

                break;

            case Intent.ACTION_PACKAGE_REMOVED:
                if(!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    Log.e("application", "removed");
                }

                break;
        }

    }
}

在清单中:

<receiver
    android:name=".receivers.PackageReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
         <action android:name="android.intent.action.PACKAGE_ADDED" />
         <action android:name="android.intent.action.PACKAGE_REMOVED" />
         <data android:scheme="package" />
    </intent-filter>
</receiver>

1 个答案:

答案 0 :(得分:0)

android documentation和此answer中的信息与堆栈溢出相结合,我想出了以下内容。您正在使用的意图可能包含额外的EXTRA_UID,其中包含已修改应用的uid。使用uid,您可以获得应用名称。但是你只能在ACTION_PACKAGE_ADDED意图上执行此操作,因为在ACTION_PACKAGE_REMOVED应用程序已经删除并且您无法获取其名称(您仍然可以获得uid)。

检查此样本:

int uid = intent.getIntegerExtra(Intent.EXTRA_UID);
String appName = context.getPackageManager().getNameForUid(uid);

所以在你的情况下,它将是:

public class PackageReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch(intent.getAction())
        {
            case Intent.ACTION_PACKAGE_ADDED:
                String replaced = "";
                String appName = "";
                int uid = -1;
                if(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    replaced = "replaced";
                }
                uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
                if(uid != -1){
                    appName = context.getPackageManager().getNameForUid(uid);
                }
                Log.e("application", "installed " + replaced + " uid " + uid + " appname " + appName);

                break;

            case Intent.ACTION_PACKAGE_REMOVED:
                if(!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    Log.e("application", "removed");
                }
                break;
        }
    }
}

使用此代码,我从Google Play安装Google地球后看到这是用logcat编写的:

  

安装了uid 10404 appname com.google.earth