Example usage for android.widget RemoteViews setOnClickPendingIntent

List of usage examples for android.widget RemoteViews setOnClickPendingIntent

Introduction

In this page you can find the example usage for android.widget RemoteViews setOnClickPendingIntent.

Prototype

public void setOnClickPendingIntent(int viewId, PendingIntent pendingIntent) 

Source Link

Document

Equivalent to calling android.view.View#setOnClickListener(android.view.View.OnClickListener) to launch the provided PendingIntent .

Usage

From source file:com.perm.DoomPlay.PlayingService.java

private RemoteViews getNotifViews(int layoutId) {
    RemoteViews views = new RemoteViews(getPackageName(), layoutId);

    Audio audio = audios.get(indexCurrentTrack);

    views.setTextViewText(R.id.notifTitle, audio.getTitle());
    views.setTextViewText(R.id.notifArtist, audio.getArtist());

    Bitmap cover = AlbumArtGetter.getBitmapFromStore(audio.getAid(), this);

    if (cover == null) {
        Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover);
        views.setImageViewBitmap(R.id.notifAlbum, tempBitmap);
        tempBitmap.recycle();/*  w w w .j a v a2s .  c om*/
    } else {
        //TODO: java.lang.IllegalArgumentException: RemoteViews for widget update exceeds
        // maximum bitmap memory usage (used: 3240000, max: 2304000)
        // The total memory cannot exceed that required to fill the device's screen once
        try {
            views.setImageViewBitmap(R.id.notifAlbum, cover);
        } catch (IllegalArgumentException e) {
            Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover);
            views.setImageViewBitmap(R.id.notifAlbum, tempBitmap);
            tempBitmap.recycle();
        } finally {
            cover.recycle();
        }
    }

    views.setImageViewResource(R.id.notifPlay, isPlaying ? R.drawable.widget_pause : R.drawable.widget_play);

    ComponentName componentName = new ComponentName(this, PlayingService.class);

    Intent intentPlay = new Intent(actionPlay);
    intentPlay.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifPlay, PendingIntent.getService(this, 0, intentPlay, 0));

    Intent intentNext = new Intent(actionNext);
    intentNext.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifNext, PendingIntent.getService(this, 0, intentNext, 0));

    Intent intentPrevious = new Intent(actionPrevious);
    intentPrevious.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifPrevious, PendingIntent.getService(this, 0, intentPrevious, 0));

    Intent intentClose = new Intent(actionClose);
    intentClose.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifClose, PendingIntent.getService(this, 0, intentClose, 0));

    return 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 w  w  .j a v a  2 s .co  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:com.piusvelte.taplock.client.core.TapLockService.java

