Example usage for android.content.res Resources getString

List of usage examples for android.content.res Resources getString

Introduction

In this page you can find the example usage for android.content.res Resources getString.

Prototype

@NonNull
public String getString(@StringRes int id) throws NotFoundException 

Source Link

Document

Return the string value associated with a particular resource ID.

Usage

From source file:com.customdatepicker.time.RadialTextsView.java

public void initialize(Context context, String[] texts, String[] innerTexts, TimePickerController controller,
        SelectionValidator validator, boolean disappearsOut) {
    if (mIsInitialized) {
        Log.e(TAG, "This RadialTextsView may only be initialized once.");
        return;/*from  ww w  .ja  v a 2  s.  c om*/
    }
    Resources res = context.getResources();

    // Set up the paint.
    int textColorRes = controller.isThemeDark() ? R.color.mdtp_white : R.color.mdtp_numbers_text_color;
    mPaint.setColor(ContextCompat.getColor(context, textColorRes));
    String typefaceFamily = res.getString(R.string.mdtp_radial_numbers_typeface);
    mTypefaceLight = Typeface.create(typefaceFamily, Typeface.NORMAL);
    String typefaceFamilyRegular = res.getString(R.string.mdtp_sans_serif);
    mTypefaceRegular = Typeface.create(typefaceFamilyRegular, Typeface.NORMAL);
    mPaint.setAntiAlias(true);
    mPaint.setTextAlign(Align.CENTER);

    // Set up the selected paint
    int selectedTextColor = ContextCompat.getColor(context, R.color.mdtp_white);
    mSelectedPaint.setColor(selectedTextColor);
    mSelectedPaint.setAntiAlias(true);
    mSelectedPaint.setTextAlign(Align.CENTER);

    // Set up the inactive paint
    int inactiveColorRes = controller.isThemeDark() ? R.color.mdtp_date_picker_text_disabled_dark_theme
            : R.color.mdtp_date_picker_text_disabled;
    mInactivePaint.setColor(ContextCompat.getColor(context, inactiveColorRes));
    mInactivePaint.setAntiAlias(true);
    mInactivePaint.setTextAlign(Align.CENTER);

    mTexts = texts;
    mInnerTexts = innerTexts;
    mIs24HourMode = controller.is24HourMode();
    mHasInnerCircle = (innerTexts != null);

    // Calculate the radius for the main circle.
    if (mIs24HourMode || controller.getVersion() != TimePickerDialog.Version.VERSION_1) {
        mCircleRadiusMultiplier = Float
                .parseFloat(res.getString(R.string.mdtp_circle_radius_multiplier_24HourMode));
    } else {
        mCircleRadiusMultiplier = Float.parseFloat(res.getString(R.string.mdtp_circle_radius_multiplier));
        mAmPmCircleRadiusMultiplier = Float
                .parseFloat(res.getString(R.string.mdtp_ampm_circle_radius_multiplier));
    }

    // Initialize the widths and heights of the grid, and calculate the values for the numbers.
    mTextGridHeights = new float[7];
    mTextGridWidths = new float[7];
    if (mHasInnerCircle) {
        mNumbersRadiusMultiplier = Float
                .parseFloat(res.getString(R.string.mdtp_numbers_radius_multiplier_outer));
        mTextSizeMultiplier = Float.parseFloat(res.getString(R.string.mdtp_text_size_multiplier_outer));
        mInnerNumbersRadiusMultiplier = Float
                .parseFloat(res.getString(R.string.mdtp_numbers_radius_multiplier_inner));
        mInnerTextSizeMultiplier = Float.parseFloat(res.getString(R.string.mdtp_text_size_multiplier_inner));

        mInnerTextGridHeights = new float[7];
        mInnerTextGridWidths = new float[7];
    } else {
        mNumbersRadiusMultiplier = Float
                .parseFloat(res.getString(R.string.mdtp_numbers_radius_multiplier_normal));
        mTextSizeMultiplier = Float.parseFloat(res.getString(R.string.mdtp_text_size_multiplier_normal));
    }

    mAnimationRadiusMultiplier = 1;
    mTransitionMidRadiusMultiplier = 1f + (0.05f * (disappearsOut ? -1 : 1));
    mTransitionEndRadiusMultiplier = 1f + (0.3f * (disappearsOut ? 1 : -1));
    mInvalidateUpdateListener = new InvalidateUpdateListener();

    mValidator = validator;

    mTextGridValuesDirty = true;
    mIsInitialized = true;
}

