Example usage for android.content.pm PackageManager getApplicationLabel

List of usage examples for android.content.pm PackageManager getApplicationLabel

Introduction

In this page you can find the example usage for android.content.pm PackageManager getApplicationLabel.

Prototype

public abstract CharSequence getApplicationLabel(ApplicationInfo info);

Source Link

Document

Return the label to use for this application.

Usage

From source file:com.leec.tools.apps.DetailsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_details_pager);

    // Set up the action bar.
    final android.support.v7.app.ActionBar actionBar = this.getSupportActionBar();

    Intent intent = getIntent();//from  w w w . j  a  va2s. c  o m
    String packageName = intent.getStringExtra(ARG_PACKAGE_NAME);

    PackageManager pm = getPackageManager();

    if (actionBar != null) {
        //show icon false
        //actionBar.setDisplayShowHomeEnabled(false);
        //back action
        actionBar.setDisplayHomeAsUpEnabled(true);

        actionBar.setSubtitle(packageName);
        try {
            PackageInfo p = pm.getPackageInfo(packageName, 0);
            actionBar.setTitle(pm.getApplicationLabel(p.applicationInfo));
            actionBar.setIcon(pm.getApplicationIcon(p.applicationInfo));
        } catch (NameNotFoundException e) {
        }
    }

    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager(), packageName, this);

    // Set up the ViewPager, attaching the adapter and setting up a listener for when the
    // user swipes between sections.
    mViewPager = (ViewPager) findViewById(R.id.app_details_pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);

    PagerTabStrip tabStrip = (PagerTabStrip) mViewPager.findViewById(R.id.pager_title);
    //tabStrip.setTabIndicatorColor();
    tabStrip.setTabIndicatorColorResource(R.color.tab_indicator_color);

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by the adapter.
        // Also specify this Activity object, which implements the TabListener interface, as the
        // listener for when this tab is selected.
        actionBar.addTab(
                actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

}

From source file:com.polyvi.xface.extension.XAppExt.java

/**
 * ???/* w  ww .j  a  v a2  s.c  o  m*/
 *
 * @param type
 *            "0":"1","2":
 * @return ??
 * @throws JSONException
 */
public JSONArray queryInstalledNativeApp(String type) throws JSONException {
    JSONArray appArray = new JSONArray();
    int appType = Integer.valueOf(type);
    PackageManager pm = getContext().getPackageManager();
    List<PackageInfo> packages = pm.getInstalledPackages(0);
    for (PackageInfo packageInfo : packages) {
        if (getContext().getPackageName().equals(packageInfo.applicationInfo.packageName))
            continue;
        switch (appType) {
        case 0:
            JSONObject obj = new JSONObject();
            obj.put(TAG_APP_NAME, pm.getApplicationLabel(packageInfo.applicationInfo).toString());
            obj.put(TAG_APP_ID, packageInfo.applicationInfo.packageName);
            obj.put(TAG_APP_ICON, drawableToBase64(pm.getApplicationIcon(packageInfo.applicationInfo)));
            appArray.put(obj);
            break;
        case 1:
            if ((packageInfo.applicationInfo.flags & 0x1) != 0)
                continue;
            JSONObject userAppObj = new JSONObject();
            userAppObj.put(TAG_APP_NAME, pm.getApplicationLabel(packageInfo.applicationInfo).toString());
            userAppObj.put(TAG_APP_ID, packageInfo.applicationInfo.packageName);
            userAppObj.put(TAG_APP_ICON, drawableToBase64(pm.getApplicationIcon(packageInfo.applicationInfo)));
            appArray.put(userAppObj);

            break;
        case 2:
            if ((packageInfo.applicationInfo.flags & 0x1) == 0)
                continue;
            JSONObject sysAppObj = new JSONObject();
            sysAppObj.put(TAG_APP_NAME, pm.getApplicationLabel(packageInfo.applicationInfo).toString());
            sysAppObj.put(TAG_APP_ID, packageInfo.applicationInfo.packageName);
            sysAppObj.put(TAG_APP_ICON, drawableToBase64(pm.getApplicationIcon(packageInfo.applicationInfo)));
            appArray.put(sysAppObj);
        }
    }
    return appArray;
}

