Example usage for android.content.pm PackageManager GET_META_DATA

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

Introduction

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

Prototype

int GET_META_DATA

To view the source code for android.content.pm PackageManager GET_META_DATA.

Click Source Link

Document

ComponentInfo flag: return the ComponentInfo#metaData data android.os.Bundle s that are associated with a component.

Usage

From source file:com.evandroid.musica.broadcastReceiver.MusicBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /** Google Play Music
     //bool streaming            long position
     //long albumId               String album
     //bool currentSongLoaded      String track
     //long ListPosition         long ListSize
     //long id                  bool playing
     //long duration            int previewPlayType
     //bool supportsRating         int domain
     //bool albumArtFromService      String artist
     //int rating               bool local
     //bool preparing            bool inErrorState
     *//*from  ww  w . j  a v a 2  s. c om*/

    Bundle extras = intent.getExtras();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true);

    if (extras != null)
        try {
            extras.getInt("state");
        } catch (BadParcelableException e) {
            return;
        }

    if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs
            || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000)
                    || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000)
                    || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200))
            || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000)
                    || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000)
                    || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200)))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") ? extras.getLong("position") : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean("playing", true);

    if (intent.getAction().equals("com.amazon.mp3.metachanged")) {
        artist = extras.getString("com.amazon.mp3.artist");
        track = extras.getString("com.amazon.mp3.track");
    } else if (intent.getAction().equals("com.spotify.music.metadatachanged"))
        isPlaying = spotifyPlaying;
    else if (intent.getAction().equals("com.spotify.music.playbackstatechanged"))
        spotifyPlaying = isPlaying;

    if ((artist == null || "".equals(artist)) //Could be problematic
            || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts
        return;

    SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    String currentArtist = current.getString("artist", "");
    String currentTrack = current.getString("track", "");

    SharedPreferences.Editor editor = current.edit();
    editor.putString("artist", artist);
    editor.putString("track", track);
    editor.putLong("position", position);
    editor.putBoolean("playing", isPlaying);
    if (isPlaying) {
        long currentTime = System.currentTimeMillis();
        editor.putLong("startTime", currentTime);
    }
    editor.apply();

    autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false);
    int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0"));

    if (autoUpdate && App.isActivityVisible()) {
        Intent internalIntent = new Intent("Broadcast");
        internalIntent.putExtra("artist", artist).putExtra("track", track);
        LyricsViewFragment.sendIntent(context, internalIntent);
        forceAutoUpdate(false);
    }

    SQLiteDatabase db = new DatabaseHelper(context).getReadableDatabase();
    boolean inDatabase = DatabaseHelper.presenceCheck(db, new String[] { artist, track, artist, track });
    db.close();

    if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) {
        Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS",
                new String[] { artist, track });
        Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist)
                .putExtra("track", track);
        PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch,
                context.getString(R.string.wearable_prompt), wearablePending).build();

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
        NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context);

        if ("0".equals(sharedPref.getString("pref_theme", "0")))
            notifBuilder.setColor(context.getResources().getColor(R.color.primary));

        notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setGroupSummary(true);

        wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setOngoing(false).setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
        } else
            notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW

        Notification notif = notifBuilder.build();
        Notification wearableNotif = wearableNotifBuilder.build();

        if (notificationPref == 2)
            notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        else
            notif.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat.from(context).notify(0, notif);
        try {
            context.getPackageManager().getPackageInfo("com.google.android.wearable.app",
                    PackageManager.GET_META_DATA);
            NotificationManagerCompat.from(context).notify(8, wearableNotif);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    } else if (track.equals(current.getString("track", "")))
        NotificationManagerCompat.from(context).cancel(0);
}

From source file:io.flutter.embedding.engine.android.FlutterActivity.java

