Example usage for android.content.res Resources getSystem

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

Introduction

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

Prototype

public static Resources getSystem() 

Source Link

Document

Return a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).

Usage

From source file:com.dycody.android.idealnote.BaseActivity.java

protected void setActionBarTitle(String title) {
    // Creating a spannable to support custom fonts on ActionBar
    int actionBarTitle = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
    android.widget.TextView actionBarTitleView = (android.widget.TextView) getWindow()
            .findViewById(actionBarTitle);
    Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
    if (actionBarTitleView != null) {
        actionBarTitleView.setTypeface(font);
    }//from  w  w  w. ja va 2 s.  c o m

    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(title);
    }
}

From source file:org.mozilla.labs.Soup.provider.AppsProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    // Validate the requested uri
    if (sUriMatcher.match(uri) != APPS) {
        throw new IllegalArgumentException("Unknown URI " + uri);
    }/*w  ww.j ava 2 s.c  om*/

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    Long now = Long.valueOf(System.currentTimeMillis());

    // Make sure that the fields are all set
    if (values.containsKey(AppsContract.Apps.CREATED_DATE) == false) {
        values.put(AppsContract.Apps.CREATED_DATE, now);
    }
    if (values.containsKey(AppsContract.Apps.MODIFIED_DATE) == false) {
        values.put(AppsContract.Apps.MODIFIED_DATE, now);
    }
    if (values.containsKey(AppsContract.Apps.INSTALL_TIME) == false) {
        values.put(AppsContract.Apps.INSTALL_TIME, now);
    }

    if (values.containsKey(AppsContract.Apps.NAME) == false) {
        Resources r = Resources.getSystem();
        values.put(AppsContract.Apps.NAME, r.getString(android.R.string.untitled));
    }
    if (values.containsKey(AppsContract.Apps.DESCRIPTION) == false) {
        values.put(AppsContract.Apps.DESCRIPTION, "");
    }

    if (values.containsKey(AppsContract.Apps.MANIFEST) == false) {
        values.put(AppsContract.Apps.MANIFEST, new JSONObject().toString());
    }
    if (values.containsKey(AppsContract.Apps.MANIFEST_URL) == false) {
        values.put(AppsContract.Apps.MANIFEST_URL, "");
    }
    if (values.containsKey(AppsContract.Apps.INSTALL_DATA) == false) {
        values.put(AppsContract.Apps.INSTALL_DATA, new JSONObject().toString());
    }

    if (values.containsKey(AppsContract.Apps.STATUS) == false) {
        values.put(AppsContract.Apps.STATUS, 0);
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId = db.insert(APPS_TABLE_NAME, null, values);

    if (rowId > 0) {
        Uri appUri = ContentUris.withAppendedId(AppsContract.Apps.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(appUri, null);
        return appUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:plugin.google.maps.GoogleMaps.java

@SuppressLint("NewApi")
@Override/* w w w. j a v  a2 s.  c o  m*/
public void initialize(final CordovaInterface cordova, final CordovaWebView webView) {
    super.initialize(cordova, webView);
    activity = cordova.getActivity();
    density = Resources.getSystem().getDisplayMetrics().density;
    root = (ViewGroup) webView.getParent();

    // Is this app in debug mode?
    try {
        PackageManager manager = activity.getPackageManager();
        ApplicationInfo appInfo = manager.getApplicationInfo(activity.getPackageName(), 0);
        isDebug = (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE;
    } catch (Exception e) {
    }

    Log.i("CordovaLog", "This app uses phonegap-googlemaps-plugin version " + PLUGIN_VERSION);

    if (isDebug) {
        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {

                try {

                    JSONArray params = new JSONArray();
                    params.put("get");
                    params.put("http://plugins.cordova.io/api/plugin.google.maps");
                    HttpRequest httpReq = new HttpRequest();
                    httpReq.initialize(cordova, null);
                    httpReq.execute("execute", params, new CallbackContext("version_check", webView) {
                        @Override
                        public void sendPluginResult(PluginResult pluginResult) {
                            if (pluginResult.getStatus() == PluginResult.Status.OK.ordinal()) {
                                try {
                                    JSONObject result = new JSONObject(pluginResult.getStrMessage());
                                    JSONObject distTags = result.getJSONObject("dist-tags");
                                    String latestVersion = distTags.getString("latest");
                                    if (latestVersion.equals(PLUGIN_VERSION) == false) {
                                        Log.i("CordovaLog", "phonegap-googlemaps-plugin version "
                                                + latestVersion + " is available.");
                                    }
                                } catch (JSONException e) {
                                }

                            }
                        }
                    });
                } catch (Exception e) {
                }
            }
        });
    }

    cordova.getActivity().runOnUiThread(new Runnable() {
        @SuppressLint("NewApi")
        public void run() {
            /*
                try {
                  Method method = webView.getClass().getMethod("getSettings");
                  WebSettings settings = (WebSettings)method.invoke(null);
                  settings.setRenderPriority(RenderPriority.HIGH);
                  settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
                } catch (Exception e) {
                  e.printStackTrace();
                }
             */
            if (Build.VERSION.SDK_INT >= 11) {
                webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }

            root.setBackgroundColor(Color.WHITE);
            if (VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            }
            if (VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                Log.d(TAG,
                        "Google Maps Plugin reloads the browser to change the background color as transparent.");
                webView.setBackgroundColor(0);
                try {
                    Method method = webView.getClass().getMethod("reload");
                    method.invoke(webView);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

}

From source file:io.teak.sdk.NotificationBuilder.java

public static Notification createNativeNotification(final Context context, Bundle bundle,
        TeakNotification teakNotificaton) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Rich text message
    Spanned richMessageText = Html.fromHtml(teakNotificaton.message);

    // Configure notification behavior
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    builder.setDefaults(NotificationCompat.DEFAULT_ALL);
    builder.setOnlyAlertOnce(true);/*from w  w w .j  a  va 2s .c o m*/
    builder.setAutoCancel(true);
    builder.setTicker(richMessageText);

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    Random rng = new Random();

    // Create intent to fire if/when notification is cleared
    Intent pushClearedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_CLEARED_INTENT_ACTION_SUFFIX);
    pushClearedIntent.putExtras(bundle);
    PendingIntent pushClearedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(),
            pushClearedIntent, PendingIntent.FLAG_ONE_SHOT);
    builder.setDeleteIntent(pushClearedPendingIntent);

    // Create intent to fire if/when notification is opened, attach bundle info
    Intent pushOpenedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_OPENED_INTENT_ACTION_SUFFIX);
    pushOpenedIntent.putExtras(bundle);
    PendingIntent pushOpenedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(), pushOpenedIntent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pushOpenedPendingIntent);

    // Because we can't be certain that the R class will line up with what is at SDK build time
    // like in the case of Unity et. al.
    class IdHelper {
        public int id(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "id", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.id." + identifier);
            }
            return ret;
        }

        public int layout(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "layout", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.layout." + identifier);
            }
            return ret;
        }
    }
    IdHelper R = new IdHelper(); // Declaring local as 'R' ensures we don't accidentally use the other R

    // Configure notification small view
    RemoteViews smallView = new RemoteViews(context.getPackageName(),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_notif_no_title_v21")
                    : R.layout("teak_notif_no_title"));

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        smallView.setImageViewResource(R.id("left_image"), ai.icon);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    // Set small view text
    smallView.setTextViewText(R.id("text"), richMessageText);

    // Check for Jellybean (API 16, 4.1)+ for expanded view
    RemoteViews bigView = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && teakNotificaton.longText != null
            && !teakNotificaton.longText.isEmpty()) {
        bigView = new RemoteViews(context.getPackageName(),
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_big_notif_image_text_v21")
                        : R.layout("teak_big_notif_image_text"));

        // Set big view text
        bigView.setTextViewText(R.id("text"), Html.fromHtml(teakNotificaton.longText));

        URI imageAssetA = null;
        try {
            imageAssetA = new URI(teakNotificaton.imageAssetA);
        } catch (Exception ignored) {
        }

        Bitmap topImageBitmap = null;
        if (imageAssetA != null) {
            try {
                URL aURL = new URL(imageAssetA.toString());
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                topImageBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap == null) {
            try {
                InputStream istr = context.getAssets().open("teak_notif_large_image_default.png");
                topImageBitmap = BitmapFactory.decodeStream(istr);
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap != null) {
            // Set large bitmap
            bigView.setImageViewBitmap(R.id("top_image"), topImageBitmap);
        } else {
            Log.e(LOG_TAG, "Unable to load image asset for Notification.");
            // Hide pulldown
            smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
        }
    } else {
        // Hide pulldown
        smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
    }

    // Voodoo from http://stackoverflow.com/questions/28169474/notification-background-in-android-lollipop-is-white-can-we-change-it
    int topId = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    int topBigLayout = Resources.getSystem().getIdentifier("notification_template_material_big_media_narrow",
            "layout", "android");
    int topSmallLayout = Resources.getSystem().getIdentifier("notification_template_material_media", "layout",
            "android");

    RemoteViews topBigView = null;
    if (bigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // This is invisible inner view - to have media_actions in hierarchy
        RemoteViews innerTopView = new RemoteViews("android", topBigLayout);
        bigView.addView(android.R.id.empty, innerTopView);

        // This should be on top - we need status_bar_latest_event_content as top layout
        topBigView = new RemoteViews("android", topBigLayout);
        topBigView.removeAllViews(topId);
        topBigView.addView(topId, bigView);
    } else if (bigView != null) {
        topBigView = bigView;
    }

    // This should be on top - we need status_bar_latest_event_content as top layout
    RemoteViews topSmallView;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        topSmallView = new RemoteViews("android", topSmallLayout);
        topSmallView.removeAllViews(topId);
        topSmallView.addView(topId, smallView);
    } else {
        topSmallView = smallView;
    }

    builder.setContent(topSmallView);

    Notification n = builder.build();
    if (topBigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // Use reflection to avoid compile-time issues, we check minimum API version above
        try {
            Field bigContentViewField = n.getClass().getField("bigContentView");
            bigContentViewField.set(n, topBigView);
        } catch (Exception ignored) {
        }
    }

    return n;
}