From source file:com.grass.caishi.cc.MyApplication.java

private String getAppName(int pID) {
    String processName = null;/* w  w w.  j  a  va 2  s . c om*/
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List l = am.getRunningAppProcesses();
    Iterator i = l.iterator();
    PackageManager pm = this.getPackageManager();
    while (i.hasNext()) {
        ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
        try {
            if (info.pid == pID) {
                CharSequence c = pm.getApplicationLabel(
                        pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                // info.processName +" Label: "+c.toString());
                // processName = c.toString();
                processName = info.processName;
                return processName;
            }
        } catch (Exception e) {
            // Log.d("Process", "Error>> :"+ e.toString());
        }
    }
    return processName;
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushIntentService.java

private String getNotificationTitle(Context context) {
    // Check if push_notification_title is defined, if not get the
    // application name
    int notificationTitle = -1;
    try {/* ww w . j  a  v a 2 s . com*/
        notificationTitle = MFPPushUtils.getResourceId(getApplicationContext(), "string",
                "push_notification_title");
        return context.getString(notificationTitle);
    } catch (Exception e) {
        // ignore the exception
    }

    if (notificationTitle == -1) {
        ApplicationInfo appInfo = null;
        PackageManager packManager = context.getPackageManager();
        try {
            appInfo = packManager.getApplicationInfo(context.getPackageName(), 0);
        } catch (Exception e) {
            logger.warn(
                    "MFPPushIntentService:getNotificationTitle() - Notification will not have a title because application name is not available.");
        }

        if (appInfo != null) {
            return (String) packManager.getApplicationLabel(appInfo);
        }
    }

    return "";
}

From source file:de.arcus.framework.activities.CrashActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crash);

    // Reads the crash information
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        if (bundle.containsKey(EXTRA_FLAG_CRASH_MESSAGE))
            mCrashMessage = bundle.getString(EXTRA_FLAG_CRASH_MESSAGE);
        if (bundle.containsKey(EXTRA_FLAG_CRASH_LOG))
            mCrashLog = bundle.getString(EXTRA_FLAG_CRASH_LOG);
    } else {//from   www  .  j av a2 s  .c  om
        // No information; close activity
        finish();
        return;
    }

    try {
        // Get the PackageManager to load information about the app
        PackageManager packageManager = getPackageManager();
        // Loads the ApplicationInfo with meta data
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(),
                PackageManager.GET_META_DATA);

        if (applicationInfo.metaData != null) {
            // Reads the crash handler settings from meta data
            if (applicationInfo.metaData.containsKey("crashhandler.email"))
                mMetaDataEmail = applicationInfo.metaData.getString("crashhandler.email");
            if (applicationInfo.metaData.containsKey("crashhandler.supporturl"))
                mMetaDataSupportURL = applicationInfo.metaData.getString("crashhandler.supporturl");
        }

        // Gets the app name
        mAppName = packageManager.getApplicationLabel(applicationInfo).toString();
        // Gets the launch intent for the restart
        mLaunchIntent = packageManager.getLaunchIntentForPackage(getPackageName());

    } catch (PackageManager.NameNotFoundException ex) {
        // If this occurs then god must be already dead
        Logger.getInstance().logError("CrashHandler", ex.toString());
    }

    // Set the action bar title
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(getString(R.string.crashhandler_app_has_stopped_working, mAppName));
    }

    // Set the message
    TextView textViewMessage = (TextView) findViewById(R.id.text_view_crash_message);
    if (textViewMessage != null) {
        textViewMessage.setText(mCrashLog);
    }
}

From source file:com.ccxt.whl.DemoApplication.java