/**
 * The Dart entrypoint that will be executed as soon as the Dart snapshot is loaded.
 * <p>//from   w ww .  java2  s. c  om
 * This preference can be controlled with 2 methods:
 * <ol>
 *   <li>Pass a {@code String} as {@link #EXTRA_DART_ENTRYPOINT} with the launching {@code Intent}, or</li>
 *   <li>Set a {@code <meta-data>} called {@link #DART_ENTRYPOINT_META_DATA_KEY} for this
 *       {@code Activity} in the Android manifest.</li>
 * </ol>
 * If both preferences are set, the {@code Intent} preference takes priority.
 * <p>
 * The reason that a {@code <meta-data>} preference is supported is because this {@code Activity}
 * might be the very first {@code Activity} launched, which means the developer won't have
 * control over the incoming {@code Intent}.
 * <p>
 * Subclasses may override this method to directly control the Dart entrypoint.
 */
@Nullable
protected String getDartEntrypoint() {
    if (getIntent().hasExtra(EXTRA_DART_ENTRYPOINT)) {
        return getIntent().getStringExtra(EXTRA_DART_ENTRYPOINT);
    }

    try {
        ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(),
                PackageManager.GET_META_DATA | PackageManager.GET_ACTIVITIES);
        Bundle metadata = activityInfo.metaData;
        return metadata != null ? metadata.getString(DART_ENTRYPOINT_META_DATA_KEY) : null;
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }
}

From source file:com.playtang.commonnavigation.login.PlayTangLoginActivity.java

private Bundle getMergedOptions() {
    // Read activity metadata from AndroidManifest.xml
    ActivityInfo activityInfo = null;//from ww w.j  a  va2  s. com
    try {
        activityInfo = getPackageManager().getActivityInfo(this.getComponentName(),
                PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        if (Parse.getLogLevel() <= Parse.LOG_LEVEL_ERROR && Log.isLoggable(LOG_TAG, Log.WARN)) {
            Log.w(LOG_TAG, e.getMessage());
        }
    }

    // The options specified in the Intent (from PlayTangLoginBuilder) will
    // override any duplicate options specified in the activity metadata
    Bundle mergedOptions = new Bundle();
    if (activityInfo != null && activityInfo.metaData != null) {
        mergedOptions.putAll(activityInfo.metaData);
    }
    if (getIntent().getExtras() != null) {
        mergedOptions.putAll(getIntent().getExtras());
    }

    return mergedOptions;
}

From source file:com.piggate.sdk.Piggate.java

public static String getMetadata(Context context, String name) {
    try {/*from ww w.j  a  v a2 s.c  o  m*/
        ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                PackageManager.GET_META_DATA);
        if (appInfo.metaData != null) {
            return appInfo.metaData.getString(name);
        }
    } catch (PackageManager.NameNotFoundException e) {
    }

    return null;
}

From source file:android.security.cts.BrowserTest.java

/**
 * Create intents for all activities that can display the given URI.
 *//*from  w w w.j  av a 2 s  .c om*/
private List<Intent> createAllIntents(Uri uri) {

    Intent implicit = new Intent(Intent.ACTION_VIEW);
    implicit.setData(uri);

    /* convert our implicit Intent into multiple explicit Intents */
    List<Intent> retval = new ArrayList<Intent>();
    PackageManager pm = mContext.getPackageManager();
    List<ResolveInfo> list = pm.queryIntentActivities(implicit, PackageManager.GET_META_DATA);
    for (ResolveInfo i : list) {
        Intent explicit = new Intent(Intent.ACTION_VIEW);
        explicit.setClassName(i.activityInfo.packageName, i.activityInfo.name);
        explicit.setData(uri);
        explicit.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        retval.add(explicit);
    }

    return retval;
}

From source file:com.sentaroh.android.TaskAutomation.TaskManager.java

