List of usage examples for android.content.pm PackageManager getApplicationLabel
public abstract CharSequence getApplicationLabel(ApplicationInfo info);
From source file:fr.inria.ucn.collectors.RunningAppsCollector.java
@SuppressLint("NewApi") @Override/*from ww w . ja v a 2 s. co m*/ public void run(Context c, long ts) { try { ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE); PackageManager pm = c.getPackageManager(); JSONObject data = new JSONObject(); // running tasks JSONArray runTaskArray = new JSONArray(); List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(50); boolean first = true; for (ActivityManager.RunningTaskInfo info : taskInfo) { JSONObject jinfo = new JSONObject(); jinfo.put("task_id", info.id); jinfo.put("task_num_activities", info.numActivities); jinfo.put("task_num_running", info.numRunning); // is this the foreground process ? jinfo.put("task_foreground", first); if (first) { first = false; } if (info.topActivity != null) { jinfo.put("task_top_class_name", info.topActivity.getClassName()); jinfo.put("task_top_package_name", info.topActivity.getPackageName()); try { // map package name to app label CharSequence appLabel = pm.getApplicationLabel(pm.getApplicationInfo( info.topActivity.getPackageName(), PackageManager.GET_META_DATA)); jinfo.put("task_app_label", appLabel.toString()); } catch (NameNotFoundException e) { } } runTaskArray.put(jinfo); } data.put("runningTasks", runTaskArray); // processes JSONArray runProcArray = new JSONArray(); for (ActivityManager.RunningAppProcessInfo pinfo : am.getRunningAppProcesses()) { JSONObject jinfo = new JSONObject(); jinfo.put("proc_uid", pinfo.uid); jinfo.put("proc_name", pinfo.processName); jinfo.put("proc_packages", Helpers.getPackagesForUid(c, pinfo.uid)); runProcArray.put(jinfo); } data.put("runningAppProcesses", runProcArray); // done Helpers.sendResultObj(c, "running_apps", ts, data); } catch (JSONException jex) { Log.w(Constants.LOGTAG, "failed to create json obj", jex); } }
From source file:com.noshufou.android.su.InstallReceiver.java
@Override public void onReceive(Context context, Intent intent) { PackageManager pm = context.getPackageManager(); String packageName = intent.getDataString().split(":")[1]; PackageInfo packageInfo = null;//from w w w . j ava2 s .c om try { packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { // This won't happen, but if it does, we don't continue Log.e(TAG, "PackageManager divided by zero...", e); return; } if (Util.isPackageMalicious(context, packageInfo) != 0) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(Intent.ACTION_DELETE, intent.getData()); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.stat_su) .setTicker(context.getText(R.string.malicious_app_notification_ticker)) .setWhen(System.currentTimeMillis()).setContentTitle(context.getText(R.string.app_name)) .setContentText(context.getString(R.string.malicious_app_notification_text, pm.getApplicationLabel(packageInfo.applicationInfo))) .setContentIntent(contentIntent).setAutoCancel(true).getNotification(); nm.notify(0, notification); } }
From source file:com.android.leanlauncher.IconCache.java
public ArrayMap<String, String> getAvailableIconPacks() { ArrayMap<String, String> availableIconPacks = new ArrayMap<>(); PackageManager pm = mContext.getPackageManager(); // fetch installed icon packs for popular launchers Intent novaIntent = new Intent(Intent.ACTION_MAIN); novaIntent.addCategory(NOVA_LAUNCHER_THEME_NAME); List<ResolveInfo> novaTheme = pm.queryIntentActivities(novaIntent, PackageManager.GET_META_DATA); List<ResolveInfo> goTheme = pm.queryIntentActivities(new Intent(GO_LAUNCHER_THEME_NAME), PackageManager.GET_META_DATA); // merge those lists List<ResolveInfo> rinfo = new ArrayList<>(novaTheme); rinfo.addAll(goTheme);// w ww .ja v a 2 s . c om for (ResolveInfo ri : rinfo) { String packageName = ri.activityInfo.packageName; try { ApplicationInfo ai = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); String label = pm.getApplicationLabel(ai).toString(); Log.d(TAG, "Icon package = " + packageName + " title " + label); availableIconPacks.put(packageName, label); } catch (NameNotFoundException e) { Log.e(TAG, "Package not found = " + e); } } return availableIconPacks; }
From source file:com.rui.ruitime.AppUsageStatisticsFragment.java
/** * Updates the {@link #mRecyclerView} with the list of {@link UsageStats} passed as an argument. * * @param usageStatsList A list of {@link UsageStats} from which update the * {@link #mRecyclerView}. *///from w w w. j ava 2s.co m //VisibleForTesting void updateAppsList(List<UsageStats> usageStatsList, int modeOfSorting) { customUsageStatsList.clear(); PackageManager packageManager = getActivity().getPackageManager(); for (int i = 0; i < usageStatsList.size(); i++) { CustomAppUsageStats customUsageStats = new CustomAppUsageStats(); ApplicationInfo appInfo = new ApplicationInfo(); customUsageStats.usageStats = usageStatsList.get(i); try { Drawable appIcon = getActivity().getPackageManager() .getApplicationIcon(customUsageStats.usageStats.getPackageName()); customUsageStats.appIcon = appIcon; } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, String.format("App Icon is not found for %s", customUsageStats.usageStats.getPackageName())); customUsageStats.appIcon = getActivity().getDrawable(R.drawable.ic_default_app_launcher); } try { appInfo = packageManager.getApplicationInfo(customUsageStats.usageStats.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, String.format("App Name is not interpreted for %s", customUsageStats.usageStats.getPackageName())); } customUsageStats.appName = (String) (appInfo != null ? packageManager.getApplicationLabel(appInfo) : "Unknown"); int[] statsDuration = { 0, 0, 0 }; long lastTimeUsed = customUsageStats.usageStats.getLastTimeUsed(); DateFormat df = new SimpleDateFormat(); customUsageStats.lastUsedTimestampString = df.format(new Date(lastTimeUsed)); long totalDurationUsed = (long) (customUsageStats.usageStats.getTotalTimeInForeground() / 1000.0D); statsDuration[0] = (int) (totalDurationUsed / 3600); statsDuration[1] = (int) ((totalDurationUsed - statsDuration[0] * 3600) / 60); statsDuration[2] = (int) ((totalDurationUsed - statsDuration[0] * 3600 - statsDuration[1] * 60)); customUsageStats.totalUsedDurationString = ((statsDuration[0] > 0) ? statsDuration[0] + "h " : "") + ((statsDuration[1] > 0) ? statsDuration[1] + "m " : "") + ((statsDuration[2] > 0) ? statsDuration[2] + "s " : "1s"); customUsageStatsList.add(customUsageStats); } if (modeOfSorting == 0) { Collections.sort(customUsageStatsList, new TotalDurationUsedComparatorDesc()); } else if (modeOfSorting == 1) { Collections.sort(customUsageStatsList, new AlphabeticalComparatorDesc()); } mUsageListAdapter.setCustomUsageStatsList(customUsageStatsList); mUsageListAdapter.notifyDataSetChanged(); mRecyclerView.scrollToPosition(0); }
From source file:net.kidlogger.kidlogger.KLService.java
private void doScanTask() { ActivityManager actMng = (ActivityManager) KLService.this.getSystemService(ACTIVITY_SERVICE); List<RunningTaskInfo> taskInfo = actMng.getRunningTasks(1); String packageName = taskInfo.get(0).topActivity.getPackageName(); if (!packageName.equalsIgnoreCase(prevPack)) { PackageManager pm = getPackageManager(); String currTask;//from w w w . java2s . c o m //prevPack = packageName; prevPack = new String(packageName); try { CharSequence cs = pm .getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)); currTask = cs.toString(); } catch (Exception e) { currTask = "unknown"; } if (!currTask.equals("unknown")) { final String ct = new String(currTask); new Thread(new Runnable() { public void run() { sync.writeLog(".htm", Templates.getApiLog(ct)); } }).start(); //WriteThread wt = new WriteThread(sync, ".htm", Templates.getApiLog(currTask)); } } }
From source file:com.dattasmoon.pebble.plugin.NotificationService.java
@Override public void onAccessibilityEvent(AccessibilityEvent event) { // handle the prefs changing, because of how accessibility services // work, sharedprefsonchange listeners don't work if (watchFile.lastModified() > lastChange) { loadPrefs();/*from www .j av a 2 s.co m*/ } if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal())); } // if we are off, don't do anything. if (mode == Mode.OFF) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications"); } return; } //handle quiet hours if (quiet_hours) { Calendar c = Calendar.getInstance(); Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)); if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs " + quiet_hours_before.toString() + " and " + quiet_hours_after.toString()); } if (quiet_hours_before.after(quiet_hours_after)) { if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning."); } return; } } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning."); } return; } } // handle if they only want notifications if (notifications_only) { if (event != null) { Parcelable parcelable = event.getParcelableData(); if (!(parcelable instanceof Notification)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is not a notification and notifications only is enabled. Returning."); } return; } } } if (no_ongoing_notifs) { Parcelable parcelable = event.getParcelableData(); if (parcelable instanceof Notification) { Notification notif = (Notification) parcelable; if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning."); } return; } } else { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is not a notification."); } } } // Handle the do not disturb screen on settings PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn + " screen=" + powMan.isScreenOn()); } if (!notifScreenOn && powMan.isScreenOn()) { return; } if (event == null) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is null. Returning."); } return; } if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event: " + event.toString()); } // main logic PackageManager pm = getPackageManager(); String eventPackageName; if (event.getPackageName() != null) { eventPackageName = event.getPackageName().toString(); } else { eventPackageName = ""; } if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Service package list is: "); for (String strPackage : packages) { Log.i(Constants.LOG_TAG, strPackage); } Log.i(Constants.LOG_TAG, "End Service package list"); } switch (mode) { case EXCLUDE: // exclude functionality if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Mode is set to exclude"); } for (String packageName : packages) { if (packageName.equalsIgnoreCase(eventPackageName)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName + " which is on the exclude list. Returning."); } return; } } break; case INCLUDE: // include only functionality if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Mode is set to include only"); } boolean found = false; for (String packageName : packages) { if (packageName.equalsIgnoreCase(eventPackageName)) { found = true; break; } } if (!found) { Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning."); return; } break; } // get the title String title = ""; try { boolean renamed = false; for (int i = 0; i < pkg_renames.length(); i++) { if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) { renamed = true; title = pkg_renames.getJSONObject(i).getString("to"); } } if (!renamed) { title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString(); } } catch (NameNotFoundException e) { title = eventPackageName; } catch (JSONException e) { title = eventPackageName; } // get the notification text String notificationText = event.getText().toString(); // strip the first and last characters which are [ and ] notificationText = notificationText.substring(1, notificationText.length() - 1); if (notification_extras) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Fetching extras from notification"); } Parcelable parcelable = event.getParcelableData(); if (parcelable instanceof Notification) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim()); } else { notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim()); } } } // Check ignore lists for (int i = 0; i < ignores.length(); i++) { try { JSONObject ignore = ignores.getJSONObject(i); String app = ignore.getString("app"); boolean exclude = ignore.optBoolean("exclude", true); boolean case_insensitive = ignore.optBoolean("insensitive", true); if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) { //this rule doesn't apply to all apps and this isn't the app we're looking for. continue; } String regex = ""; if (case_insensitive) { regex += "(?i)"; } if (!ignore.getBoolean("raw")) { regex += Pattern.quote(ignore.getString("match")); } else { regex += ignore.getString("match"); } Pattern p = Pattern.compile(regex); Matcher m = p.matcher(notificationText); if (m.find()) { if (exclude) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '" + regex + "' and exclude is on. Returning"); } return; } } else { if (!exclude) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' does not match: '" + regex + "' and include is on. Returning"); } return; } } } catch (JSONException e) { continue; } } // Send the alert to Pebble sendToPebble(title, notificationText); if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, event.toString()); Log.i(Constants.LOG_TAG, event.getPackageName().toString()); } }
From source file:dev.ukanth.ufirewall.Api.java
/** * @param ctx application context (mandatory) * @return a list of applications/*from w w w .j av a2 s . c om*/ */ public static List<PackageInfoData> getApps(Context ctx, GetAppList appList) { initSpecial(); if (applications != null && applications.size() > 0) { // return cached instance return applications; } final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); final boolean enableRoam = defaultPrefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final String savedPkg_wifi_uid = prefs.getString(PREF_WIFI_PKG_UIDS, ""); final String savedPkg_3g_uid = prefs.getString(PREF_3G_PKG_UIDS, ""); final String savedPkg_roam_uid = prefs.getString(PREF_ROAMING_PKG_UIDS, ""); final String savedPkg_vpn_uid = prefs.getString(PREF_VPN_PKG_UIDS, ""); final String savedPkg_lan_uid = prefs.getString(PREF_LAN_PKG_UIDS, ""); List<Integer> selected_wifi = new ArrayList<Integer>(); List<Integer> selected_3g = new ArrayList<Integer>(); List<Integer> selected_roam = new ArrayList<Integer>(); List<Integer> selected_vpn = new ArrayList<Integer>(); List<Integer> selected_lan = new ArrayList<Integer>(); selected_wifi = getListFromPref(savedPkg_wifi_uid); selected_3g = getListFromPref(savedPkg_3g_uid); if (enableRoam) { selected_roam = getListFromPref(savedPkg_roam_uid); } if (enableVPN) { selected_vpn = getListFromPref(savedPkg_vpn_uid); } if (enableLAN) { selected_lan = getListFromPref(savedPkg_lan_uid); } //revert back to old approach //always use the defaul preferences to store cache value - reduces the application usage size final SharedPreferences cachePrefs = ctx.getSharedPreferences("AFWallPrefs", Context.MODE_PRIVATE); int count = 0; try { final PackageManager pkgmanager = ctx.getPackageManager(); final List<ApplicationInfo> installed = pkgmanager .getInstalledApplications(PackageManager.GET_META_DATA); SparseArray<PackageInfoData> syncMap = new SparseArray<PackageInfoData>(); final Editor edit = cachePrefs.edit(); boolean changed = false; String name = null; String cachekey = null; final String cacheLabel = "cache.label."; PackageInfoData app = null; ApplicationInfo apinfo = null; for (int i = 0; i < installed.size(); i++) { //for (final ApplicationInfo apinfo : installed) { count = count + 1; apinfo = installed.get(i); if (appList != null) { appList.doProgress(count); } boolean firstseen = false; app = syncMap.get(apinfo.uid); // filter applications which are not allowed to access the Internet if (app == null && PackageManager.PERMISSION_GRANTED != pkgmanager .checkPermission(Manifest.permission.INTERNET, apinfo.packageName)) { continue; } // try to get the application label from our cache - getApplicationLabel() is horribly slow!!!! cachekey = cacheLabel + apinfo.packageName; name = prefs.getString(cachekey, ""); if (name.length() == 0) { // get label and put on cache name = pkgmanager.getApplicationLabel(apinfo).toString(); edit.putString(cachekey, name); changed = true; firstseen = true; } if (app == null) { app = new PackageInfoData(); app.uid = apinfo.uid; app.names = new ArrayList<String>(); app.names.add(name); app.appinfo = apinfo; app.pkgName = apinfo.packageName; syncMap.put(apinfo.uid, app); } else { app.names.add(name); } app.firstseen = firstseen; // check if this application is selected if (!app.selected_wifi && Collections.binarySearch(selected_wifi, app.uid) >= 0) { app.selected_wifi = true; } if (!app.selected_3g && Collections.binarySearch(selected_3g, app.uid) >= 0) { app.selected_3g = true; } if (enableRoam && !app.selected_roam && Collections.binarySearch(selected_roam, app.uid) >= 0) { app.selected_roam = true; } if (enableVPN && !app.selected_vpn && Collections.binarySearch(selected_vpn, app.uid) >= 0) { app.selected_vpn = true; } if (enableLAN && !app.selected_lan && Collections.binarySearch(selected_lan, app.uid) >= 0) { app.selected_lan = true; } } List<PackageInfoData> specialData = new ArrayList<PackageInfoData>(); specialData.add(new PackageInfoData(SPECIAL_UID_ANY, ctx.getString(R.string.all_item), "dev.afwall.special.any")); specialData.add(new PackageInfoData(SPECIAL_UID_KERNEL, ctx.getString(R.string.kernel_item), "dev.afwall.special.kernel")); specialData.add(new PackageInfoData(SPECIAL_UID_TETHER, ctx.getString(R.string.tethering_item), "dev.afwall.special.tether")); //specialData.add(new PackageInfoData(SPECIAL_UID_DNSPROXY, ctx.getString(R.string.dnsproxy_item), "dev.afwall.special.dnsproxy")); specialData.add(new PackageInfoData(SPECIAL_UID_NTP, ctx.getString(R.string.ntp_item), "dev.afwall.special.ntp")); specialData .add(new PackageInfoData("root", ctx.getString(R.string.root_item), "dev.afwall.special.root")); specialData.add(new PackageInfoData("media", "Media server", "dev.afwall.special.media")); specialData.add(new PackageInfoData("vpn", "VPN networking", "dev.afwall.special.vpn")); specialData.add(new PackageInfoData("shell", "Linux shell", "dev.afwall.special.shell")); specialData.add(new PackageInfoData("gps", "GPS", "dev.afwall.special.gps")); specialData.add(new PackageInfoData("adb", "ADB (Android Debug Bridge)", "dev.afwall.special.adb")); if (specialApps == null) { specialApps = new HashMap<String, Integer>(); } for (int i = 0; i < specialData.size(); i++) { app = specialData.get(i); specialApps.put(app.pkgName, app.uid); //default DNS/NTP if (app.uid != -1 && syncMap.get(app.uid) == null) { // check if this application is allowed if (!app.selected_wifi && Collections.binarySearch(selected_wifi, app.uid) >= 0) { app.selected_wifi = true; } if (!app.selected_3g && Collections.binarySearch(selected_3g, app.uid) >= 0) { app.selected_3g = true; } if (enableRoam && !app.selected_roam && Collections.binarySearch(selected_roam, app.uid) >= 0) { app.selected_roam = true; } if (enableVPN && !app.selected_vpn && Collections.binarySearch(selected_vpn, app.uid) >= 0) { app.selected_vpn = true; } if (enableLAN && !app.selected_lan && Collections.binarySearch(selected_lan, app.uid) >= 0) { app.selected_lan = true; } syncMap.put(app.uid, app); } } if (changed) { edit.commit(); } /* convert the map into an array */ applications = new ArrayList<PackageInfoData>(); for (int i = 0; i < syncMap.size(); i++) { applications.add(syncMap.valueAt(i)); } return applications; } catch (Exception e) { alert(ctx, ctx.getString(R.string.error_common) + e); } return null; }
From source file:com.apptentive.android.sdk.ApptentiveInternal.java
public boolean init() { boolean bRet = true; codePointStore.init();/*from ww w. j av a 2 s . co m*/ /* If Message Center feature has never been used before, don't initialize message polling thread. * Message Center feature will be seen as used, if one of the following conditions has been met: * 1. Message Center has been opened for the first time * 2. The first Push is received which would open Message Center * 3. An unreadMessageCountListener() is set up */ boolean featureEverUsed = prefs.getBoolean(Constants.PREF_KEY_MESSAGE_CENTER_FEATURE_USED, false); if (featureEverUsed) { messageManager.init(); } conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null); conversationId = prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, null); personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null); apptentiveToolbarTheme = appContext.getResources().newTheme(); boolean apptentiveDebug = false; String logLevelOverride = null; String manifestApiKey = null; try { appPackageName = appContext.getPackageName(); PackageManager packageManager = appContext.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo(appPackageName, PackageManager.GET_META_DATA | PackageManager.GET_RECEIVERS); ApplicationInfo ai = packageInfo.applicationInfo; Bundle metaData = ai.metaData; if (metaData != null) { manifestApiKey = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY)); logLevelOverride = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL)); apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG); } // Used for application theme inheritance if the theme is an AppCompat theme. setApplicationDefaultTheme(ai.theme); AppRelease appRelease = AppRelease.generateCurrentAppRelease(appContext); isAppDebuggable = appRelease.getDebug(); currentVersionCode = appRelease.getVersionCode(); currentVersionName = appRelease.getVersionName(); VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore.getLastVersionSeen(); if (lastVersionEntrySeen == null) { onVersionChanged(null, currentVersionCode, null, currentVersionName, appRelease); } else { int lastSeenVersionCode = lastVersionEntrySeen.getVersionCode(); Apptentive.Version lastSeenVersionNameVersion = new Apptentive.Version(); lastSeenVersionNameVersion.setVersion(lastVersionEntrySeen.getVersionName()); if (!(currentVersionCode == lastSeenVersionCode) || !currentVersionName.equals(lastSeenVersionNameVersion.getVersion())) { onVersionChanged(lastVersionEntrySeen.getVersionCode(), currentVersionCode, lastVersionEntrySeen.getVersionName(), currentVersionName, appRelease); } } defaultAppDisplayName = packageManager .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0)).toString(); // Prevent delayed run-time exception if the app upgrades from pre-2.0 and doesn't remove NetworkStateReceiver from manifest ActivityInfo[] registered = packageInfo.receivers; if (registered != null) { for (ActivityInfo activityInfo : registered) { // Throw assertion error when relict class found in manifest. if (activityInfo.name.equals("com.apptentive.android.sdk.comm.NetworkStateReceiver")) { throw new AssertionError( "NetworkStateReceiver has been removed from Apptentive SDK, please make sure it's also removed from manifest file"); } } } } catch (Exception e) { ApptentiveLog.e("Unexpected error while reading application or package info.", e); bRet = false; } // Set debuggable and appropriate log level. if (apptentiveDebug) { ApptentiveLog.i("Apptentive debug logging set to VERBOSE."); setMinimumLogLevel(ApptentiveLog.Level.VERBOSE); } else if (logLevelOverride != null) { ApptentiveLog.i("Overriding log level: %s", logLevelOverride); setMinimumLogLevel(ApptentiveLog.Level.parse(logLevelOverride)); } else { if (isAppDebuggable) { setMinimumLogLevel(ApptentiveLog.Level.VERBOSE); } } ApptentiveLog.i("Debug mode enabled? %b", isAppDebuggable); String lastSeenSdkVersion = prefs.getString(Constants.PREF_KEY_LAST_SEEN_SDK_VERSION, ""); if (!lastSeenSdkVersion.equals(Constants.APPTENTIVE_SDK_VERSION)) { onSdkVersionChanged(appContext, lastSeenSdkVersion, Constants.APPTENTIVE_SDK_VERSION); } // The apiKey can be passed in programmatically, or we can fallback to checking in the manifest. if (TextUtils.isEmpty(apiKey) && !TextUtils.isEmpty(manifestApiKey)) { apiKey = manifestApiKey; } if (TextUtils.isEmpty(apiKey) || apiKey.contains(Constants.EXAMPLE_API_KEY_VALUE)) { String errorMessage = "The Apptentive API Key is not defined. You may provide your Apptentive API Key in Apptentive.register(), or in as meta-data in your AndroidManifest.xml.\n" + "<meta-data android:name=\"apptentive_api_key\"\n" + " android:value=\"@string/your_apptentive_api_key\"/>"; if (isAppDebuggable) { throw new RuntimeException(errorMessage); } else { ApptentiveLog.e(errorMessage); } } else { ApptentiveLog.d("Using cached Apptentive API Key"); } ApptentiveLog.d("Apptentive API Key: %s", apiKey); // Grab app info we need to access later on. androidId = Settings.Secure.getString(appContext.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); ApptentiveLog.d("Android ID: ", androidId); ApptentiveLog.d("Default Locale: %s", Locale.getDefault().toString()); ApptentiveLog.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null")); return bRet; }
From source file:com.android.calendar.EventInfoFragment.java
private void updateCustomAppButton() { buttonSetup: {//from w w w . j a va2s . c o m final Button launchButton = (Button) mView.findViewById(R.id.launch_custom_app_button); if (launchButton == null) break buttonSetup; final String customAppPackage = mEventCursor.getString(EVENT_INDEX_CUSTOM_APP_PACKAGE); final String customAppUri = mEventCursor.getString(EVENT_INDEX_CUSTOM_APP_URI); if (TextUtils.isEmpty(customAppPackage) || TextUtils.isEmpty(customAppUri)) break buttonSetup; PackageManager pm = mContext.getPackageManager(); if (pm == null) break buttonSetup; ApplicationInfo info; try { info = pm.getApplicationInfo(customAppPackage, 0); if (info == null) break buttonSetup; } catch (NameNotFoundException e) { break buttonSetup; } Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId); final Intent intent = new Intent(CalendarContract.ACTION_HANDLE_CUSTOM_EVENT, uri); intent.setPackage(customAppPackage); intent.putExtra(CalendarContract.EXTRA_CUSTOM_APP_URI, customAppUri); intent.putExtra(EXTRA_EVENT_BEGIN_TIME, mStartMillis); // See if we have a taker for our intent if (pm.resolveActivity(intent, 0) == null) break buttonSetup; Drawable icon = pm.getApplicationIcon(info); if (icon != null) { Drawable[] d = launchButton.getCompoundDrawables(); icon.setBounds(0, 0, mCustomAppIconSize, mCustomAppIconSize); launchButton.setCompoundDrawables(icon, d[1], d[2], d[3]); } CharSequence label = pm.getApplicationLabel(info); if (label != null && label.length() != 0) { launchButton.setText(label); } else if (icon == null) { // No icon && no label. Hide button? break buttonSetup; } // Launch custom app launchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { startActivityForResult(intent, 0); } catch (ActivityNotFoundException e) { // Shouldn't happen as we checked it already setVisibilityCommon(mView, R.id.launch_custom_app_container, View.GONE); } } }); setVisibilityCommon(mView, R.id.launch_custom_app_container, View.VISIBLE); return; } setVisibilityCommon(mView, R.id.launch_custom_app_container, View.GONE); return; }
From source file:com.linkbubble.Settings.java
public void updateBrowsers() { if (mBrowsers == null) { mBrowsers = new Vector<Intent>(); mBrowserPackageNames = new ArrayList<String>(); } else {/*from w w w .j av a 2 s .c om*/ mBrowsers.clear(); mBrowserPackageNames.clear(); } PackageManager packageManager = mContext.getPackageManager(); Intent queryIntent = new Intent(); queryIntent.setAction(Intent.ACTION_VIEW); queryIntent.setData(Uri.parse("http://www.fdasfjsadfdsfas.com")); // Something stupid that no non-browser app will handle List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(queryIntent, PackageManager.GET_RESOLVED_FILTER); String fallbackDefaultBrowserPackageName = null; String fallbackDefaultBrowserActivityClassName = null; for (ResolveInfo resolveInfo : resolveInfos) { IntentFilter filter = resolveInfo.filter; if (filter != null && filter.hasAction(Intent.ACTION_VIEW) && filter.hasCategory(Intent.CATEGORY_BROWSABLE)) { // Ignore LinkBubble from this list if (resolveInfo.activityInfo.packageName.equals(BuildConfig.APPLICATION_ID)) { mLinkBubbleEntryActivityResolveInfo = resolveInfo; } else if (Util.isValidBrowserPackageName(resolveInfo.activityInfo.packageName)) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name); mBrowsers.add(intent); mBrowserPackageNames.add(resolveInfo.activityInfo.packageName); if (resolveInfo.activityInfo.packageName .equals(mContext.getResources().getString(R.string.tab_based_browser_id_name))) { fallbackDefaultBrowserPackageName = resolveInfo.activityInfo.packageName; fallbackDefaultBrowserActivityClassName = resolveInfo.activityInfo.name; } } } } String defaultBrowserPackage = mSharedPreferences.getString(PREFERENCE_DEFAULT_BROWSER_PACKAGE_NAME, null); //String rightConsumeBubblePackageName = mSharedPreferences.getString(PREFERENCE_RIGHT_CONSUME_BUBBLE_PACKAGE_NAME, null); String leftConsumeBubblePackageName = mSharedPreferences .getString(PREFERENCE_LEFT_CONSUME_BUBBLE_PACKAGE_NAME, null); if (fallbackDefaultBrowserPackageName != null) { try { ApplicationInfo applicationInfo = packageManager .getApplicationInfo(fallbackDefaultBrowserPackageName, 0); String defaultBrowserLabel = packageManager.getApplicationLabel(applicationInfo).toString(); if (defaultBrowserPackage == null || !doesPackageExist(packageManager, defaultBrowserPackage)) { SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putString(PREFERENCE_DEFAULT_BROWSER_LABEL, defaultBrowserLabel); editor.putString(PREFERENCE_DEFAULT_BROWSER_PACKAGE_NAME, fallbackDefaultBrowserPackageName); editor.commit(); } if (leftConsumeBubblePackageName != null && !doesPackageExist(packageManager, leftConsumeBubblePackageName)) { setConsumeBubble(Constant.BubbleAction.ConsumeLeft, Constant.ActionType.View, defaultBrowserLabel, fallbackDefaultBrowserPackageName, fallbackDefaultBrowserActivityClassName); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } }