Example usage for android.content.res Resources getText

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

Introduction

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

Prototype

@NonNull
public CharSequence getText(@StringRes int id) throws NotFoundException 

Source Link

Document

Return the string value associated with a particular resource ID.

Usage

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

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

From source file:net.sourceforge.servestream.service.AppWidgetOneProvider.java

/**
 * Update all active widget instances by pushing changes 
 *//*from  ww w .  j a v  a 2  s. c  o  m*/
public void performUpdate(MediaPlaybackService service, int[] appWidgetIds, String what) {
    final Resources res = service.getResources();
    final RemoteViews views = new RemoteViews(service.getPackageName(), R.layout.appwidget_one);

    if (what.equals(MediaPlaybackService.PLAYER_CLOSED)) {
        defaultAppWidget(service, appWidgetIds);
    } else {
        CharSequence trackName = service.getTrackName();
        CharSequence artistName = service.getArtistName();
        //CharSequence errorState = null;

        if (trackName == null || trackName.equals(Media.UNKNOWN_STRING)) {
            trackName = res.getText(R.string.widget_one_track_info_unavailable);
        }

        if (artistName == null || artistName.equals(Media.UNKNOWN_STRING)) {
            artistName = service.getMediaUri();
        }

        // Show media info
        views.setViewVisibility(R.id.title, View.VISIBLE);
        views.setTextViewText(R.id.title, trackName);
        views.setViewVisibility(R.id.artist, View.VISIBLE);
        views.setTextViewText(R.id.artist, artistName);

        // Set correct drawable for pause state
        final boolean playing = service.isPlaying();
        if (playing) {
            views.setImageViewResource(R.id.control_play, android.R.drawable.ic_media_pause);
        } else {
            views.setImageViewResource(R.id.control_play, android.R.drawable.ic_media_play);
        }

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap b = BitmapFactory.decodeStream(
                service.getResources().openRawResource(R.drawable.albumart_mp_unknown_widget), null, opts);

        views.setImageViewBitmap(R.id.coverart, b);

        if (service.getAudioId() >= 0) {
            views.setImageViewBitmap(R.id.coverart, service.getAlbumArt(true));
        }

        // Link actions buttons to intents
        linkButtons(service, views, true);
        pushUpdate(service, appWidgetIds, views);
    }
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

private void setFinishedNotification() {
    Intent notificationIntent = new Intent(getApplicationContext(), RMBTMainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent openAppIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    final Resources res = getResources();
    final Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.stat_icon_loop)
            .setContentTitle(res.getText(R.string.loop_notification_finished_title))
            .setTicker(res.getText(R.string.loop_notification_finished_ticker)).setContentIntent(openAppIntent)
            .build();//  w w w  . ja  v a2  s .c  o m

    //notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(NotificationIDs.LOOP_ACTIVE, notification);
}

From source file:at.alladin.rmbt.android.test.RMBTService.java

private void addNotificationIfTestRunning() {
    if (isTestRunning() && !bound) {
        final Resources res = getResources();

        final PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(getApplicationContext(), RMBTMainActivity.class), 0);

        final Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.stat_icon_test)
                .setContentTitle(res.getText(R.string.test_notification_title))
                .setContentText(res.getText(R.string.test_notification_text))
                .setTicker(res.getText(R.string.test_notification_ticker)).setContentIntent(contentIntent)
                .build();/*from  ww w.  j  ava2 s .c  om*/

        startForeground(NotificationIDs.TEST_RUNNING, notification);
    }
}