From source file:com.brewcrewfoo.performance.fragments.Tools.java

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    final String key = preference.getKey();

    if (key.equals(PREF_SH)) {
        Resources res = context.getResources();
        String cancel = res.getString(R.string.cancel);
        String ok = res.getString(R.string.ps_volt_save);

        LayoutInflater factory = LayoutInflater.from(context);
        final View alphaDialog = factory.inflate(R.layout.sh_dialog, null);

        settingText = (EditText) alphaDialog.findViewById(R.id.shText);
        settingText.setHint(R.string.sh_msg);
        settingText.setText(mPreferences.getString(key, ""));
        settingText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override//from   w  w  w.java  2s . c o  m
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return true;
            }
        });

        new AlertDialog.Builder(context).setTitle(getString(R.string.sh_title)).setView(alphaDialog)
                .setNegativeButton(cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        /* nothing */
                    }
                }).setPositiveButton(ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final SharedPreferences.Editor editor = mPreferences.edit();
                        editor.putString(key, settingText.getText().toString()).commit();

                    }
                }).create().show();

    } else if (key.equals(PREF_WIPE_CACHE)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(getString(R.string.wipe_cache_title)).setMessage(getString(R.string.wipe_cache_msg))
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //alertDialog.setCancelable(false);
        Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        theButton.setOnClickListener(new opListener(alertDialog, 0));

    } else if (key.equals(FLASH_KERNEL)) {
        Intent flash = new Intent(context, FlasherActivity.class);
        flash.putExtra("mod", "kernel");
        startActivity(flash);
    } else if (key.equals(RESIDUAL_FILES)) {
        Intent intent = new Intent(context, ResidualsActivity.class);
        startActivity(intent);
    } else if (key.equals(PREF_FIX_PERMS)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(getString(R.string.fix_perms_title)).setMessage(getString(R.string.fix_perms_msg))
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //alertDialog.setCancelable(false);

        Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        theButton.setOnClickListener(new opListener(alertDialog, 1));

    } else if (key.equals(PREF_OPTIM_DB)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(getString(R.string.optim_db_title))
                .setMessage(getString(R.string.ps_optim_db) + "\n\n" + getString(R.string.fix_perms_msg))
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //alertDialog.setCancelable(false);
        Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        theButton.setOnClickListener(new opListener(alertDialog, 2));
    } else if (key.equals(PREF_FRREZE)) {
        Intent intent = new Intent(context, FreezerActivity.class);
        intent.putExtra("freeze", true);
        intent.putExtra("packs", "usr");
        startActivity(intent);
    } else if (key.equals(PREF_UNFRREZE)) {
        Intent intent = new Intent(context, FreezerActivity.class);
        intent.putExtra("freeze", false);
        startActivity(intent);
    } else if (key.equals("pref_build_prop")) {
        Intent intent = new Intent(context, BuildPropEditor.class);
        startActivity(intent);
    } else if (key.equals("pref_sysctl")) {
        Intent intent = new Intent(context, SysctlEditor.class);
        startActivity(intent);
    } else if (key.equals("pref_logcat")) {

        Date now = new Date();
        nf = "/logcat_" + formatter.format(now) + ".txt";
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(getString(R.string.logcat_title)).setMessage(getString(R.string.logcat_msg, dn + nf))
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //alertDialog.setCancelable(false);
        Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        theButton.setOnClickListener(new opListener(alertDialog, 3));
    } else if (key.equals("pref_dmesg")) {

        Date now = new Date();
        nf = "/dmesg_" + formatter.format(now) + ".txt";
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(getString(R.string.dmesg_title)).setMessage(getString(R.string.dmesg_msg, dn + nf))
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //alertDialog.setCancelable(false);
        Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        theButton.setOnClickListener(new opListener(alertDialog, 4));
    }
    return super.onPreferenceTreeClick(preferenceScreen, preference);
}