final static public void initNotification(TaskManagerParms taskMgrParms, EnvironmentParms envParms) {
    String appl_ver = "";
    try {//ww w .jav a 2s .c o m
        String packegeName = taskMgrParms.context.getPackageName();
        PackageInfo packageInfo = taskMgrParms.context.getPackageManager().getPackageInfo(packegeName,
                PackageManager.GET_META_DATA);
        appl_ver = packageInfo.versionName;
    } catch (NameNotFoundException e) {
    }

    taskMgrParms.main_notification_msgs_appname = taskMgrParms.context.getString(R.string.app_name);
    taskMgrParms.main_notification_msgs_svc_active_task = taskMgrParms.main_notification_msgs_appname + " "
            + appl_ver + "   " + "T=";
    //                   "   "+taskMgrParms.context.getString(R.string.msgs_svc_active_task);
    taskMgrParms.main_notification_msgs_main_task_scheduler_not_running = taskMgrParms.context
            .getString(R.string.msgs_main_task_scheduler_not_running);
    taskMgrParms.mainNotificationManager = (NotificationManager) taskMgrParms.context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    taskMgrParms.mainNotificationManager.cancelAll();

    Intent in = new Intent(taskMgrParms.context.getApplicationContext(), ActivityTaskStatus.class);
    taskMgrParms.mainNotificationPi = PendingIntent.getActivity(taskMgrParms.context, 0, in,
            PendingIntent.FLAG_UPDATE_CURRENT);
    buildNotification(taskMgrParms, envParms);
}

From source file:com.userhook.UserHook.java

public static Notification handlePushMessage(Map<String, String> data) {

    String message = data.get("message");
    String title = "";

    if (data.containsKey("title") && data.get("title") != null) {
        title = data.get("title");
    } else {//from  w  w  w .  java2 s .  co m
        title = applicationContext.getApplicationInfo().loadLabel(applicationContext.getPackageManager())
                .toString();
    }

    Map<String, Object> payload = new HashMap<>();
    if (data.containsKey("payload")) {
        try {
            JSONObject json = new JSONObject(data.get("payload"));
            payload = UHJsonUtils.toMap(json);

            // check if this is a feedback reply
            if (json.has("new_feedback") && json.getBoolean("new_feedback")) {
                UserHook.setHasNewFeedback(true);
            } else {
                UserHook.setHasNewFeedback(false);
            }

        } catch (JSONException e) {
            Log.e("uh", "error parsing push notification payload");
        }
    }

    // message received
    Intent intent;

    if (pushMessageListener != null) {
        intent = pushMessageListener.onPushMessage(payload);
    } else {
        // default to opening the main activity
        intent = applicationContext.getPackageManager()
                .getLaunchIntentForPackage(applicationContext.getPackageName());
    }

    // convert data to a try Map<String,String> since it will come in as an ArrayMap
    if (data instanceof ArrayMap) {
        HashMap<String, String> hashMap = new HashMap<>();
        for (String key : data.keySet()) {
            hashMap.put(key, data.get(key));
        }
        data = hashMap;
    }

    intent.putExtra(UserHook.UH_PUSH_DATA, (Serializable) data);
    intent.putExtra(UserHook.UH_PUSH_TRACKED, false);
    if (payload.size() > 0) {
        intent.putExtra(UserHook.UH_PUSH_PAYLOAD, data.get("payload"));
    }

    //PendingIntent.FLAG_UPDATE_CURRENT is required to pass along our Intent Extras
    PendingIntent pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    try {
        ApplicationInfo appInfo = applicationContext.getPackageManager()
                .getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);

        int pushIcon = appInfo.icon;
        // check for a custom push icon
        if (pushNotificationIcon > 0) {
            pushIcon = pushNotificationIcon;
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext)
                .setSmallIcon(pushIcon).setContentText(message).setContentTitle(title).setAutoCancel(true)
                .setContentIntent(pendingIntent);

        // use default sound
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);

        return notificationBuilder.build();

    } catch (Exception e) {
        Log.e("uh", "error create push notification", e);
        return null;
    }

}

