List of usage examples for android.widget RemoteViews setViewVisibility
public void setViewVisibility(int viewId, int visibility)
From source file:com.tortel.deploytrack.service.NotificationService.java
@SuppressLint("NewApi") private void showNotification() { // If there isnt an ID saved, shut down the service if (deploymentId == -1) { stopSelf();// www . ja va 2 s. co m return; } if (DEBUG) { Toast.makeText(this, "NotificationService loading notification", Toast.LENGTH_SHORT).show(); } // Load the Deployment object Deployment deployment = DatabaseManager.getInstance(this).getDeployment(deploymentId); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification); view.setImageViewBitmap(R.id.notification_pie, WidgetProvider.getChartBitmap(deployment, SIZE)); view.setTextViewText(R.id.notification_title, deployment.getName()); view.setTextViewText(R.id.notification_main, getResources().getString(R.string.small_notification, deployment.getPercentage(), deployment.getCompleted(), deployment.getLength())); if (prefs.getBoolean(Prefs.KEY_HIDE_DATE, false)) { view.setViewVisibility(R.id.notification_daterange, View.GONE); } else { view.setTextViewText(R.id.notification_daterange, getResources().getString(R.string.date_range, deployment.getFormattedStart(), deployment.getFormattedEnd())); } NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle(deployment.getName()); builder.setContentText(getResources().getString(R.string.small_notification, deployment.getPercentage(), deployment.getCompleted(), deployment.getLength())); builder.setOngoing(true); // Hide the time, its persistent builder.setWhen(0); builder.setSmallIcon(R.drawable.ic_notification); builder.setPriority(Integer.MAX_VALUE); Notification notification = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { notification.bigContentView = view; } notificationManager.notify(NOTIFICATION_ID, notification); //Schedule an update at midnight AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); DateTime now = new DateTime(); DateTime tomorrow = new DateTime(now.plusDays(1)).withTimeAtStartOfDay(); PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, new Intent(UPDATE_INTENT), PendingIntent.FLAG_UPDATE_CURRENT); //Adding 100msec to make sure its triggered after midnight Log.d("Scheduling notification update for " + tomorrow.getMillis() + 100); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) { alarmManager.setExact(AlarmManager.RTC, tomorrow.getMillis() + 100, pending); } else { alarmManager.set(AlarmManager.RTC, tomorrow.getMillis() + 100, pending); } }
From source file:org.chromium.chrome.browser.media.ui.NotificationMediaPlaybackControls.java
private RemoteViews createContentView() { RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.playback_notification_bar); // On Android pre-L, dismissing the notification when the service is no longer in foreground // doesn't work. Instead, a STOP button is shown. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { contentView.setViewVisibility(R.id.stop, View.VISIBLE); contentView.setOnClickPendingIntent(R.id.stop, mService.getPendingIntent(ListenerService.ACTION_STOP)); }/* ww w . j a v a2 s .c o m*/ return contentView; }
From source file:com.ratusapparatus.tapsaff.TapsAff.java
protected void onPostExecute(String feed) { ComponentName thisWidget = new ComponentName(context, TapsAff.class); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); Log.i("tapsaffonPostExecuteFeed", feed); JSONObject jsonObj;/*www .j av a2 s .c om*/ try { jsonObj = new JSONObject(feed); /*for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Log.i(TapsAff.class.getName(), jsonObject.getString("text")); }*/ String oanAff = jsonObj.get("taps").toString(); Integer itsClose = (Integer) jsonObj.get("temp_f"); if (itsClose >= TapsAff.tapsTemp - 5 && itsClose <= TapsAff.tapsTemp) views.setViewVisibility(R.id.bottom, View.VISIBLE); else views.setViewVisibility(R.id.bottom, View.GONE); String colour = "blue"; if (oanAff == "Aff") colour = "red"; String text = "taps" + " " + "<font color='" + colour + "'>" + oanAff + "</font>"; //textView.setText(, TextView.BufferType.SPANNABLE); views.setTextViewText(R.id.main, Html.fromHtml(text)); } catch (Exception e) { Log.i("tapsaffonPostExecuteException", e.getLocalizedMessage()); } appWidgetManager.updateAppWidget(thisWidget, views); }
From source file:name.gumartinm.weather.information.widget.WidgetIntentService.java
private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) { // 1. Update units of measurement. UnitsConversor tempUnitsConversor;//from w ww .j a va2 s. c o m String keyPreference = this.getApplicationContext() .getString(R.string.widget_preferences_temperature_units_key); String realKeyPreference = keyPreference + "_" + appWidgetId; // What was saved to permanent storage (or default values if it is the first time) final int tempValue = this.getSharedPreferences(WIDGET_PREFERENCES_NAME, Context.MODE_PRIVATE) .getInt(realKeyPreference, 0); final String tempSymbol = this.getResources() .getStringArray(R.array.weather_preferences_temperature)[tempValue]; if (tempValue == 0) { tempUnitsConversor = new UnitsConversor() { @Override public double doConversion(final double value) { return value - 273.15; } }; } else if (tempValue == 1) { tempUnitsConversor = new UnitsConversor() { @Override public double doConversion(final double value) { return (value * 1.8) - 459.67; } }; } else { tempUnitsConversor = new UnitsConversor() { @Override public double doConversion(final double value) { return value; } }; } // 2. Update country. keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_country_switch_key); realKeyPreference = keyPreference + "_" + appWidgetId; // What was saved to permanent storage (or default values if it is the first time) final boolean isCountry = this.getSharedPreferences(WIDGET_PREFERENCES_NAME, Context.MODE_PRIVATE) .getBoolean(realKeyPreference, false); // 3. Formatters final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); tempFormatter.applyPattern("###.##"); // 4. Prepare data for RemoteViews. String tempMax = ""; if (current.getMain().getTemp_max() != null) { double conversion = (Double) current.getMain().getTemp_max(); conversion = tempUnitsConversor.doConversion(conversion); tempMax = tempFormatter.format(conversion) + tempSymbol; } String tempMin = ""; if (current.getMain().getTemp_min() != null) { double conversion = (Double) current.getMain().getTemp_min(); conversion = tempUnitsConversor.doConversion(conversion); tempMin = tempFormatter.format(conversion) + tempSymbol; } Bitmap picture; if ((current.getWeather().size() > 0) && (current.getWeather().get(0).getIcon() != null) && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) { final String icon = current.getWeather().get(0).getIcon(); picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon).getResourceDrawable()); } else { picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert); } final String city = weatherLocation.getCity(); final String country = weatherLocation.getCountry(); // 5. Insert data in RemoteViews. final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget); remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture); remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax); remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin); remoteView.setTextViewText(R.id.weather_appwidget_city, city); if (!isCountry) { remoteView.setViewVisibility(R.id.weather_appwidget_country, View.GONE); } else { // TODO: It is as if Android had a view cache. If I did not set VISIBLE value, // the country field would be gone forever... :/ remoteView.setViewVisibility(R.id.weather_appwidget_country, View.VISIBLE); remoteView.setTextViewText(R.id.weather_appwidget_country, country); } // 6. Activity launcher. final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class); resultIntent.putExtra("actionFromUser", true); resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/"), String.valueOf(appWidgetId)); resultIntent.setData(data); final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext()); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(WidgetConfigure.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent); return remoteView; }
From source file:net.sourceforge.servestream.service.AppWidgetOneProvider.java
/** * Update all active widget instances by pushing changes *///from w w w . j ava2 s. com 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:net.naonedbus.appwidget.HoraireWidgetProvider.java
/** * Lancer le chargement des horaires./* w ww . j a v a 2 s. c o m*/ */ protected void prepareWidgetAndloadHoraires(final Context context, final RemoteViews views, final Favori favori, final Integer appWidgetId) { final NextHoraireTask horaireTask = new NextHoraireTask(); horaireTask.setContext(context); horaireTask.setArret(favori); horaireTask.setId(appWidgetId); horaireTask.setLimit(mHoraireLimit); horaireTask.setActionCallback(ACTION_APPWIDGET_UPDATE); // Lancer le chargement des horaires final HoraireManager horaireManager = HoraireManager.getInstance(); horaireManager.schedule(horaireTask); views.setTextViewText(R.id.itemTime, null); views.setViewVisibility(R.id.widgetProgress, View.VISIBLE); }
From source file:com.namelessdev.mpdroid.NotificationService.java
/** * This method builds the base, otherwise known as the collapsed notification. The expanded * notification method builds upon this method. * * @param resultView The RemoteView to begin with, be it new or from the current notification. * @return The base, otherwise known as, collapsed notification resources for RemoteViews. *//*from ww w . j av a 2s.c om*/ private RemoteViews buildBaseNotification(final RemoteViews resultView) { final String title = mCurrentMusic.getTitle(); /** If in streaming, the notification should be persistent. */ if (app.getApplicationState().streamingMode && !StreamingService.isWoundDown()) { resultView.setViewVisibility(R.id.notificationClose, View.GONE); } else { resultView.setViewVisibility(R.id.notificationClose, View.VISIBLE); resultView.setOnClickPendingIntent(R.id.notificationClose, notificationClose); } if (MPDStatus.MPD_STATE_PLAYING.equals(getStatus().getState())) { resultView.setOnClickPendingIntent(R.id.notificationPlayPause, notificationPause); resultView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_media_pause); } else { resultView.setOnClickPendingIntent(R.id.notificationPlayPause, notificationPlay); resultView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_media_play); } /** When streaming, move things down (hopefully, very) temporarily. */ if (mediaPlayerServiceIsBuffering) { resultView.setTextViewText(R.id.notificationTitle, getString(R.string.buffering)); resultView.setTextViewText(R.id.notificationArtist, title); } else { resultView.setTextViewText(R.id.notificationTitle, title); resultView.setTextViewText(R.id.notificationArtist, mCurrentMusic.getArtist()); } resultView.setOnClickPendingIntent(R.id.notificationNext, notificationNext); if (mAlbumCover != null) { resultView.setImageViewUri(R.id.notificationIcon, Uri.parse(mAlbumCoverPath)); } return resultView; }
From source file:org.xbmc.kore.service.NotificationObserver.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void buildNotification(PlayerType.GetActivePlayersReturnType getActivePlayerResult, PlayerType.PropertyValue getPropertiesResult, ListType.ItemsAll getItemResult) { final String title, underTitle, poster; int smallIcon, playPauseIcon, rewindIcon, ffIcon; boolean isVideo = ((getItemResult.type.equals(ListType.ItemsAll.TYPE_MOVIE)) || (getItemResult.type.equals(ListType.ItemsAll.TYPE_EPISODE))); switch (getItemResult.type) { case ListType.ItemsAll.TYPE_MOVIE: title = getItemResult.title;/*from w w w . j a v a 2 s . com*/ underTitle = getItemResult.tagline; poster = getItemResult.thumbnail; smallIcon = R.drawable.ic_movie_white_24dp; break; case ListType.ItemsAll.TYPE_EPISODE: title = getItemResult.title; String seasonEpisode = String.format(mContext.getString(R.string.season_episode_abbrev), getItemResult.season, getItemResult.episode); underTitle = String.format("%s | %s", getItemResult.showtitle, seasonEpisode); poster = getItemResult.art.poster; smallIcon = R.drawable.ic_tv_white_24dp; break; case ListType.ItemsAll.TYPE_SONG: title = getItemResult.title; underTitle = getItemResult.displayartist + " | " + getItemResult.album; poster = getItemResult.thumbnail; smallIcon = R.drawable.ic_headset_white_24dp; break; case ListType.ItemsAll.TYPE_MUSIC_VIDEO: title = getItemResult.title; underTitle = Utils.listStringConcat(getItemResult.artist, ", ") + " | " + getItemResult.album; poster = getItemResult.thumbnail; smallIcon = R.drawable.ic_headset_white_24dp; break; default: // We don't know what this is, forget it return; } switch (getPropertiesResult.speed) { case 1: playPauseIcon = R.drawable.ic_pause_white_24dp; break; default: playPauseIcon = R.drawable.ic_play_arrow_white_24dp; break; } // Create the actions, depending on the type of media PendingIntent rewindPendingItent, ffPendingItent, playPausePendingIntent; playPausePendingIntent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_PLAY_PAUSE); if (getItemResult.type.equals(ListType.ItemsAll.TYPE_SONG)) { rewindPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_PREVIOUS); rewindIcon = R.drawable.ic_skip_previous_white_24dp; ffPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_NEXT); ffIcon = R.drawable.ic_skip_next_white_24dp; } else { rewindPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_REWIND); rewindIcon = R.drawable.ic_fast_rewind_white_24dp; ffPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_FAST_FORWARD); ffIcon = R.drawable.ic_fast_forward_white_24dp; } // Setup the collpased and expanded notifications final RemoteViews collapsedRV = new RemoteViews(mContext.getPackageName(), R.layout.notification_colapsed); collapsedRV.setImageViewResource(R.id.rewind, rewindIcon); collapsedRV.setOnClickPendingIntent(R.id.rewind, rewindPendingItent); collapsedRV.setImageViewResource(R.id.play, playPauseIcon); collapsedRV.setOnClickPendingIntent(R.id.play, playPausePendingIntent); collapsedRV.setImageViewResource(R.id.fast_forward, ffIcon); collapsedRV.setOnClickPendingIntent(R.id.fast_forward, ffPendingItent); collapsedRV.setTextViewText(R.id.title, title); collapsedRV.setTextViewText(R.id.text2, underTitle); final RemoteViews expandedRV = new RemoteViews(mContext.getPackageName(), R.layout.notification_expanded); expandedRV.setImageViewResource(R.id.rewind, rewindIcon); expandedRV.setOnClickPendingIntent(R.id.rewind, rewindPendingItent); expandedRV.setImageViewResource(R.id.play, playPauseIcon); expandedRV.setOnClickPendingIntent(R.id.play, playPausePendingIntent); expandedRV.setImageViewResource(R.id.fast_forward, ffIcon); expandedRV.setOnClickPendingIntent(R.id.fast_forward, ffPendingItent); expandedRV.setTextViewText(R.id.title, title); expandedRV.setTextViewText(R.id.text2, underTitle); final int expandedIconResId; if (isVideo) { expandedIconResId = R.id.icon_slim; expandedRV.setViewVisibility(R.id.icon_slim, View.VISIBLE); expandedRV.setViewVisibility(R.id.icon_square, View.GONE); } else { expandedIconResId = R.id.icon_square; expandedRV.setViewVisibility(R.id.icon_slim, View.GONE); expandedRV.setViewVisibility(R.id.icon_square, View.VISIBLE); } // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext); final Notification notification = builder.setSmallIcon(smallIcon).setShowWhen(false).setOngoing(true) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_TRANSPORT).setContentIntent(mRemoteStartPendingIntent) .setContent(collapsedRV).build(); // This is a convoluted way of loading the image and showing the // notification, but it's what works with Picasso and is efficient. // Here's what's going on: // // 1. The image is loaded asynchronously into a Target, and only after // it is loaded is the notification shown. Using targets is a lot more // efficient than letting Picasso load it directly into the // notification imageview, which causes a lot of flickering // // 2. The target needs to be static, because Picasso only keeps a weak // reference to it, so we need to keed a strong reference and reset it // to null when we're done. We also need to check if it is not null in // case a previous request hasn't finished yet. // // 3. We can only show the notification after the bitmap is loaded into // the target, so it is done in the callback // // 4. We specifically resize the image to the same dimensions used in // the remote, so that Picasso reuses it in the remote and here from the cache Resources resources = mContext.getResources(); final int posterWidth = resources.getDimensionPixelOffset(R.dimen.now_playing_poster_width); final int posterHeight = isVideo ? resources.getDimensionPixelOffset(R.dimen.now_playing_poster_height) : posterWidth; if (picassoTarget == null) { picassoTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { showNotification(bitmap); } @Override public void onBitmapFailed(Drawable errorDrawable) { CharacterDrawable avatarDrawable = UIUtils.getCharacterAvatar(mContext, title); showNotification(Utils.drawableToBitmap(avatarDrawable, posterWidth, posterHeight)); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } private void showNotification(Bitmap bitmap) { collapsedRV.setImageViewBitmap(R.id.icon, bitmap); if (Utils.isJellybeanOrLater()) { notification.bigContentView = expandedRV; expandedRV.setImageViewBitmap(expandedIconResId, bitmap); } NotificationManager notificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notification); picassoTarget = null; } }; // Load the image HostManager hostManager = HostManager.getInstance(mContext); hostManager.getPicasso().load(hostManager.getHostInfo().getImageUrl(poster)) .resize(posterWidth, posterHeight).into(picassoTarget); } }
From source file:com.syncedsynapse.kore2.service.NotificationService.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void buildNotification(PlayerType.GetActivePlayersReturnType getActivePlayerResult, PlayerType.PropertyValue getPropertiesResult, ListType.ItemsAll getItemResult) { final String title, underTitle, poster; int smallIcon, playPauseIcon, rewindIcon, ffIcon; boolean isVideo = ((getItemResult.type.equals(ListType.ItemsAll.TYPE_MOVIE)) || (getItemResult.type.equals(ListType.ItemsAll.TYPE_EPISODE))); switch (getItemResult.type) { case ListType.ItemsAll.TYPE_MOVIE: title = getItemResult.title;//from www .ja v a 2 s . c om underTitle = getItemResult.tagline; poster = getItemResult.thumbnail; smallIcon = R.drawable.ic_movie_white_24dp; break; case ListType.ItemsAll.TYPE_EPISODE: title = getItemResult.title; String seasonEpisode = String.format(getString(R.string.season_episode_abbrev), getItemResult.season, getItemResult.episode); underTitle = String.format("%s | %s", getItemResult.showtitle, seasonEpisode); poster = getItemResult.art.poster; smallIcon = R.drawable.ic_tv_white_24dp; break; case ListType.ItemsAll.TYPE_SONG: title = getItemResult.title; underTitle = getItemResult.displayartist + " | " + getItemResult.album; poster = getItemResult.thumbnail; smallIcon = R.drawable.ic_headset_white_24dp; break; case ListType.ItemsAll.TYPE_MUSIC_VIDEO: title = getItemResult.title; underTitle = Utils.listStringConcat(getItemResult.artist, ", ") + " | " + getItemResult.album; poster = getItemResult.thumbnail; smallIcon = R.drawable.ic_headset_white_24dp; break; default: // We don't know what this is, forget it return; } switch (getPropertiesResult.speed) { case 1: playPauseIcon = R.drawable.ic_pause_white_24dp; break; default: playPauseIcon = R.drawable.ic_play_arrow_white_24dp; break; } // Create the actions, depending on the type of media PendingIntent rewindPendingItent, ffPendingItent, playPausePendingIntent; playPausePendingIntent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_PLAY_PAUSE); if (getItemResult.type.equals(ListType.ItemsAll.TYPE_SONG)) { rewindPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_PREVIOUS); rewindIcon = R.drawable.ic_skip_previous_white_24dp; ffPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_NEXT); ffIcon = R.drawable.ic_skip_next_white_24dp; } else { rewindPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_REWIND); rewindIcon = R.drawable.ic_fast_rewind_white_24dp; ffPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid, IntentActionsService.ACTION_FAST_FORWARD); ffIcon = R.drawable.ic_fast_forward_white_24dp; } // Setup the collpased and expanded notifications final RemoteViews collapsedRV = new RemoteViews(this.getPackageName(), R.layout.notification_colapsed); collapsedRV.setImageViewResource(R.id.rewind, rewindIcon); collapsedRV.setOnClickPendingIntent(R.id.rewind, rewindPendingItent); collapsedRV.setImageViewResource(R.id.play, playPauseIcon); collapsedRV.setOnClickPendingIntent(R.id.play, playPausePendingIntent); collapsedRV.setImageViewResource(R.id.fast_forward, ffIcon); collapsedRV.setOnClickPendingIntent(R.id.fast_forward, ffPendingItent); collapsedRV.setTextViewText(R.id.title, title); collapsedRV.setTextViewText(R.id.text2, underTitle); final RemoteViews expandedRV = new RemoteViews(this.getPackageName(), R.layout.notification_expanded); expandedRV.setImageViewResource(R.id.rewind, rewindIcon); expandedRV.setOnClickPendingIntent(R.id.rewind, rewindPendingItent); expandedRV.setImageViewResource(R.id.play, playPauseIcon); expandedRV.setOnClickPendingIntent(R.id.play, playPausePendingIntent); expandedRV.setImageViewResource(R.id.fast_forward, ffIcon); expandedRV.setOnClickPendingIntent(R.id.fast_forward, ffPendingItent); expandedRV.setTextViewText(R.id.title, title); expandedRV.setTextViewText(R.id.text2, underTitle); final int expandedIconResId; if (isVideo) { expandedIconResId = R.id.icon_slim; expandedRV.setViewVisibility(R.id.icon_slim, View.VISIBLE); expandedRV.setViewVisibility(R.id.icon_square, View.GONE); } else { expandedIconResId = R.id.icon_square; expandedRV.setViewVisibility(R.id.icon_slim, View.GONE); expandedRV.setViewVisibility(R.id.icon_square, View.VISIBLE); } // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this); final Notification notification = builder.setSmallIcon(smallIcon).setShowWhen(false).setOngoing(true) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_TRANSPORT).setContentIntent(mRemoteStartPendingIntent) .setContent(collapsedRV).build(); // This is a convoluted way of loading the image and showing the // notification, but it's what works with Picasso and is efficient. // Here's what's going on: // // 1. The image is loaded asynchronously into a Target, and only after // it is loaded is the notification shown. Using targets is a lot more // efficient than letting Picasso load it directly into the // notification imageview, which causes a lot of flickering // // 2. The target needs to be static, because Picasso only keeps a weak // reference to it, so we need to keed a strong reference and reset it // to null when we're done. We also need to check if it is not null in // case a previous request hasn't finished yet. // // 3. We can only show the notification after the bitmap is loaded into // the target, so it is done in the callback // // 4. We specifically resize the image to the same dimensions used in // the remote, so that Picasso reuses it in the remote and here from the cache Resources resources = this.getResources(); final int posterWidth = resources.getDimensionPixelOffset(R.dimen.now_playing_poster_width); final int posterHeight = isVideo ? resources.getDimensionPixelOffset(R.dimen.now_playing_poster_height) : posterWidth; if (picassoTarget == null) { picassoTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { showNotification(bitmap); } @Override public void onBitmapFailed(Drawable errorDrawable) { CharacterDrawable avatarDrawable = UIUtils.getCharacterAvatar(NotificationService.this, title); showNotification(Utils.drawableToBitmap(avatarDrawable, posterWidth, posterHeight)); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } private void showNotification(Bitmap bitmap) { collapsedRV.setImageViewBitmap(R.id.icon, bitmap); if (Utils.isJellybeanOrLater()) { notification.bigContentView = expandedRV; expandedRV.setImageViewBitmap(expandedIconResId, bitmap); } NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notification); picassoTarget = null; } }; // Load the image HostManager hostManager = HostManager.getInstance(this); hostManager.getPicasso().load(hostManager.getHostInfo().getImageUrl(poster)) .resize(posterWidth, posterHeight).into(picassoTarget); } }
From source file:net.naonedbus.appwidget.HoraireWidgetProvider.java
/** * Prparer le widget avec les horaires.//from w w w . j a v a 2 s . c om * * @param views * @param favori */ protected void prepareWidgetViewHoraires(final Context context, final RemoteViews views, final Favori favori, final List<Horaire> nextHoraires) { final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context); CharSequence content = ""; if (nextHoraires.size() > 0) { // Programmer si besoin l'alarme scheduleUpdate(context, nextHoraires.get(0).getHoraire().getMillis()); for (int i = 0; i < nextHoraires.size(); i++) { final Horaire horaire = nextHoraires.get(i); content = TextUtils.concat(content, FormatUtils.formatTimeAmPm(context, timeFormat.format(horaire.getHoraire().toDate()))); if (i < nextHoraires.size() - 1) { content = TextUtils.concat(content, " \u2022 "); } } } else { content = context.getString(R.string.msg_aucun_depart_24h); } views.setTextViewText(R.id.itemTime, content); views.setViewVisibility(R.id.widgetProgress, View.GONE); }