From source file:br.com.frs.foodrestrictions.MessageCannibal.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_message_cannibal, container, false);

    String language = getArguments().getString(MessageLanguageSelector.ARG_LANGUAGE);

    TextView tv = (TextView) v.findViewById(R.id.tvCannibal);

    /* Getting the current resource  and config info */
    Resources rsc = v.getContext().getResources();
    Configuration config = rsc.getConfiguration();
    /* Saving the original locale before changing to the new one
     * just to show the texts/* www .j a  va2s.  com*/
     */
    Locale orgLocale = config.locale;

    /* Changing the language to the one the user have selected based on the
     * Languages.xml file
     */
    if (language != null) {
        config.locale = new Locale(language);
    }

    /* Setting the new locale */
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
    /* Updating the layout with the new selected language */
    tv.setText(rsc.getString(R.string.msg_joke_cannibal));

    /* Return to last locale to keep the app as it was before */
    config.locale = orgLocale;
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());

    return v;
}

From source file:com.hichinaschool.flashcards.anki.Feedback.java

/**
 * Create AlertDialogs used on all the activity
 */// w w  w. java  2 s. com
private void initAllAlertDialogs() {
    Resources res = getResources();

    StyledDialog.Builder builder = new StyledDialog.Builder(this);

    builder.setTitle(res.getString(R.string.connection_error_title));
    builder.setIcon(R.drawable.ic_dialog_alert);
    builder.setMessage(res.getString(R.string.connection_needed));
    builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            mPostingFeedback = false;
            refreshInterface();
        }
    });
    mNoConnectionAlert = builder.create();
}

From source file:com.codetroopers.betterpickers.radialtimepicker.RadialTextsView.java

public void initialize(Resources res, String[] texts, String[] innerTexts, boolean is24HourMode,
        boolean disappearsOut) {
    if (mIsInitialized) {
        Log.e(TAG, "This RadialTextsView may only be initialized once.");
        return;// w  w w . j ava 2  s  . com
    }

    // Set up the paint.
    mPaint.setColor(res.getColor(R.color.numbers_text_color));
    String typefaceFamily = res.getString(R.string.radial_numbers_typeface);
    mTypefaceLight = Typeface.create(typefaceFamily, Typeface.NORMAL);
    String typefaceFamilyRegular = res.getString(R.string.sans_serif);
    mTypefaceRegular = Typeface.create(typefaceFamilyRegular, Typeface.NORMAL);
    mPaint.setAntiAlias(true);
    mPaint.setTextAlign(Align.CENTER);

    mTexts = texts;
    mInnerTexts = innerTexts;
    mIs24HourMode = is24HourMode;
    mHasInnerCircle = (innerTexts != null);

    // Calculate the radius for the main circle.
    if (is24HourMode) {
        mCircleRadiusMultiplier = Float.parseFloat(res.getString(R.string.circle_radius_multiplier_24HourMode));
    } else {
        mCircleRadiusMultiplier = Float.parseFloat(res.getString(R.string.circle_radius_multiplier));
        mAmPmCircleRadiusMultiplier = Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
    }

    // Initialize the widths and heights of the grid, and calculate the values for the numbers.
    mTextGridHeights = new float[7];
    mTextGridWidths = new float[7];
    if (mHasInnerCircle) {
        mNumbersRadiusMultiplier = Float.parseFloat(res.getString(R.string.numbers_radius_multiplier_outer));
        mTextSizeMultiplier = Float.parseFloat(res.getString(R.string.text_size_multiplier_outer));
        mInnerNumbersRadiusMultiplier = Float
                .parseFloat(res.getString(R.string.numbers_radius_multiplier_inner));
        mInnerTextSizeMultiplier = Float.parseFloat(res.getString(R.string.text_size_multiplier_inner));

        mInnerTextGridHeights = new float[7];
        mInnerTextGridWidths = new float[7];
    } else {
        mNumbersRadiusMultiplier = Float.parseFloat(res.getString(R.string.numbers_radius_multiplier_normal));
        mTextSizeMultiplier = Float.parseFloat(res.getString(R.string.text_size_multiplier_normal));
    }

    mAnimationRadiusMultiplier = 1;
    mTransitionMidRadiusMultiplier = 1f + (0.05f * (disappearsOut ? -1 : 1));
    mTransitionEndRadiusMultiplier = 1f + (0.3f * (disappearsOut ? 1 : -1));
    mInvalidateUpdateListener = new InvalidateUpdateListener();

    mTextGridValuesDirty = true;
    mIsInitialized = true;
}