From source file:com.geecko.QuickLyric.broadcastReceiver.MusicBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /** Google Play Music
     //bool streaming            long position
     //long albumId               String album
     //bool currentSongLoaded      String track
     //long ListPosition         long ListSize
     //long id                  bool playing
     //long duration            int previewPlayType
     //bool supportsRating         int domain
     //bool albumArtFromService      String artist
     //int rating               bool local
     //bool preparing            bool inErrorState
     *///w w w  .j ava2  s  . c o  m

    Bundle extras = intent.getExtras();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true);

    if (extras != null)
        try {
            extras.getInt("state");
        } catch (BadParcelableException e) {
            return;
        }

    if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs
            || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000)
                    || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000)
                    || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200))
            || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000)
                    || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000)
                    || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200))
            || (extras.containsKey("com.maxmpz.audioplayer.source") && Build.VERSION.SDK_INT >= 19))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") && extras.get("position") instanceof Long
            ? extras.getLong("position")
            : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean(extras.containsKey("playstate") ? "playstate" : "playing", true);

    if (intent.getAction().equals("com.amazon.mp3.metachanged")) {
        artist = extras.getString("com.amazon.mp3.artist");
        track = extras.getString("com.amazon.mp3.track");
    } else if (intent.getAction().equals("com.spotify.music.metadatachanged"))
        isPlaying = spotifyPlaying;
    else if (intent.getAction().equals("com.spotify.music.playbackstatechanged"))
        spotifyPlaying = isPlaying;

    if ((artist == null || "".equals(artist)) //Could be problematic
            || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts
        return;

    SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    String currentArtist = current.getString("artist", "");
    String currentTrack = current.getString("track", "");

    SharedPreferences.Editor editor = current.edit();
    editor.putString("artist", artist);
    editor.putString("track", track);
    if (!(artist.equals(currentArtist) && track.equals(currentTrack) && position == -1))
        editor.putLong("position", position);
    editor.putBoolean("playing", isPlaying);
    if (isPlaying) {
        long currentTime = System.currentTimeMillis();
        editor.putLong("startTime", currentTime);
    }
    editor.apply();

    autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false);
    int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0"));

    if (autoUpdate && App.isActivityVisible()) {
        Intent internalIntent = new Intent("Broadcast");
        internalIntent.putExtra("artist", artist).putExtra("track", track);
        LyricsViewFragment.sendIntent(context, internalIntent);
        forceAutoUpdate(false);
    }

    boolean inDatabase = DatabaseHelper.getInstance(context)
            .presenceCheck(new String[] { artist, track, artist, track });

    if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) {
        Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS",
                new String[] { artist, track });
        Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist)
                .putExtra("track", track);
        PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch,
                context.getString(R.string.wearable_prompt), wearablePending).build();

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
        NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context);

        int[] themes = new int[] { R.style.Theme_QuickLyric, R.style.Theme_QuickLyric_Red,
                R.style.Theme_QuickLyric_Purple, R.style.Theme_QuickLyric_Indigo,
                R.style.Theme_QuickLyric_Green, R.style.Theme_QuickLyric_Lime, R.style.Theme_QuickLyric_Brown,
                R.style.Theme_QuickLyric_Dark };
        int themeNum = Integer.valueOf(sharedPref.getString("pref_theme", "0"));

        TypedValue primaryColorValue = new TypedValue();
        context.setTheme(themes[themeNum]);
        context.getTheme().resolveAttribute(R.attr.colorPrimary, primaryColorValue, true);

        notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setColor(primaryColorValue.data).setGroupSummary(true);

        wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setOngoing(false).setColor(primaryColorValue.data)
                .setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
            wearableNotifBuilder.setPriority(-2);
        } else
            notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW

        Notification notif = notifBuilder.build();
        Notification wearableNotif = wearableNotifBuilder.build();

        if (notificationPref == 2)
            notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        else
            notif.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat.from(context).notify(0, notif);
        try {
            context.getPackageManager().getPackageInfo("com.google.android.wearable.app",
                    PackageManager.GET_META_DATA);
            NotificationManagerCompat.from(context).notify(8, wearableNotif);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    } else if (track.equals(current.getString("track", "")))
        NotificationManagerCompat.from(context).cancel(0);
}