From source file:org.ulteo.ovd.AndRdpActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void startSession(int screen_width, int screen_height) {
    if (isConnected())
        return;//from  ww w.  j  a  v  a  2 s . c o  m

    Bundle bundle = getIntent().getExtras();

    if (bundle == null) {
        finish();
        return;
    }

    Point res;
    // check if user has chosen a specific resolution
    if (!Settings.getResolutionAuto(this)) {
        res = Settings.getResolution(this);
    } else {
        res = new Point(screen_width, screen_height);
        // Prefer wide screen
        if (!Settings.getResolutionWide(this) && res.y > res.x) {
            int w = res.x;
            res.x = res.y;
            res.y = w;
        }
    }
    Log.i(Config.TAG, "Resolution: " + res.x + "x" + res.y);

    String gateway_token = null;
    Boolean gateway_mode = bundle.getBoolean(PARAM_GATEWAYMODE);
    if (gateway_mode)
        gateway_token = bundle.getString(PARAM_TOKEN);

    int drives = Properties.REDIRECT_DRIVES_FULL;
    Properties prop = smHandler.getResponseProperties();
    if (prop != null)
        drives = prop.isDrives();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN
            && bundle.getString(PARAM_SM_URI) != null) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null) {
            NdefRecord rtdUriRecord = NdefRecord.createUri(bundle.getString(PARAM_SM_URI));
            NdefMessage ndefMessage = new NdefMessage(rtdUriRecord);
            nfcAdapter.setNdefPushMessage(ndefMessage, this);
        }
    }

    rdp = new Rdp(res, bundle.getString(PARAM_LOGIN), bundle.getString(PARAM_PASSWD),
            bundle.getString(PARAM_IP), bundle.getInt(PARAM_PORT, SessionManagerCommunication.DEFAULT_RDP_PORT),
            gateway_mode, gateway_token, drives,
            bundle.getString(PARAM_RDPSHELL) == null ? "" : bundle.getString(PARAM_RDPSHELL),
            Settings.getBulkCompression(AndRdpActivity.this), Settings.getConnexionType(AndRdpActivity.this));

    Resources resources = getResources();
    Intent notificationIntent = new Intent(this, AndRdpActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon_bw)
            .setContentTitle(resources.getText(R.string.app_name)).setOngoing(true)
            .setContentText(resources.getText(R.string.desktop_session_active)).setContentIntent(pendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            public void onPrimaryClipChanged() {
                ClipboardManager clipboard = (ClipboardManager) AndRdpActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = clipboard.getPrimaryClip();
                String text = clip.getItemAt(0).coerceToText(AndRdpActivity.this).toString();
                if (Config.DEBUG)
                    Log.d(Config.TAG, "Android clipboard : " + text);

                if (isLoggedIn())
                    rdp.sendClipboard(text);
            }
        };
        clipboard.addPrimaryClipChangedListener(clipChangedListener);
    }
}

From source file:com.example.android.snake.SnakeView.java

public void setMode(int newMode) {
    int oldMode = mMode;
    mMode = newMode;/*from  ww w .  j a  v  a  2  s  . c o m*/

    if (newMode == RUNNING & oldMode != RUNNING) {
        isPaused = false;
        /*
        mEndImage.post(new Runnable() {
        @Override
        public void run() {
            mEndImage.setVisibility(View.INVISIBLE);
        }
        });
        mStatusText.post(new Runnable() {
        @Override
        public void run() {
            mStatusText.setVisibility(View.INVISIBLE);
        }
        });
        */
        mEndImage.setVisibility(View.INVISIBLE);
        mStatusText.setVisibility(View.INVISIBLE);
        //update();
        return;
    }

    Resources res = getContext().getResources();

    if (newMode == PAUSE) {
        isPaused = true;
        str = res.getText(R.string.mode_pause);
    }
    if (newMode == READY) {
        str = res.getText(R.string.mode_ready);
    }
    if (newMode == LOSE) {
        endGame();
        str = res.getString(R.string.mode_lose_prefix) + mScore + res.getString(R.string.mode_lose_suffix);
    }
    if (newMode == WIN) {
        endGame();
        str = res.getString(R.string.mode_win_prefix) + mScore + res.getString(R.string.mode_win_suffix);
    }
    mStatusText.post(new Runnable() {
        @Override
        public void run() {
            mStatusText.setText(str);
            mStatusText.setVisibility(View.VISIBLE);
        }
    });
    /*
    mStatusText.setText(str);
    mStatusText.setVisibility(View.VISIBLE);
    */
}

From source file:com.android.kalite27.ScriptActivity.java