From source file:com.google.android.apps.muzei.settings.SettingsChooseSourceFragment.java

public void updateSources() {
    mSelectedSource = null;/*from  w w w  .  ja  v a  2  s  . co m*/
    Intent queryIntent = new Intent(ACTION_MUZEI_ART_SOURCE);
    PackageManager pm = getActivity().getPackageManager();
    mSources.clear();
    List<ResolveInfo> resolveInfos = pm.queryIntentServices(queryIntent, PackageManager.GET_META_DATA);

    for (ResolveInfo ri : resolveInfos) {
        Source source = new Source();
        source.label = ri.loadLabel(pm).toString();
        source.icon = new BitmapDrawable(getResources(), generateSourceImage(ri.loadIcon(pm)));
        source.componentName = new ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name);
        if (ri.serviceInfo.descriptionRes != 0) {
            try {
                Context packageContext = getActivity()
                        .createPackageContext(source.componentName.getPackageName(), 0);
                Resources packageRes = packageContext.getResources();
                source.description = packageRes.getString(ri.serviceInfo.descriptionRes);
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(TAG, "Can't read package resources for source " + source.componentName);
            }
        }
        Bundle metaData = ri.serviceInfo.metaData;
        source.color = Color.WHITE;
        if (metaData != null) {
            String settingsActivity = metaData.getString("settingsActivity");
            if (!TextUtils.isEmpty(settingsActivity)) {
                source.settingsActivity = ComponentName
                        .unflattenFromString(ri.serviceInfo.packageName + "/" + settingsActivity);
            }

            String setupActivity = metaData.getString("setupActivity");
            if (!TextUtils.isEmpty(setupActivity)) {
                source.setupActivity = ComponentName
                        .unflattenFromString(ri.serviceInfo.packageName + "/" + setupActivity);
            }

            source.color = metaData.getInt("color", source.color);

            try {
                float[] hsv = new float[3];
                Color.colorToHSV(source.color, hsv);
                boolean adjust = false;
                if (hsv[2] < 0.8f) {
                    hsv[2] = 0.8f;
                    adjust = true;
                }
                if (hsv[1] > 0.4f) {
                    hsv[1] = 0.4f;
                    adjust = true;
                }
                if (adjust) {
                    source.color = Color.HSVToColor(hsv);
                }
                if (Color.alpha(source.color) != 255) {
                    source.color = Color.argb(255, Color.red(source.color), Color.green(source.color),
                            Color.blue(source.color));
                }
            } catch (IllegalArgumentException ignored) {
            }
        }

        mSources.add(source);
    }

    final String appPackage = getActivity().getPackageName();
    Collections.sort(mSources, new Comparator<Source>() {
        @Override
        public int compare(Source s1, Source s2) {
            String pn1 = s1.componentName.getPackageName();
            String pn2 = s2.componentName.getPackageName();
            if (!pn1.equals(pn2)) {
                if (appPackage.equals(pn1)) {
                    return -1;
                } else if (appPackage.equals(pn2)) {
                    return 1;
                }
            }
            return s1.label.compareTo(s2.label);
        }
    });

    redrawSources();
}

From source file:org.runnerup.export.RunKeeperSynchronizer.java