From source file:com.onegravity.contactpicker.core.ContactPickerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // check if all custom attributes are defined
    if (!checkTheming()) {
        finish();//from  www .  j  a va2 s  .c om
        return;
    }

    /*
     * Check if we have the READ_CONTACTS permission, if not --> terminate.
     */
    try {
        int pid = android.os.Process.myPid();
        PackageManager pckMgr = getPackageManager();
        int uid = pckMgr.getApplicationInfo(getComponentName().getPackageName(),
                PackageManager.GET_META_DATA).uid;
        enforcePermission(Manifest.permission.READ_CONTACTS, pid, uid,
                "Contact permission hasn't been granted to this app, terminating.");
    } catch (PackageManager.NameNotFoundException | SecurityException e) {
        Log.e(getClass().getSimpleName(), e.getMessage());
        finish();
        return;
    }

    mDefaultTitle = "Select Contacts";

    mThemeResId = R.style.Theme_Light;

    Intent intent = getIntent();
    if (savedInstanceState == null) {
        //            /*
        //             * Retrieve default title used if no contacts are selected.
        //             */
        //            try {
        //                PackageManager pkMgr = getPackageManager();
        //                ActivityInfo activityInfo = pkMgr.getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
        //                mDefaultTitle = activityInfo.loadLabel(pkMgr).toString();
        //            }
        //            catch (PackageManager.NameNotFoundException ignore) {
        //                mDefaultTitle = getTitle().toString();
        //            }

        if (intent.hasExtra(EXTRA_PRESELECTED_CONTACTS)) {
            Collection<Long> preselectedContacts = (Collection<Long>) intent
                    .getSerializableExtra(EXTRA_PRESELECTED_CONTACTS);
            mSelectedContactIds.addAll(preselectedContacts);
        }

        if (intent.hasExtra(EXTRA_PRESELECTED_GROUPS)) {
            Collection<Long> preselectedGroups = (Collection<Long>) intent
                    .getSerializableExtra(EXTRA_PRESELECTED_GROUPS);
            mSelectedGroupIds.addAll(preselectedGroups);
        }

        //            mThemeResId = intent.getIntExtra(EXTRA_THEME, R.style.ContactPicker_Theme_Light);
    } else {
        //            mDefaultTitle = savedInstanceState.getString("mDefaultTitle");
        //
        //            mThemeResId = savedInstanceState.getInt("mThemeResId");

        // Retrieve selected contact and group ids.
        try {
            mSelectedContactIds = (HashSet<Long>) savedInstanceState.getSerializable(CONTACT_IDS);
            mSelectedGroupIds = (HashSet<Long>) savedInstanceState.getSerializable(GROUP_IDS);
        } catch (ClassCastException ignore) {
        }
    }

    /*
     * Retrieve ContactPictureType.
     */
    String enumName = intent.getStringExtra(EXTRA_CONTACT_BADGE_TYPE);
    mBadgeType = ContactPictureType.lookup(enumName);

    /*
     * Retrieve SelectContactsLimit.
     */
    mSelectContactsLimit = intent.getIntExtra(EXTRA_SELECT_CONTACTS_LIMIT, 0);

    /*
     * Retrieve ShowCheckAll.
     */
    mShowCheckAll = mSelectContactsLimit > 0 ? false : intent.getBooleanExtra(EXTRA_SHOW_CHECK_ALL, true);

    /*
     * Retrieve OnlyWithPhoneNumbers.
     */
    mOnlyWithPhoneNumbers = intent.getBooleanExtra(EXTRA_ONLY_CONTACTS_WITH_PHONE, false);

    /*
     * Retrieve LimitReachedMessage.
     */
    String limitMsg = intent.getStringExtra(EXTRA_LIMIT_REACHED_MESSAGE);
    if (limitMsg != null) {
        mLimitReachedMessage = limitMsg;
    } else {
        mLimitReachedMessage = getString(R.string.cp_limit_reached, mSelectContactsLimit);
    }

    /*
     * Retrieve ContactDescription.
     */
    enumName = intent.getStringExtra(EXTRA_CONTACT_DESCRIPTION);
    mDescription = ContactDescription.lookup(enumName);
    mDescriptionType = intent.getIntExtra(EXTRA_CONTACT_DESCRIPTION_TYPE,
            ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME);

    /*
     * Retrieve ContactSortOrder.
     */
    enumName = intent.getStringExtra(EXTRA_CONTACT_SORT_ORDER);
    mSortOrder = ContactSortOrder.lookup(enumName);

    setTheme(mThemeResId);
    setContentView(R.layout.cp_contact_tab_layout);

    // initialize TabLayout
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabContent);
    tabLayout.setTabMode(TabLayout.MODE_FIXED);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    TabLayout.Tab tabContacts = tabLayout.newTab();
    tabContacts.setText(R.string.cp_contact_tab_title);
    tabLayout.addTab(tabContacts);

    TabLayout.Tab tabGroups = tabLayout.newTab();
    tabGroups.setText(R.string.cp_group_tab_title);
    tabLayout.addTab(tabGroups);

    // initialize ViewPager
    final ViewPager viewPager = (ViewPager) findViewById(R.id.tabPager);
    mAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), mSortOrder, mBadgeType,
            mDescription, mDescriptionType);
    viewPager.setAdapter(mAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

From source file:com.rp.podemu.MainActivity.java

private void loadPreferences() {
    try {//  w ww  .  ja v a2s.c  om
        ImageView appLogo = (ImageView) findViewById(R.id.CTRL_app_icon);
        SharedPreferences sharedPref = this.getSharedPreferences("PODEMU_PREFS", Context.MODE_PRIVATE);
        ctrlAppProcessName = sharedPref.getString("ControlledAppProcessName", "unknown app");
        String enableDebug = sharedPref.getString("enableDebug", "false");
        Boolean ctrlAppUpdated = sharedPref.getBoolean("ControlledAppUpdated", false);

        if (PodEmuMediaStore.getInstance() == null) {
            PodEmuMediaStore.initialize(this);
        }

        // update ctrlApp only if it was changed or MediaPlayback engine is not yet initialized
        if (ctrlAppUpdated || MediaPlayback.getInstance() == null) {
            PodEmuMediaStore.getInstance().setCtrlAppProcessName(ctrlAppProcessName);
        }

        if (enableDebug.equals("true"))
            PodEmuLog.DEBUG_LEVEL = 2;
        else
            PodEmuLog.DEBUG_LEVEL = 0;

        if (podEmuService != null) {
            podEmuService.reloadBaudRate();
        }

        if (MediaPlayback.getInstance() != null) {
            currentlyPlaying.bulk_update(
                    MediaPlayback.getInstance().getCurrentPlaylist().getCurrentTrack().toPodEmuMessage());
            updateCurrentlyPlayingDisplay();
        }

        PackageManager pm = getPackageManager();
        ApplicationInfo appInfo;

        try {
            appInfo = pm.getApplicationInfo(ctrlAppProcessName, PackageManager.GET_META_DATA);

            ctrlAppStatusTitle.setText("Controlled app: " + appInfo.loadLabel(pm));
            ctrlAppStatusTitle.setTextColor(Color.rgb(0xff, 0xff, 0xff));

            if (ctrlAppUpdated && currentlyPlaying.isPlaying()) {
                // invoke play_pause button to switch the app
                MediaPlayback mediaPlayback = MediaPlayback.getInstance();
                mediaPlayback.action_play_pause();
            }
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putBoolean("ControlledAppUpdated", false);
            editor.apply();

            appLogo.setImageDrawable(appInfo.loadIcon(pm));
        } catch (PackageManager.NameNotFoundException e) {
            ctrlAppStatusTitle.setText("Please go to the settings and setup controlled music application");
            ctrlAppStatusTitle.setTextColor(Color.rgb(0xff, 0x00, 0x00));

            appLogo.setImageDrawable(ContextCompat.getDrawable(this, (R.drawable.questionmark)));
        }
    } catch (Exception e) {
        PodEmuLog.printStackTrace(e);
        throw e;
    }

}