private void copyResourcesToLocal() {
    String name, sFileName;/*from  w  ww  .  j  av  a2  s .c o  m*/
    InputStream content;

    R.raw a = new R.raw();
    java.lang.reflect.Field[] t = R.raw.class.getFields();
    Resources resources = getResources();

    boolean succeed = true;

    for (int i = 0; i < t.length; i++) {
        try {
            name = resources.getText(t[i].getInt(a)).toString();
            sFileName = name.substring(name.lastIndexOf('/') + 1, name.length());
            content = getResources().openRawResource(t[i].getInt(a));
            content.reset();

            // python project
            if (sFileName.endsWith(GlobalConstants.PYTHON_PROJECT_ZIP_NAME)) {
                succeed &= Utils.unzip(content, this.getFilesDir().getAbsolutePath() + "/", true);
            }
            // python -> /data/data/com.android.python27/files/python
            else if (sFileName.endsWith(GlobalConstants.PYTHON_ZIP_NAME)) {
                succeed &= Utils.unzip(content, this.getFilesDir().getAbsolutePath() + "/", true);
                FileUtils.chmod(new File(this.getFilesDir().getAbsolutePath() + "/python/bin/python"), 0755);
            }
            // python extras -> /sdcard/com.android.python27/extras/python
            else if (sFileName.endsWith(GlobalConstants.PYTHON_EXTRAS_ZIP_NAME)) {
                Utils.createDirectoryOnExternalStorage(this.getPackageName() + "/" + "extras");
                Utils.createDirectoryOnExternalStorage(this.getPackageName() + "/" + "extras" + "/" + "tmp");
                succeed &= Utils.unzip(content, Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/" + this.getPackageName() + "/extras/", true);
            }

        } catch (Exception e) {
            Log.e(GlobalConstants.LOG_TAG, "Failed to copyResourcesToLocal", e);
            succeed = false;
        }
    } // end for all files in res/raw

}

From source file:com.android.deskclock.data.StopwatchNotificationBuilderN.java

@Override
public Notification build(Context context, NotificationModel nm, Stopwatch stopwatch) {
    @StringRes/* ww  w.j av a  2  s.  c o m*/
    final int eventLabel = R.string.label_notification;

    // Intent to load the app when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    // Compute some values required below.
    final boolean running = stopwatch.isRunning();
    final String pname = context.getPackageName();
    final Resources res = context.getResources();
    final long base = SystemClock.elapsedRealtime() - stopwatch.getTotalTime();

    final RemoteViews content = new RemoteViews(pname, R.layout.chronometer_notif_content);
    content.setChronometer(R.id.chronometer, base, null, running);

    final List<Notification.Action> actions = new ArrayList<>(2);

    if (running) {
        // Left button: Pause
        final Intent pause = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_pause_24dp);
        final CharSequence title1 = res.getText(R.string.sw_pause_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Add Lap
        if (DataModel.getDataModel().canAddMoreLaps()) {
            final Intent lap = new Intent(context, StopwatchService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

            final Icon icon2 = Icon.createWithResource(context, R.drawable.ic_sw_lap_24dp);
            final CharSequence title2 = res.getText(R.string.sw_lap_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, lap);
            actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());
        }

        // Show the current lap number if any laps have been recorded.
        final int lapCount = DataModel.getDataModel().getLaps().size();
        if (lapCount > 0) {
            final int lapNumber = lapCount + 1;
            final String lap = res.getString(R.string.sw_notification_lap_number, lapNumber);
            content.setTextViewText(R.id.state, lap);
            content.setViewVisibility(R.id.state, VISIBLE);
        } else {
            content.setViewVisibility(R.id.state, GONE);
        }
    } else {
        // Left button: Start
        final Intent start = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_START_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_start_24dp);
        final CharSequence title1 = res.getText(R.string.sw_start_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Reset (dismisses notification and resets stopwatch)
        final Intent reset = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon2 = Icon.createWithResource(context, R.drawable.ic_reset_24dp);
        final CharSequence title2 = res.getText(R.string.sw_reset_button);
        final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());

        // Indicate the stopwatch is paused.
        content.setTextViewText(R.id.state, res.getString(R.string.swn_paused));
        content.setViewVisibility(R.id.state, VISIBLE);
    }

    // Swipe away will reset the stopwatch without bringing forward the app.
    final Intent reset = new Intent(context, StopwatchService.class)
            .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    return new Notification.Builder(context).setLocalOnly(true).setOngoing(running)
            .setCustomContentView(content).setContentIntent(pendingShowApp).setAutoCancel(stopwatch.isPaused())
            .setPriority(Notification.PRIORITY_MAX).setSmallIcon(R.drawable.stat_notify_stopwatch)
            .setGroup(nm.getStopwatchNotificationGroupKey())
            .setStyle(new Notification.DecoratedCustomViewStyle())
            .setDeleteIntent(Utils.pendingServiceIntent(context, reset))
            .setActions(actions.toArray(new Notification.Action[actions.size()]))
            .setColor(ContextCompat.getColor(context, R.color.default_background)).build();
}