private String getAppName(int pID) {
    String processName = null;// w w  w  .  j a v a2s. c om
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List l = am.getRunningAppProcesses();
    Iterator i = l.iterator();
    PackageManager pm = this.getPackageManager();
    while (i.hasNext()) {
        ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
        try {
            if (info.pid == pID) {
                CharSequence c = pm.getApplicationLabel(
                        pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                // info.processName +"  Label: "+c.toString());
                // processName = c.toString();
                processName = info.processName;
                return processName;
            }
        } catch (Exception e) {
            // Log.d("Process", "Error>> :"+ e.toString());
        }
    }
    return processName;
}

From source file:me.piebridge.prevent.ui.UserGuideActivity.java

private CharSequence getLabel(PackageManager pm, ApplicationInfo info)
        throws PackageManager.NameNotFoundException {
    CharSequence label = null;/*  w ww.j  ava  2s  .c o  m*/
    if ("com.android.vending".equals(info.packageName)) {
        Resources resources = pm.getResourcesForApplication(info);
        int appName = resources.getIdentifier("app_name", "string", info.packageName);
        if (appName > 0) {
            label = resources.getText(appName);
        }
    }
    if (TextUtils.isEmpty(label)) {
        label = pm.getApplicationLabel(info);
    }
    return label;
}

From source file:com.android.messaging.util.PhoneUtils.java

/**
 * Returns the name of the default SMS app, or the empty string if there is
 * an error or there is no default app (e.g. JB and below).
 *///w ww  . j av a2  s.  c  o  m
public String getDefaultSmsAppLabel() {
    if (OsUtil.isAtLeastKLP()) {
        final String packageName = Telephony.Sms.getDefaultSmsPackage(mContext);
        final PackageManager pm = mContext.getPackageManager();
        try {
            final ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0);
            return pm.getApplicationLabel(appInfo).toString();
        } catch (NameNotFoundException e) {
            // Fall through and return empty string
        }
    }
    return "";
}

From source file:com.dafeng.upgradeapp.util.AutoUpdateApk2.java

private void setupVariables(Context ctx, String pkgName) {
    context = ctx;/*w  ww  .  j  a  v  a 2s  . com*/

    packageName = pkgName;
    preferences = context.getSharedPreferences(packageName + "_" + TAG, Context.MODE_PRIVATE);
    device_id = crc32(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID));
    last_update = preferences.getLong("last_update", 0);
    NOTIFICATION_ID += crc32(packageName);
    // schedule.add(new ScheduleEntry(0,24));
    PackageManager pm = context.getPackageManager();

    ApplicationInfo appinfo = null;// context.getApplicationInfo();

    try {
        appinfo = pm.getApplicationInfo(pkgName, 0);
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (appinfo == null)
        return;

    if (appinfo.icon != 0) {
        appIcon = appinfo.icon;
    } else {
        Log_w(TAG, "unable to find application icon");
    }
    if (appinfo.labelRes != 0) {
        appName = (String) pm.getApplicationLabel(appinfo);
    } else {
        Log_w(TAG, "unable to find application label");
    }
    if (new File(appinfo.sourceDir).lastModified() > preferences.getLong(MD5_TIME, 0)) {
        preferences.edit().putString(MD5_KEY, MD5Hex(appinfo.sourceDir)).commit();
        preferences.edit().putLong(MD5_TIME, System.currentTimeMillis()).commit();

        String update_file = preferences.getString(UPDATE_FILE, "");
        if (update_file.length() > 0) {
            if (new File(context.getFilesDir().getAbsolutePath() + "/" + update_file).delete()) {
                preferences.edit().remove(UPDATE_FILE).remove(SILENT_FAILED).commit();
            }
        }
    }
    // raise_notification();
    //
    // if (haveInternetPermissions()) {
    // context.registerReceiver(connectivity_receiver, new IntentFilter(
    // ConnectivityManager.CONNECTIVITY_ACTION));
    // }
}

From source file:com.apptentive.android.sdk.Apptentive.java