From source file:com.souvenir.android.DrawerActivity.java

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

    STrip strip = new STrip("uncategorized");
    strip.setDirty(true);//w w w .jav  a2s .  c  o  m
    strip.insert(this);

    if (!ImageLoader.getInstance().isInited()) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.getApplicationContext())
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                /* .enableLogging() */.build();
        ImageLoader.getInstance().init(config);
    }
    mTitle = mDrawerTitle = getTitle();
    mDrawerTitles = getResources().getStringArray(R.array.drawer_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new aa(this, R.layout.drawer_list_item, mDrawerTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
    TextView yourTextView = (TextView) findViewById(titleId);
    yourTextView.setTextColor(getResources().getColor(android.R.color.white));

    prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
    if (prefs.contains("autosync")) {
        autosync = prefs.getBoolean("autosync", false);
    }

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            // String curTitle = (String) getSupportActionBar().getTitle();
            // if (curTitle.toString().contains(":"))
            // {
            // setTitle(curTitle);
            // }
            // else
            // {
            //
            // getSupportActionBar().setTitle(mTitle);
            // }
            getSupportActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(COMPLETED_POSITION);
    }
}

From source file:com.github.shareme.gwsmaterialuikit.library.toast.ToastCompat.java

/**
 * Make a standard toast that just contains a text view.
 *
 * @param context  The context to use.  Usually your {@link android.app.Application}
 *                 or {@link android.app.Activity} object.
 * @param text     The text to show.  Can be formatted text.
 * @param duration How long to display the message.  Either {@link #LENGTH_SHORT} or
 *                 {@link #LENGTH_LONG}// ww w.j  av a  2 s.c o  m
 *
 */