private double getLapLength() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Resources res = context.getResources();
    double lapLength = Formatter.getUnitMeters(context);
    if (prefs.getBoolean(res.getString(R.string.pref_autolap_active), false)) {
        String autoLap = prefs.getString(res.getString(R.string.pref_autolap), String.valueOf(lapLength));
        try {//  w  w  w .  j  a v  a 2 s  .c om
            lapLength = Double.parseDouble(autoLap);
        } catch (NumberFormatException e) {
            return lapLength;
        }
        return lapLength;
    }
    return lapLength;
}

From source file:com.openerp.MainActivity.java

private List<DrawerItem> setSettingMenu() {
    List<DrawerItem> sys = new ArrayList<DrawerItem>();
    String key = "com.openerp.settings";
    Resources r = getResources();
    sys.add(new DrawerItem(key, r.getString(R.string.title_settings), true));
    sys.add(new DrawerItem(key, r.getString(R.string.title_profile), 0, R.drawable.ic_action_user,
            getFragBundle(new Fragment(), "settings", SettingKeys.PROFILE)));

    sys.add(new DrawerItem(key, r.getString(R.string.title_general_settings), 0, R.drawable.ic_action_settings,
            getFragBundle(new Fragment(), "settings", SettingKeys.GLOBAL_SETTING)));

    sys.add(new DrawerItem(key, r.getString(R.string.title_accounts), 0, R.drawable.ic_action_accounts,
            getFragBundle(new Fragment(), "settings", SettingKeys.ACCOUNTS)));
    sys.add(new DrawerItem(key, r.getString(R.string.title_about_us), 0, R.drawable.ic_action_about,
            getFragBundle(new Fragment(), "settings", SettingKeys.ABOUT_US)));
    return sys;/* w w w .ja  va 2  s. c  o  m*/
}

From source file:com.androidinspain.deskclock.alarms.AlarmNotifications.java