private void buildWidget(int appWidgetId) {
    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.widget);
    String deviceName = null;/*www .  jav a  2  s  . c o m*/
    for (JSONObject deviceJObj : mDevices) {
        if (deviceJObj.has(KEY_WIDGETS) && deviceJObj.has(KEY_NAME)) {
            JSONArray widgetsJArr = null;
            try {
                widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (widgetsJArr != null) {
                for (int i = 0, l = widgetsJArr.length(); (i < l) && (deviceName == null); i++) {
                    int widgetId;
                    try {
                        widgetId = widgetsJArr.getInt(i);
                    } catch (JSONException e) {
                        widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
                        e.printStackTrace();
                    }
                    if ((widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) && (appWidgetId == widgetId)) {
                        try {
                            deviceName = deviceJObj.getString(KEY_NAME);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
            if (deviceName != null)
                break;
        }
    }
    if (deviceName == null)
        deviceName = "unknown";
    rv.setTextViewText(R.id.device_name, deviceName);
    rv.setOnClickPendingIntent(R.id.widget_icon,
            PendingIntent.getActivity(this, 0,
                    TapLock.getPackageIntent(this, TapLockToggle.class)
                            .setData(Uri.parse(String.format(getString(R.string.device_uri), deviceName))),
                    Intent.FLAG_ACTIVITY_NEW_TASK));
    AppWidgetManager.getInstance(this).updateAppWidget(appWidgetId, rv);
}

From source file:github.daneren2005.dsub.util.Util.java

private static void setupViews(RemoteViews rv, Context context, MusicDirectory.Entry song, boolean playing) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();
    String arist = song.getArtist();
    String album = song.getAlbum();

    // Set the album art.
    try {//from  w ww. ja va2s  .  c om
        int size = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight();
        Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, song, size);
        if (bitmap == null) {
            // set default album art
            rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
        } else {
            rv.setImageViewBitmap(R.id.notification_image, bitmap);
        }
    } catch (Exception x) {
        Log.w(TAG, "Failed to get notification cover art", x);
        rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
    }

    // set the text for the notifications
    rv.setTextViewText(R.id.notification_title, title);
    rv.setTextViewText(R.id.notification_artist, arist);
    rv.setTextViewText(R.id.notification_album, album);

    Pair<Integer, Integer> colors = getNotificationTextColors(context);
    if (colors.getFirst() != null) {
        rv.setTextColor(R.id.notification_title, colors.getFirst());
    }
    if (colors.getSecond() != null) {
        rv.setTextColor(R.id.notification_artist, colors.getSecond());
    }

    if (!playing) {
        rv.setImageViewResource(R.id.control_pause, R.drawable.notification_play);
        rv.setImageViewResource(R.id.control_previous, R.drawable.notification_stop);
    }

    // Create actions for media buttons
    PendingIntent pendingIntent;
    if (playing) {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_PREVIOUS");
        prevIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(R.id.control_previous, pendingIntent);
    } else {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_STOP");
        prevIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_STOP));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(R.id.control_previous, pendingIntent);
    }

    Intent pauseIntent = new Intent("KEYCODE_MEDIA_PLAY_PAUSE");
    pauseIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    pauseIntent.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
    pendingIntent = PendingIntent.getService(context, 0, pauseIntent, 0);
    rv.setOnClickPendingIntent(R.id.control_pause, pendingIntent);

    Intent nextIntent = new Intent("KEYCODE_MEDIA_NEXT");
    nextIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    nextIntent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT));
    pendingIntent = PendingIntent.getService(context, 0, nextIntent, 0);
    rv.setOnClickPendingIntent(R.id.control_next, pendingIntent);
}

From source file:com.zertinteractive.wallpaper.MainActivity.java

@SuppressLint("NewApi")
public void setNotification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager notificationManager = (NotificationManager) getSystemService(ns);

    @SuppressWarnings("deprecation")
    Notification notification = new Notification(R.drawable.ic_launcher, "Ticker Text",
            System.currentTimeMillis());

    RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.romantic_wallpaper);

    //the intent that is started when the notification is clicked (works)
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.contentView = notificationView;
    notification.contentIntent = pendingNotificationIntent;
    //        notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.flags = Notification.FLAG_LOCAL_ONLY;

    //this is the intent that is supposed to be called when the button is clicked
    Intent switchIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
    ///* w ww  .j ava2  s .c o  m*/
    notificationView.setOnClickPendingIntent(R.id.download_notification, pendingSwitchIntent);
    notificationManager.notify(1, notification);
}

From source file:github.daneren2005.dsub.util.Notifications.java