public static ToastCompat makeText(Context context, String text, @Duration int duration) {
    ToastCompat result = new ToastCompat(context);

    LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(Resources.getSystem().getIdentifier("transient_notification", "layout", "android"),
            null);
    TextView tv = (TextView) v.findViewById(Resources.getSystem().getIdentifier("message", "id", "android"));
    tv.setText(text);

    result.mNextView = v;
    result.mDuration = duration;

    return result;
}

From source file:com.moonpi.tapunlock.MainActivity.java

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

    // Get lobster_two asset and create typeface
    // Set action bar title to lobster_two typeface
    lobsterTwo = Typeface.createFromAsset(getAssets(), "lobster_two.otf");

    int actionBarTitle = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
    actionBarTitleView = (TextView) getWindow().findViewById(actionBarTitle);

    if (actionBarTitleView != null) {
        actionBarTitleView.setTypeface(lobsterTwo);
        actionBarTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28f);
        actionBarTitleView.setTextColor(getResources().getColor(R.color.blue));
    }/*w w  w.  j a va 2 s.  c  om*/

    setContentView(R.layout.activity_main);

    // Hide keyboard on app launch
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    // Get NFC service and adapter
    NfcManager nfcManager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
    nfcAdapter = nfcManager.getDefaultAdapter();

    // Create PendingIntent for enableForegroundDispatch for NFC tag discovery
    pIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    readFromJSON();
    writeToJSON();
    readFromJSON();

    // If Android 4.2 or bigger
    if (Build.VERSION.SDK_INT > 16) {
        // Check if TapUnlock folder exists, if not, create directory
        File folder = new File(Environment.getExternalStorageDirectory() + "/TapUnlock");
        boolean folderSuccess = true;

        if (!folder.exists()) {
            folderSuccess = folder.mkdir();
        }

        try {
            // If blur var bigger than 0
            if (settings.getInt("blur") > 0) {
                // If folder exists or successfully created
                if (folderSuccess) {
                    // If blurred wallpaper file doesn't exist
                    if (!ImageUtils.doesBlurredWallpaperExist()) {
                        // Get default wallpaper
                        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
                        final Drawable wallpaperDrawable = wallpaperManager.peekFastDrawable();

                        if (wallpaperDrawable != null) {
                            // Default wallpaper to bitmap - fastBlur the bitmap - store bitmap
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Bitmap bitmapToBlur = ImageUtils.drawableToBitmap(wallpaperDrawable);

                                    Bitmap blurredWallpaper = null;
                                    if (bitmapToBlur != null)
                                        blurredWallpaper = ImageUtils.fastBlur(MainActivity.this, bitmapToBlur,
                                                blur);

                                    if (blurredWallpaper != null) {
                                        ImageUtils.storeImage(blurredWallpaper);
                                    }
                                }
                            }).start();
                        }
                    }
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // Initialize layout items
    pinEdit = (EditText) findViewById(R.id.pinEdit);
    pinEdit.setImeOptions(EditorInfo.IME_ACTION_DONE);
    Button setPin = (Button) findViewById(R.id.setPin);
    ImageButton newTag = (ImageButton) findViewById(R.id.newTag);
    enabled_disabled = (TextView) findViewById(R.id.enabled_disabled);
    Switch toggle = (Switch) findViewById(R.id.toggle);
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    Button refreshWallpaper = (Button) findViewById(R.id.refreshWallpaper);
    listView = (ListView) findViewById(R.id.listView);
    backgroundBlurValue = (TextView) findViewById(R.id.backgroundBlurValue);
    noTags = (TextView) findViewById(R.id.noTags);

    // Initialize TagAdapter
    adapter = new TagAdapter(this, tags);

    registerForContextMenu(listView);

    // Set listView adapter to TapAdapter object
    listView.setAdapter(adapter);

    // Set click, check and seekBar listeners
    setPin.setOnClickListener(this);
    newTag.setOnClickListener(this);
    refreshWallpaper.setOnClickListener(this);
    toggle.setOnCheckedChangeListener(this);
    seekBar.setOnSeekBarChangeListener(this);

    // Set seekBar progress to blur var
    try {
        seekBar.setProgress(settings.getInt("blur"));

    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Refresh the listView height
    updateListViewHeight(listView);

    // If no tags, show 'Press + to add Tags' textView
    if (tags.length() == 0)
        noTags.setVisibility(View.VISIBLE);

    else
        noTags.setVisibility(View.INVISIBLE);

    // Scroll up
    scrollView = (ScrollView) findViewById(R.id.scrollView);

    scrollView.post(new Runnable() {
        public void run() {
            scrollView.scrollTo(0, scrollView.getTop());
            scrollView.fullScroll(View.FOCUS_UP);
        }
    });

    // If lockscreen enabled, initialize switch, text and start service
    try {
        if (settings.getBoolean("lockscreen")) {
            onStart = true;
            enabled_disabled.setText(R.string.lockscreen_enabled);
            enabled_disabled.setTextColor(getResources().getColor(R.color.green));

            toggle.setChecked(true);
        }

    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

From source file:org.proninyaroslav.libretorrent.core.utils.Utils.java

public static int getDefaultBatteryLowLevel() {
    return Resources.getSystem().getInteger(
            Resources.getSystem().getIdentifier("config_lowBatteryWarningLevel", "integer", "android"));
}

From source file:net.pmarks.chromadoze.NoiseService.java

private void addButtonToNotification(Notification n) {
    // Create a new RV with a Stop button.
    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification_with_stop_button);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            newStopIntent(this, R.string.stop_reason_notification), PendingIntent.FLAG_CANCEL_CURRENT);
    rv.setOnClickPendingIntent(R.id.stop_button, pendingIntent);

    // Pre-render the original RV, and copy some of the colors.
    final View inflated = n.contentView.apply(this, new FrameLayout(this));
    final TextView titleText = findTextView(inflated, getString(R.string.app_name));
    final TextView defaultText = findTextView(inflated, getString(R.string.notification_text));
    rv.setInt(R.id.divider, "setBackgroundColor", defaultText.getTextColors().getDefaultColor());
    rv.setInt(R.id.stop_button_square, "setBackgroundColor", titleText.getTextColors().getDefaultColor());

    // Insert a copy of the original RV into the new one.
    rv.addView(R.id.notification_insert, n.contentView.clone());

    // Splice everything back into the original's root view.
    int id = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    n.contentView.removeAllViews(id);//from  w ww  . j a v  a2s  .  c  o  m
    n.contentView.addView(id, rv);
}

From source file:com.oasisfeng.nevo.decorators.bundle.BundleDecorator.java

private Notification buildBundleNotification(final String bundle, final int number,
        final List<StatusBarNotificationEvo> sbns) throws RemoteException {
    final Set<String> bundled_pkgs = new HashSet<>(sbns.size());
    final ArrayList<String> bundled_keys = new ArrayList<>(sbns.size());
    long latest_when = 0;
    for (final StatusBarNotificationEvo sbn : sbns) {
        final long when = sbn.notification().getWhen();
        if (when > latest_when)
            latest_when = when;//from   w ww. java  2 s.  c om
        bundled_pkgs.add(sbn.getPackageName());
        bundled_keys.add(sbn.getKey());
    }

    final Intent delete_intent = new Intent(ACTION_BUNDLE_CLEAR)
            .setData(Uri.fromParts(SCHEME_BUNDLE, bundle, null))
            .putStringArrayListExtra(EXTRA_KEYS, bundled_keys);
    final PendingIntent delete_pending_intent = PendingIntent.getBroadcast(this, 0, delete_intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    final Builder builder = new Builder(this).setContentTitle(bundle)
            .setSmallIcon(R.drawable.ic_notification_bundle).setWhen(latest_when).setAutoCancel(false)
            .setPriority(PRIORITY_MIN).setNumber(number).setDeleteIntent(delete_pending_intent);
    if (bundled_pkgs.size() == 1) {
        final IBundle last_extras = sbns.get(0).notification().extras();
        builder.setContentText(last_extras.getCharSequence(NotificationCompat.EXTRA_TITLE))
                .setSubText(last_extras.getCharSequence(NotificationCompat.EXTRA_TEXT));
    } else
        builder.setContentText(getSourceNames(bundled_pkgs));

    builder.getExtras().putBoolean(NevoConstants.EXTRA_PHANTOM, true); // Bundle notification should never be evolved or stored.

    final Notification notification = builder.build();
    // Set on-click pending intent explicitly, to avoid notification drawer collapse when bundle is clicked.
    final Intent click_intent = new Intent(ACTION_BUNDLE_EXPAND)
            .setData(Uri.fromParts(SCHEME_BUNDLE, bundle, null))
            .putStringArrayListExtra(EXTRA_KEYS, bundled_keys);
    final PendingIntent click_pending_intent = PendingIntent.getBroadcast(this, 0, click_intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    final int view_id = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    if (view_id != 0)
        notification.contentView.setOnClickPendingIntent(view_id, click_pending_intent);
    else
        builder.setContentIntent(click_pending_intent); // Fallback to normal content intent (notification drawer will collapse)

    notification.bigContentView = buildExpandedView(sbns);
    return notification;
}