static synchronized void showAlarmNotification(Service service, AlarmInstance instance) {
    LogUtils.v("Displaying alarm notification for alarm instance: " + instance.mId);

    Resources resources = service.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(service)
            .setContentTitle(instance.getLabelOrDefault(service))
            .setContentText(AlarmUtils.getFormattedTime(service, instance.getAlarmTime()))
            .setColor(ContextCompat.getColor(service, com.androidinspain.deskclock.R.color.default_background))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm).setOngoing(true)
            .setAutoCancel(false).setDefaults(NotificationCompat.DEFAULT_LIGHTS).setWhen(0)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);/*from   w w  w  .ja va2  s. com*/

    // Setup Snooze Action
    Intent snoozeIntent = AlarmStateManager.createStateChangeIntent(service, AlarmStateManager.ALARM_SNOOZE_TAG,
            instance, AlarmInstance.SNOOZE_STATE);
    snoozeIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent snoozePendingIntent = PendingIntent.getService(service, ALARM_FIRING_NOTIFICATION_ID,
            snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(com.androidinspain.deskclock.R.drawable.ic_snooze_24dp,
            resources.getString(com.androidinspain.deskclock.R.string.alarm_alert_snooze_text),
            snoozePendingIntent);

    // Setup Dismiss Action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(service,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    dismissIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent dismissPendingIntent = PendingIntent.getService(service, ALARM_FIRING_NOTIFICATION_ID,
            dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(com.androidinspain.deskclock.R.drawable.ic_alarm_off_24dp,
            resources.getString(com.androidinspain.deskclock.R.string.alarm_alert_dismiss_text),
            dismissPendingIntent);

    // Setup Content Action
    Intent contentIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    notification.setContentIntent(PendingIntent.getActivity(service, ALARM_FIRING_NOTIFICATION_ID,
            contentIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup fullscreen intent
    Intent fullScreenIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    // set action, so we can be different then content pending intent
    fullScreenIntent.setAction("fullscreen_activity");
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    notification.setFullScreenIntent(PendingIntent.getActivity(service, ALARM_FIRING_NOTIFICATION_ID,
            fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT), true);
    notification.setPriority(NotificationCompat.PRIORITY_MAX);

    clearNotification(service, instance);
    service.startForeground(ALARM_FIRING_NOTIFICATION_ID, notification.build());
}

From source file:at.flack.receiver.EMailReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();/*from  www  . j  a v  a 2 s  . co m*/
    try {
        if (bundle.getString("type").equals("mail")) {
            sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            if (!sharedPrefs.getBoolean("notification_mail", true))
                return;
            notify = sharedPrefs.getBoolean("notifications", true);
            vibrate = sharedPrefs.getBoolean("vibration", true);
            headsup = sharedPrefs.getBoolean("headsup", true);
            led_color = sharedPrefs.getInt("notification_light", -16776961);
            boolean all = sharedPrefs.getBoolean("all_mail", true);

            if (notify == false)
                return;

            NotificationCompat.Builder mBuilder = null;
            boolean use_profile_picture = false;
            Bitmap profile_picture = null;

            String origin_name = bundle.getString("senderName").equals("") ? bundle.getString("senderMail")
                    : bundle.getString("senderName");

            try {
                profile_picture = RoundedImageView.getCroppedBitmap(Bitmap.createScaledBitmap(
                        ProfilePictureCache.getInstance(context).get(origin_name), 200, 200, false), 300);
                use_profile_picture = true;
            } catch (Exception e) {
                use_profile_picture = false;
            }

            Resources res = context.getResources();

            int lastIndex = bundle.getString("subject").lastIndexOf("=");
            if (lastIndex > 0 && Base64.isBase64(bundle.getString("subject").substring(0, lastIndex))) {
                mBuilder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                        .setColor(0xFFFF5722)
                        .setContentText(res.getString(R.string.sms_receiver_new_encrypted_mail))
                        .setAutoCancel(true);
                if (use_profile_picture && profile_picture != null) {
                    mBuilder = mBuilder.setLargeIcon(profile_picture);
                } else {
                    mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                            context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                }
            } else {

                if (bundle.getString("subject").charAt(0) == '%' && (bundle.getString("subject").length() == 10
                        || bundle.getString("subject").length() == 9)) {
                    if (lastIndex > 0 && Base64.isBase64(bundle.getString("subject").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFFFF5722)
                                .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                                .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
                        if (use_profile_picture && profile_picture != null) {
                            mBuilder = mBuilder.setLargeIcon(profile_picture);
                        } else {
                            mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                    context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                        }
                    } else {
                        return;
                    }
                } else if (bundle.getString("subject").charAt(0) == '%'
                        && bundle.getString("subject").length() >= 120
                        && bundle.getString("subject").length() < 125) {
                    if (lastIndex > 0 && Base64.isBase64(bundle.getString("subject").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFFFF5722)
                                .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                                .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
                        if (use_profile_picture && profile_picture != null) {
                            mBuilder = mBuilder.setLargeIcon(profile_picture);
                        } else {
                            mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                    context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                        }
                    } else {
                        return;
                    }
                } else if (all) { // normal message
                    mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                            .setColor(0xFFFF5722).setContentText(bundle.getString("subject"))
                            .setAutoCancel(true).setStyle(
                                    new NotificationCompat.BigTextStyle().bigText(bundle.getString("subject")));

                    if (use_profile_picture && profile_picture != null) {
                        mBuilder = mBuilder.setLargeIcon(profile_picture);
                    } else {
                        mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                    }
                } else {
                    return;
                }
            }
            // }
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(alarmSound);
            mBuilder.setLights(led_color, 750, 4000);
            if (vibrate) {
                mBuilder.setVibrate(new long[] { 0, 100, 200, 300 });
            }

            Intent resultIntent = new Intent(context, MainActivity.class);
            resultIntent.putExtra("MAIL", bundle.getString("senderMail"));

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(1,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            if (Build.VERSION.SDK_INT >= 16 && headsup)
                mBuilder.setPriority(Notification.PRIORITY_HIGH);
            if (Build.VERSION.SDK_INT >= 21)
                mBuilder.setCategory(Notification.CATEGORY_MESSAGE);

            final NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);

            if (!MainActivity.isOnTop)
                mNotificationManager.notify(9, mBuilder.build());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}