private static void init(Activity activity) {

    ////  w w w.  j a v a 2s .  c  om
    // First, initialize data relies on synchronous reads from local resources.
    //

    final Context appContext = activity.getApplicationContext();

    if (!GlobalInfo.initialized) {
        SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);

        // First, Get the api key, and figure out if app is debuggable.
        GlobalInfo.isAppDebuggable = false;
        String apiKey = null;
        boolean apptentiveDebug = false;
        String logLevelOverride = null;
        try {
            ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle metaData = ai.metaData;
            if (metaData != null) {
                apiKey = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY);
                logLevelOverride = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL);
                apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
                ApptentiveClient.useStagingServer = metaData
                        .getBoolean(Constants.MANIFEST_KEY_USE_STAGING_SERVER);
            }
            if (apptentiveDebug) {
                Log.i("Apptentive debug logging set to VERBOSE.");
                ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
            } else if (logLevelOverride != null) {
                Log.i("Overriding log level: %s", logLevelOverride);
                ApptentiveInternal.setMinimumLogLevel(Log.Level.parse(logLevelOverride));
            } else {
                GlobalInfo.isAppDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
                if (GlobalInfo.isAppDebuggable) {
                    ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
                }
            }
        } catch (Exception e) {
            Log.e("Unexpected error while reading application info.", e);
        }

        Log.i("Debug mode enabled? %b", GlobalInfo.isAppDebuggable);

        // If we are in debug mode, but no api key is found, throw an exception. Otherwise, just assert log. We don't want to crash a production app.
        String errorString = "No Apptentive api key specified. Please make sure you have specified your api key in your AndroidManifest.xml";
        if ((Util.isEmpty(apiKey))) {
            if (GlobalInfo.isAppDebuggable) {
                AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("Error")
                        .setMessage(errorString).setPositiveButton("OK", null).create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
            Log.e(errorString);
        }
        GlobalInfo.apiKey = apiKey;

        Log.i("API Key: %s", GlobalInfo.apiKey);

        // Grab app info we need to access later on.
        GlobalInfo.appPackage = appContext.getPackageName();
        GlobalInfo.androidId = Settings.Secure.getString(appContext.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

        // Check the host app version, and notify modules if it's changed.
        try {
            PackageManager packageManager = appContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(appContext.getPackageName(), 0);

            Integer currentVersionCode = packageInfo.versionCode;
            String currentVersionName = packageInfo.versionName;
            VersionHistoryStore.VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore
                    .getLastVersionSeen(appContext);
            if (lastVersionEntrySeen == null) {
                onVersionChanged(appContext, null, currentVersionCode, null, currentVersionName);
            } else {
                if (!currentVersionCode.equals(lastVersionEntrySeen.versionCode)
                        || !currentVersionName.equals(lastVersionEntrySeen.versionName)) {
                    onVersionChanged(appContext, lastVersionEntrySeen.versionCode, currentVersionCode,
                            lastVersionEntrySeen.versionName, currentVersionName);
                }
            }

            GlobalInfo.appDisplayName = packageManager
                    .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0))
                    .toString();
        } catch (PackageManager.NameNotFoundException e) {
            // Nothing we can do then.
            GlobalInfo.appDisplayName = "this app";
        }

        // Grab the conversation token from shared preferences.
        if (prefs.contains(Constants.PREF_KEY_CONVERSATION_TOKEN)
                && prefs.contains(Constants.PREF_KEY_PERSON_ID)) {
            GlobalInfo.conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
            GlobalInfo.personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null);
        }

        GlobalInfo.initialized = true;
        Log.v("Done initializing...");
    } else {
        Log.v("Already initialized...");
    }

    // Initialize the Conversation Token, or fetch if needed. Fetch config it the token is available.
    if (GlobalInfo.conversationToken == null || GlobalInfo.personId == null) {
        asyncFetchConversationToken(appContext.getApplicationContext());
    } else {
        asyncFetchAppConfiguration(appContext.getApplicationContext());
        InteractionManager.asyncFetchAndStoreInteractions(appContext.getApplicationContext());
    }

    // TODO: Do this on a dedicated thread if it takes too long. Some devices are slow to read device data.
    syncDevice(appContext);
    syncSdk(appContext);
    syncPerson(appContext);

    Log.d("Default Locale: %s", Locale.getDefault().toString());
    SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    Log.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
}