From source file:com.android.inputmethod.latin.suggestions.SuggestionStripLayoutHelper.java

public void layoutAddToDictionaryHint(final String word, final ViewGroup addToDictionaryStrip) {
    final boolean shouldShowUiToAcceptTypedWord = Settings.getInstance()
            .getCurrent().mShouldShowUiToAcceptTypedWord;
    final int stripWidth = addToDictionaryStrip.getWidth();
    final int width = shouldShowUiToAcceptTypedWord ? stripWidth : stripWidth - mDividerWidth - mPadding * 2;

    final TextView wordView = (TextView) addToDictionaryStrip.findViewById(R.id.word_to_save);
    wordView.setTextColor(mColorTypedWord);
    final int wordWidth = (int) (width * mCenterSuggestionWeight);
    final CharSequence wordToSave = getEllipsizedText(word, wordWidth, wordView.getPaint());
    final float wordScaleX = wordView.getTextScaleX();
    wordView.setText(wordToSave);/*from   ww  w.j av a  2  s  .c  o m*/
    wordView.setTextScaleX(wordScaleX);
    setLayoutWeight(wordView, mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT);
    final int wordVisibility = shouldShowUiToAcceptTypedWord ? View.GONE : View.VISIBLE;
    wordView.setVisibility(wordVisibility);
    addToDictionaryStrip.findViewById(R.id.word_to_save_divider).setVisibility(wordVisibility);

    final Resources res = addToDictionaryStrip.getResources();
    final CharSequence hintText;
    final int hintWidth;
    final float hintWeight;
    final TextView hintView = (TextView) addToDictionaryStrip.findViewById(R.id.hint_add_to_dictionary);
    if (shouldShowUiToAcceptTypedWord) {
        hintText = res.getText(R.string.hint_add_to_dictionary_without_word);
        hintWidth = width;
        hintWeight = 1.0f;
        hintView.setGravity(Gravity.CENTER);
    } else {
        final boolean isRtlLanguage = (ViewCompat
                .getLayoutDirection(addToDictionaryStrip) == ViewCompat.LAYOUT_DIRECTION_RTL);
        final String arrow = isRtlLanguage ? RIGHTWARDS_ARROW : LEFTWARDS_ARROW;
        final boolean isRtlSystem = SubtypeLocaleUtils.isRtlLanguage(res.getConfiguration().locale);
        final CharSequence hint = res.getText(R.string.hint_add_to_dictionary);
        hintText = (isRtlLanguage == isRtlSystem) ? (arrow + hint) : (hint + arrow);
        hintWidth = width - wordWidth;
        hintWeight = 1.0f - mCenterSuggestionWeight;
        hintView.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
    }
    hintView.setTextColor(mColorAutoCorrect);
    final float hintScaleX = getTextScaleX(hintText, hintWidth, hintView.getPaint());
    hintView.setText(hintText);
    hintView.setTextScaleX(hintScaleX);
    setLayoutWeight(hintView, hintWeight, ViewGroup.LayoutParams.MATCH_PARENT);
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

private void setNotificationText(NotificationCompat.Builder builder) {
    final Resources res = getResources();

    final long now = SystemClock.elapsedRealtime();
    final long lastTestDelta = loopModeResults.getLastTestTime() == 0 ? 0
            : now - loopModeResults.getLastTestTime();

    final String elapsedTimeString = LoopModeTriggerItem.formatSeconds(Math.round(lastTestDelta / 1000), 1);

    final CharSequence textTemplate = res.getText(R.string.loop_notification_text_without_stop);
    final CharSequence text = MessageFormat.format(textTemplate.toString(), loopModeResults.getNumberOfTests(),
            elapsedTimeString, Math.round(loopModeResults.getLastDistance()));
    builder.setContentText(text);/*ww w  .j  a v a2 s  . c om*/

    if (bigTextStyle == null) {
        bigTextStyle = (new NotificationCompat.BigTextStyle());
        builder.setStyle(bigTextStyle);
    }

    bigTextStyle.bigText(text);
}