private static void setupViews(RemoteViews rv, Context context, MusicDirectory.Entry song, boolean expanded,
        boolean playing, boolean remote) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();
    String arist = song.getArtist();
    String album = song.getAlbum();

    // Set the album art.
    try {/*  w  w w.  j  ava 2 s  .com*/
        ImageLoader imageLoader = SubsonicActivity.getStaticImageLoader(context);
        Bitmap bitmap = null;
        if (imageLoader != null) {
            bitmap = imageLoader.getCachedImage(context, song, false);
        }
        if (bitmap == null) {
            // set default album art
            rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
        } else {
            rv.setImageViewBitmap(R.id.notification_image, bitmap);
        }
    } catch (Exception x) {
        Log.w(TAG, "Failed to get notification cover art", x);
        rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
    }

    // set the text for the notifications
    rv.setTextViewText(R.id.notification_title, title);
    rv.setTextViewText(R.id.notification_artist, arist);
    rv.setTextViewText(R.id.notification_album, album);

    boolean persistent = Util.getPreferences(context)
            .getBoolean(Constants.PREFERENCES_KEY_PERSISTENT_NOTIFICATION, false);
    if (persistent) {
        if (expanded) {
            rv.setImageViewResource(R.id.control_pause,
                    playing ? R.drawable.notification_pause : R.drawable.notification_start);
        } else {
            rv.setImageViewResource(R.id.control_previous,
                    playing ? R.drawable.notification_pause : R.drawable.notification_start);
            rv.setImageViewResource(R.id.control_pause, R.drawable.notification_forward);
            rv.setImageViewResource(R.id.control_next, R.drawable.notification_close);
        }
    }

    // Create actions for media buttons
    PendingIntent pendingIntent;
    int previous = 0, pause = 0, next = 0, close = 0;
    if (persistent && !expanded) {
        pause = R.id.control_previous;
        next = R.id.control_pause;
        close = R.id.control_next;
    } else {
        previous = R.id.control_previous;
        pause = R.id.control_pause;
        next = R.id.control_next;
    }

    if ((remote || persistent) && close == 0 && expanded) {
        close = R.id.notification_close;
        rv.setViewVisibility(close, View.VISIBLE);
    }

    if (previous > 0) {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_PREVIOUS");
        prevIntent.setComponent(new ComponentName(context, DownloadService.class));
        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(previous, pendingIntent);
    }
    if (pause > 0) {
        if (playing) {
            Intent pauseIntent = new Intent("KEYCODE_MEDIA_PLAY_PAUSE");
            pauseIntent.setComponent(new ComponentName(context, DownloadService.class));
            pauseIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
            pendingIntent = PendingIntent.getService(context, 0, pauseIntent, 0);
            rv.setOnClickPendingIntent(pause, pendingIntent);
        } else {
            Intent prevIntent = new Intent("KEYCODE_MEDIA_START");
            prevIntent.setComponent(new ComponentName(context, DownloadService.class));
            prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY));
            pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
            rv.setOnClickPendingIntent(pause, pendingIntent);
        }
    }
    if (next > 0) {
        Intent nextIntent = new Intent("KEYCODE_MEDIA_NEXT");
        nextIntent.setComponent(new ComponentName(context, DownloadService.class));
        nextIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT));
        pendingIntent = PendingIntent.getService(context, 0, nextIntent, 0);
        rv.setOnClickPendingIntent(next, pendingIntent);
    }
    if (close > 0) {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_STOP");
        prevIntent.setComponent(new ComponentName(context, DownloadService.class));
        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(close, pendingIntent);
    }
}

From source file:com.nogago.android.tracks.widgets.TrackWidgetProvider.java

/**
 * Updates view.//w w w. j  a v  a 2s . c o m
 * 
 * @param remoteViews the remote views
 */
