如何从android中的包名获取应用程序名称?

时间:2016-04-15 04:45:22

标签: android

我正在开发一个应用程序,如果有任何新的应用程序将在设备中安装我必须从该应用程序的包名称获取应用程序名称正确安装应用程序时,我正在执行下面的代码。但它总是显示(未知)消息给我而不是应用程序名称。请帮助我。

这是我的代码: -

    public class Receiver extends BroadcastReceiver {
    public Context context;
    public String title;

    @Override
    public void onReceive(Context context, Intent intent) {
        // Get application status(Install/ Uninstall)
        @SuppressWarnings("UnusedAssignment") boolean applicationStatus = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
        String toastMessage = null;

        // Check if the application is install or uninstall and display the message accordingly
        if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
            // Application Install
            toastMessage = "PACKAGE_INSTALL: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString());
        } else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {

            // Application Uninstall
            toastMessage = "PACKAGE_REMOVED: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString());
        } else if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
            // Application Replaced
            toastMessage = "PACKAGE_REPLACED: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString());
        }

        //Display Toast Message
        if (toastMessage != null) {
            Toast.makeText(context, toastMessage, Toast.LENGTH_LONG).show();
        }
        System.out.println("App Name:" + title);
    }

    /**
     * This method get application name name from application package name
     */
    private String getApplicationName(Context context, String data) {

        final PackageManager pckManager = context.getPackageManager();
        ApplicationInfo applicationInformation;
        try {
            applicationInformation = pckManager.getApplicationInfo(data, 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInformation = null;
        }

        title = (String) (applicationInformation != null ? pckManager.getApplicationLabel(applicationInformation) : "(unknown)");
        return title;

    }
}

1 个答案:

答案 0 :(得分:0)

需要使用PackageManager

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

PackageManager pkManager = getPackageManager();
        ApplicationInfo appInfo;
        String packageName=getApplicationContext().getApplicationInfo().packageName;
        try {
            appInfo = pkManager.getApplicationInfo(packageName, 0);
            final String appname = (String)((appInfo != null) ? pkManager.getApplicationLabel(appInfo) : "???");
                    Log.e("appname", appname);
        } catch (final NameNotFoundException e) {}