private void updateView(RemoteViews remoteViews) {
    Track track = selectedTrackId != PreferencesUtils.SELECTED_TRACK_ID_DEFAULT
            ? myTracksProviderUtils.getTrack(selectedTrackId)
            : myTracksProviderUtils.getLastTrack();
    TripStatistics tripStatistics = track == null ? null : track.getTripStatistics();
    String distance = tripStatistics == null ? unknown
            : StringUtils.formatDistance(context, tripStatistics.getTotalDistance(), metricUnits);
    int timeLabelId = useTotalTime ? R.string.stats_total_time : R.string.stats_moving_time;
    String time = tripStatistics == null ? unknown
            : StringUtils.formatElapsedTime(
                    useTotalTime ? tripStatistics.getTotalTime() : tripStatistics.getMovingTime());
    int speedLabelId;
    if (useTotalTime) {
        speedLabelId = reportSpeed ? R.string.stats_average_speed : R.string.stats_average_pace;
    } else {
        speedLabelId = reportSpeed ? R.string.stats_average_moving_speed : R.string.stats_average_moving_pace;
    }

    String speed = tripStatistics == null ? unknown
            : StringUtils.formatSpeed(context,
                    useTotalTime ? tripStatistics.getAverageSpeed() : tripStatistics.getAverageMovingSpeed(),
                    metricUnits, reportSpeed);
    remoteViews.setTextViewText(R.id.track_widget_distance_value, distance);
    remoteViews.setTextViewText(R.id.track_widget_time_label, context.getString(timeLabelId));
    remoteViews.setTextViewText(R.id.track_widget_time_value, time);
    remoteViews.setTextViewText(R.id.track_widget_speed_label, context.getString(speedLabelId));
    remoteViews.setTextViewText(R.id.track_widget_speed_value, speed);

    Intent intent;
    if (track != null) {
        intent = IntentUtils.newIntent(context, TrackDetailActivity.class)
                .putExtra(TrackDetailActivity.EXTRA_TRACK_ID, track.getId());
    } else {
        intent = IntentUtils.newIntent(context, TrackListActivity.class);
    }
    TaskStackBuilder taskStackBuilder = TaskStackBuilder.from(context);
    taskStackBuilder.addNextIntent(intent);
    PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, 0);
    remoteViews.setOnClickPendingIntent(R.id.track_widget_statistics, pendingIntent);
    remoteViews.setOnClickPendingIntent(R.id.track_widget_icon, pendingIntent);
}

From source file:ua.mkh.weather.MainActivity.java

private void create_notif() {
    // TODO Auto-generated method stub
    // Prepare intent which is triggered if the
    // notification is selected
    String tittle = textView3.getText().toString();
    String subject = textView3.getText().toString();
    String body = "";
    /*/* w  w  w. ja  va 2  s.c o  m*/
    NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notify=new Notification((Integer)img1.getTag(),tittle,System.currentTimeMillis());
    PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
            
    notify.setLatestEventInfo(getApplicationContext(),subject,body,pending);
    notif.notify(0, notify);
            
            
    final NotificationManager mgr=
    (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification note=new Notification((Integer)img1.getTag(),
      "",
                                                System.currentTimeMillis());
                 
        // This pending intent will open after notification click
        PendingIntent i=PendingIntent.getActivity(this, 0,
                                        new Intent(),
                                        0);
                 
        note.setLatestEventInfo(this, tittle,
      "", i);
                 
        //After uncomment this line you will see number of notification arrived
        //note.number=2;
        mgr.notify(1, note);
                
                
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        Resources r = getResources();
        Notification notification = new NotificationCompat.Builder(this)
        .setTicker("Tiket")
        .setSmallIcon(android.R.drawable.ic_menu_report_image)
        .setContentTitle("Title")
        .setContentText("Context Text")
        .setContentIntent(pi)
        .setAutoCancel(true)
        .build();
            
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    */

    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContent(remoteViews);
    // Creates an explicit intent for an Activity in your app  
    Intent resultIntent = new Intent(this, MainActivity.class);
    // The stack builder object will contain an artificial back stack for  
    // the  
    // started Activity.  
    // This ensures that navigating backward from the Activity leads out of  
    // your application to the Home screen.  
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)  
    stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack  
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setOnClickPendingIntent(R.id.button1, resultPendingIntent);
    remoteViews.setTextViewText(R.id.textView1, nnn);
    remoteViews.setTextColor(R.id.textView1, getResources().getColor(R.color.white));
    remoteViews.setImageViewResource(R.id.imageView1, (Integer) img1.getTag());
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.  
    mNotificationManager.notify(100, mBuilder.build());

}

From source file:com.irccloud.android.Notifications.java

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title,
        String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network,
        String auto_messages[]) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());

    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext())
                    .setContentTitle(title + ((network != null) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.dark_blue))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE);
        String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound");
        if (ringtone != null && ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }/* w  w  w .j a  v a 2 s .  c om*/

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(
                    android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE);
        else
            builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS);
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    if (replyIntent != null) {
        WearableExtender extender = new WearableExtender();
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
        extender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_reply, "Reply", replyPendingIntent)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                        .build());

        if (count > 1 && wear_text != null)
            extender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true))
                            .build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (auto_messages != null) {
            for (String m : auto_messages) {
                if (m != null && m.length() > 0) {
                    unreadConvBuilder.addMessage(m);
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(extender)
                .extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    android.app.Notification notification = builder.build();

    RemoteViews contentView = new RemoteViews(
            IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification);
    contentView.setTextViewText(R.id.title, title + " (" + network + ")");
    contentView.setTextViewText(R.id.text,
            (count == 1) ? Html.fromHtml(text) : (count + " unread highlights."));
    contentView.setLong(R.id.time, "setTime", eids[0] / 1000);
    notification.contentView = contentView;

    if (Build.VERSION.SDK_INT >= 16 && big_text != null) {
        RemoteViews bigContentView = new RemoteViews(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                R.layout.notification_expanded);
        bigContentView.setTextViewText(R.id.title,
                title + (!title.equals(network) ? (" (" + network + ")") : ""));
        bigContentView.setTextViewText(R.id.text, big_text);
        bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
        if (count > 3) {
            bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
            bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
        } else {
            bigContentView.setViewVisibility(R.id.more, View.GONE);
        }
        if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
            bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
            bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
            i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
            i.setData(Uri.parse("irccloud-bid://" + bid));
            i.putExtras(replyIntent);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent quickReplyIntent = PendingIntent.getActivity(
                    IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
        }
        notification.bigContentView = bigContentView;
    }

    return notification;
}

From source file:com.darshancomputing.BatteryIndicatorPro.BatteryInfoService.java

private void updateWidgets(BatteryInfo info) {
    //Intent mainWindowIntent = new Intent(this, BatteryInfoActivity.class);
    //PendingIntent mainWindowPendingIntent = PendingIntent.getActivity(this, RC_MAIN, mainWindowIntent, 0);
    //PendingIntent currentInfoPendingIntent = PendingIntent.getActivity(this, RC_MAIN, currentInfoIntent, 0);

    if (info == null) {
        cwbg.setLevel(0);/* w ww .j a va 2s  .c  o m*/
    } else {
        bl.setLevel(info.percent);
        cwbg.setLevel(info.percent);
    }

    for (Integer widgetId : widgetIds) {
        RemoteViews rv;

        android.appwidget.AppWidgetProviderInfo awpInfo = widgetManager.getAppWidgetInfo(widgetId);
        if (awpInfo == null)
            continue; // Based on Developer Console crash reports, this can be null sometimes

        int initLayout = awpInfo.initialLayout;

        if (initLayout == R.layout.circle_app_widget) {
            rv = new RemoteViews(getPackageName(), R.layout.circle_app_widget);
            rv.setImageViewBitmap(R.id.circle_widget_image_view, cwbg.getBitmap());
        } else {
            rv = new RemoteViews(getPackageName(), R.layout.full_app_widget);

            if (info == null) {
                rv.setImageViewBitmap(R.id.battery_level_view, cwbg.getBitmap());
                rv.setTextViewText(R.id.fully_charged, "");
                rv.setTextViewText(R.id.time_remaining, "");
                rv.setTextViewText(R.id.until_what, "");
            } else {
                rv.setImageViewBitmap(R.id.battery_level_view, bl.getBitmap());

                if (info.prediction.what == BatteryInfo.Prediction.NONE) {
                    rv.setTextViewText(R.id.fully_charged, str.timeRemaining(info));
                    rv.setTextViewText(R.id.time_remaining, "");
                    rv.setTextViewText(R.id.until_what, "");
                } else {
                    rv.setTextViewText(R.id.fully_charged, "");
                    rv.setTextViewText(R.id.time_remaining, str.timeRemaining(info));
                    rv.setTextViewText(R.id.until_what, str.untilWhat(info));
                }
            }
        }

        if (info == null)
            rv.setTextViewText(R.id.level, "XX" + str.percent_symbol);
        else
            rv.setTextViewText(R.id.level, "" + info.percent + str.percent_symbol);

        rv.setOnClickPendingIntent(R.id.widget_layout, currentInfoPendingIntent);
        widgetManager.updateAppWidget(widgetId, rv);
    }
}