Example usage for android.app NotificationManager cancel

List of usage examples for android.app NotificationManager cancel

Introduction

In this page you can find the example usage for android.app NotificationManager cancel.

Prototype

public void cancel(int id) 

Source Link

Document

Cancel a previously shown notification.

Usage

From source file:com.chen.mail.utils.NotificationUtils.java

/**
 * Validate the notifications notification.
 *//*w  w  w  .  j  ava 2s .  c  o  m*/
private static void validateNotifications(Context context, final Folder folder, final Account account,
        boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key) {

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final NotificationMap notificationMap = getNotificationMap(context);
    if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
        LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b",
                createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention);
    } else {
        LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b",
                notificationMap.size(), getAttention);
    }
    // The number of unread messages for this account and label.
    final Integer unread = notificationMap.getUnread(key);
    final int unreadCount = unread != null ? unread.intValue() : 0;
    final Integer unseen = notificationMap.getUnseen(key);
    int unseenCount = unseen != null ? unseen.intValue() : 0;

    Cursor cursor = null;

    try {
        final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon();
        uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString());
        // Do not allow this quick check to disrupt any active network-enabled conversation
        // cursor.
        uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK,
                Boolean.FALSE.toString());
        cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION,
                null, null, null);
        if (cursor == null) {
            // This folder doesn't exist.
            LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist");
            clearFolderNotification(context, account, folder, false);
            return;
        }
        final int cursorUnseenCount = cursor.getCount();

        // Make sure the unseen count matches the number of items in the cursor.  But, we don't
        // want to overwrite a 0 unseen count that was specified in the intent
        if (unseenCount != 0 && unseenCount != cursorUnseenCount) {
            LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count.  unseen: %d cursor count: %d",
                    unseenCount, cursorUnseenCount);
            unseenCount = cursorUnseenCount;
        }

        // For the purpose of the notifications, the unseen count should be capped at the num of
        // unread conversations.
        if (unseenCount > unreadCount) {
            unseenCount = unreadCount;
        }

        final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

        if (unseenCount == 0) {
            LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s",
                    LogUtils.sanitizeName(LOG_TAG, account.name),
                    LogUtils.sanitizeName(LOG_TAG, folder.persistentId));
            nm.cancel(notificationId);
            return;
        }

        // We now have all we need to create the notification and the pending intent
        PendingIntent clickIntent;

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
        notification.setSmallIcon(R.drawable.stat_notify_email);
        notification.setTicker(account.name);

        final long when;

        final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId);
        if (oldWhen != 0) {
            when = oldWhen;
        } else {
            when = System.currentTimeMillis();
        }

        notification.setWhen(when);

        // The timestamp is now stored in the notification, so we can remove it from here
        NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

        // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a
        // notification.  Also this intent gets fired when the user taps on a notification as
        // the AutoCancel flag has been set
        final Intent cancelNotificationIntent = new Intent(
                MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
        cancelNotificationIntent.setPackage(context.getPackageName());
        cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri));
        cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder);

        notification.setDeleteIntent(
                PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0));

        // Ensure that the notification is cleared when the user selects it
        notification.setAutoCancel(true);

        boolean eventInfoConfigured = false;

        final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox);
        final FolderPreferences folderPreferences = new FolderPreferences(context, account.getEmailAddress(),
                folder, isInbox);

        if (isInbox) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getEmailAddress());
            moveNotificationSetting(accountPreferences, folderPreferences);
        }

        if (!folderPreferences.areNotificationsEnabled()) {
            LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying");
            // Don't notify
            return;
        }

        if (unreadCount > 0) {
            // How can I order this properly?
            if (cursor.moveToNext()) {
                final Intent notificationIntent;

                // Launch directly to the conversation, if there is only 1 unseen conversation
                final boolean launchConversationMode = (unseenCount == 1);
                if (launchConversationMode) {
                    notificationIntent = createViewConversationIntent(context, account, folder, cursor);
                } else {
                    notificationIntent = createViewConversationIntent(context, account, folder, null);
                }

                Analytics.getInstance().sendEvent("notification_create",
                        launchConversationMode ? "conversation" : "conversation_list",
                        folder.getTypeDescription(), unseenCount);

                if (notificationIntent == null) {
                    LogUtils.e(LOG_TAG, "Null intent when building notification");
                    return;
                }

                // Amend the click intent with a hint that its source was a notification,
                // but remove the hint before it's used to generate notification action
                // intents. This prevents the following sequence:
                // 1. generate single notification
                // 2. user clicks reply, then completes Compose activity
                // 3. main activity launches, gets FROM_NOTIFICATION hint in intent
                notificationIntent.putExtra(Utils.EXTRA_FROM_NOTIFICATION, true);
                clickIntent = PendingIntent.getActivity(context, -1, notificationIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                notificationIntent.removeExtra(Utils.EXTRA_FROM_NOTIFICATION);

                configureLatestEventInfoFromConversation(context, account, folderPreferences, notification,
                        cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when);
                eventInfoConfigured = true;
            }
        }

        final boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        final String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled();

        if (!ignoreUnobtrusiveSetting && notifyOnce) {
            // If the user has "unobtrusive notifications" enabled, only alert the first time
            // new mail is received in this account.  This is the default behavior.  See
            // bugs 2412348 and 2413490.
            notification.setOnlyAlertOnce(true);
        }

        LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.name),
                Boolean.toString(folderPreferences.isNotificationVibrateEnabled()));

        int defaults = 0;

        /*
         * We do not want to notify if this is coming back from an Undo notification, hence the
         * oldWhen check.
         */
        if (getAttention && oldWhen == 0) {
            final AccountPreferences accountPreferences = new AccountPreferences(context, account.name);
            if (accountPreferences.areNotificationsEnabled()) {
                if (vibrate) {
                    defaults |= Notification.DEFAULT_VIBRATE;
                }

                notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri));
                LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s",
                        LogUtils.sanitizeName(LOG_TAG, account.name), vibrate, ringtoneUri);
            }
        }

        // TODO(skennedy) Why do we do any of the above if we're just going to bail here?
        if (eventInfoConfigured) {
            defaults |= Notification.DEFAULT_LIGHTS;
            notification.setDefaults(defaults);

            if (oldWhen != 0) {
                // We do not want to display the ticker again if we are re-displaying this
                // notification (like from an Undo notification)
                notification.setTicker(null);
            }

            nm.notify(notificationId, notification.build());
        } else {
            LogUtils.i(LOG_TAG, "event info not configured - not notifying");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.intel.xdk.notification.Notification.java

public void showBusyIndicator() {
    if (spinner != null)
        return;/* w w  w .j  a  va  2 s .c  o  m*/

    //get a reference to the service
    String ns = Context.NOTIFICATION_SERVICE;
    final NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(ns);
    //create the notification instance
    int icon = activity.getResources().getIdentifier("spinner_n", "drawable", activity.getPackageName());//R.drawable.spinner_n;

    PackageManager packageManager = activity.getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(activity.getPackageName(), 0);
    } catch (final NameNotFoundException e) {
    }
    final String title = (String) ((applicationInfo != null)
            ? packageManager.getApplicationLabel(applicationInfo)
            : "???");

    CharSequence tickerText = title + " is busy...";//activity.getString(R.string.app_name) + " is busy...";
    long when = System.currentTimeMillis();
    final android.app.Notification notification = new android.app.Notification(icon, tickerText, when);
    //initialize latest event info
    Context context = activity.getApplicationContext();
    CharSequence contentTitle = title + " is busy...";//activity.getString(R.string.app_name) + " is busy...";
    CharSequence contentText = "...just a moment please.";
    Intent notificationIntent = new Intent(activity, activity.getClass());
    PendingIntent contentIntent = PendingIntent.getActivity(activity, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    //make notification non-cancellable
    notification.flags = notification.flags | android.app.Notification.FLAG_NO_CLEAR;
    //show in status bar
    mNotificationManager.notify(BUSY_INDICATOR, notification);
    //animate the icon
    spinner = new Thread("intel.xdk.notification:showBusyIndicator") {
        public void run() {
            //frame pointer
            int currentFrame = 0;
            //frame array
            //int[] frames = new int[]{R.drawable.spinner_ne, R.drawable.spinner_e, R.drawable.spinner_se, R.drawable.spinner_s, R.drawable.spinner_sw, R.drawable.spinner_w, R.drawable.spinner_nw, R.drawable.spinner_n};
            int[] frames = new int[] {
                    activity.getResources().getIdentifier("spinner_ne", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_e", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_se", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_s", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_sw", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_w", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_nw", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_n", "drawable", activity.getPackageName()) };
            Thread thisThread = Thread.currentThread();
            while (spinner == thisThread) {
                //loop over the frames, updating the icon every 200 ms
                currentFrame++;
                currentFrame %= frames.length;
                notification.icon = frames[currentFrame];
                mNotificationManager.notify(BUSY_INDICATOR, notification);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //when looping ends, remove notification from status bar
            mNotificationManager.cancel(BUSY_INDICATOR);
        }

        @Override
        protected void finalize() throws Throwable {
            //in case the process crashes, try to remove notification from status bar
            super.finalize();
            mNotificationManager.cancel(BUSY_INDICATOR);
        }
    };
    spinner.start();
}

From source file:com.akop.bach.service.XboxLiveServiceClient.java

private void notifyBeacons(XboxLiveAccount account, HashMap<String, long[]> matching,
        HashMap<String, long[]> lastMatching) {
    Context context = getContext();
    NotificationManager mgr = getNotificationManager();

    if (App.getConfig().logToConsole()) {
        if (lastMatching != null && lastMatching.size() > 0) {
            App.logv("Last matching:");

            for (String key : lastMatching.keySet()) {
                String s = "* BEACONS " + key + ": ";
                for (long friendId : lastMatching.get(key))
                    s += friendId + ",";

                App.logv(s);//from w  w w .  j av  a2  s.  c  o m
            }
        }

        if (matching.size() > 0) {
            App.logv("Now matching:");

            for (String key : matching.keySet()) {
                String s = "* BEACONS " + key + ": ";
                for (long friendId : matching.get(key))
                    s += friendId + ",";

                App.logv(s);
            }
        }
    }

    int notificationId = 0x40000 | (((int) account.getId() & 0xfff) << 4);
    String[] gameUids = new String[matching.keySet().size()];

    matching.keySet().toArray(gameUids);

    for (int i = 0; i < MAX_BEACONS; i++) {
        if (i < gameUids.length) {
            String gameUid = gameUids[i];
            long[] matchingFriends = matching.get(gameUid);

            if (!lastMatching.containsKey(gameUid)
                    || !areArraysEquivalent(matchingFriends, lastMatching.get(gameUid))) {
                if (matchingFriends.length > 0) {
                    String title = XboxLive.Games.getTitle(context, account, gameUid);
                    String message = null;
                    String ticker = null;

                    int iconOverlayNumber = 0;
                    Intent intent = null;

                    if (matchingFriends.length > 1) {
                        iconOverlayNumber = matchingFriends.length;
                        intent = new Intent(context, FriendList.class);
                        intent.putExtra("account", account);
                        ticker = context.getString(R.string.friends_playing_beaconed_game_title_f,
                                matchingFriends.length, title);
                        message = context.getString(R.string.friends_playing_beaconed_game_f,
                                matchingFriends.length, account.getDescription());
                    } else {
                        String friendScreenName = Friends.getGamertag(context, matchingFriends[0]);

                        intent = account.getFriendIntent(context, friendScreenName);
                        ticker = context.getString(R.string.friend_playing_beaconed_game_title_f,
                                friendScreenName, title);
                        message = context.getString(R.string.friend_playing_beaconed_game_f, friendScreenName,
                                account.getDescription());
                    }

                    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                    builder.setContentIntent(PendingIntent.getActivity(context, 0, intent, 0))
                            .setSmallIcon(R.drawable.xbox_stat_notify_beacon).setContentTitle(title)
                            .setContentText(message).setTicker(ticker).setWhen(System.currentTimeMillis())
                            .setAutoCancel(true).setOnlyAlertOnce(true).setNumber(iconOverlayNumber)
                            .setLights(DEFAULT_LIGHTS_COLOR, DEFAULT_LIGHTS_ON_MS, DEFAULT_LIGHTS_OFF_MS)
                            .setSound(account.getRingtoneUri());

                    if (account.isVibrationEnabled())
                        builder.setDefaults(Notification.DEFAULT_VIBRATE);

                    Notification notification = builder.getNotification();
                    mgr.notify(notificationId, notification);
                } else {
                    mgr.cancel(notificationId);
                }
            }
        } else {
            mgr.cancel(notificationId);
        }

        notificationId++;
    }
}

From source file:org.mdc.chess.MDChess.java

/**
 * Set/clear the "heavy CPU usage" notification.
 *//*from   ww  w.  ja v  a 2  s.c o m*/
private void setNotification(boolean show) {
    if (notificationActive == show) {
        return;
    }
    notificationActive = show;
    final int cpuUsage = 1;
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    if (show) {
        int icon = R.mipmap.ic_launcher;
        CharSequence tickerText = getString(R.string.heavy_cpu_usage);
        long when = System.currentTimeMillis();
        Context context = getApplicationContext();
        CharSequence contentTitle = getString(R.string.background_processing);
        CharSequence contentText = getString(R.string.lot_cpu_power);
        Intent notificationIntent = new Intent(this, CPUWarning.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        @SuppressWarnings("deprecation")
        Notification notification = new Notification.Builder(context).setSmallIcon(icon).setTicker(tickerText)
                .setWhen(when).setOngoing(true).setContentTitle(contentTitle).setContentText(contentText)
                .setContentIntent(contentIntent).getNotification();
        mNotificationManager.notify(cpuUsage, notification);
    } else {
        mNotificationManager.cancel(cpuUsage);
    }
}

From source file:org.sipdroid.sipua.ui.Receiver.java

public static void onText(int type, String text, int mInCallResId, long base) {
    if (mSipdroidEngine != null && type == REGISTER_NOTIFICATION + mSipdroidEngine.pref) {
        cache_text = text;//from www  .ja  va  2 s.  com
        cache_res = mInCallResId;
    }
    if (type >= REGISTER_NOTIFICATION && mInCallResId == R.drawable.sym_presence_available
            && !PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(
                    org.sipdroid.sipua.ui.Settings.PREF_REGISTRATION,
                    org.sipdroid.sipua.ui.Settings.DEFAULT_REGISTRATION))
        text = null;
    NotificationManager mNotificationMgr = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    if (text != null) {
        Notification notification = new Notification();
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        notification.icon = mInCallResId;
        if (type == MISSED_CALL_NOTIFICATION) {
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            //TODO
            /*notification.setLatestEventInfo(mContext, text, mContext.getString(R.string.app_name),
                  PendingIntent.getActivity(mContext, 0, createCallLogIntent(), 0));
            if (PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(org.sipdroid.sipua.ui.Settings.PREF_NOTIFY, org.sipdroid.sipua.ui.Settings.DEFAULT_NOTIFY)) {
               notification.flags |= Notification.FLAG_SHOW_LIGHTS;
               notification.ledARGB = 0xff0000ff;  blue 
               notification.ledOnMS = 125;
               notification.ledOffMS = 2875;
            }*/
        } else {
            switch (type) {
            case MWI_NOTIFICATION:
                notification.flags |= Notification.FLAG_AUTO_CANCEL;
                notification.contentIntent = PendingIntent.getActivity(mContext, 0, createMWIIntent(), 0);
                notification.flags |= Notification.FLAG_SHOW_LIGHTS;
                notification.ledARGB = 0xff00ff00; /* green */
                notification.ledOnMS = 125;
                notification.ledOffMS = 2875;
                break;
            case AUTO_ANSWER_NOTIFICATION:
                notification.contentIntent = PendingIntent.getActivity(mContext, 0,
                        createIntent(AutoAnswer.class), 0);
                break;
            default:
                if (type >= REGISTER_NOTIFICATION && mSipdroidEngine != null
                        && type != REGISTER_NOTIFICATION + mSipdroidEngine.pref
                        && mInCallResId == R.drawable.sym_presence_available) {
                    int key = type - REGISTER_NOTIFICATION;
                    Intent in = createIntent(ChangeAccount.class);
                    in.setAction(Long.toString(type));
                    in.putExtra(ChangeAccount.ChangeAccountKey, key);
                    in.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    notification.contentIntent = PendingIntent.getActivity(mContext, key, in,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                } else
                    notification.contentIntent = PendingIntent.getActivity(mContext, 0,
                            createIntent(Sipdroid.class), 0);
                if (mInCallResId == R.drawable.sym_presence_away) {
                    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
                    notification.ledARGB = 0xffff0000; /* red */
                    notification.ledOnMS = 125;
                    notification.ledOffMS = 2875;
                }
                notification.flags |= Notification.FLAG_ONGOING_EVENT;
                break;
            }

            RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
                    R.layout.ongoing_call_notification);
            contentView.setImageViewResource(R.id.icon, notification.icon);
            if (base != 0) {
                contentView.setChronometer(R.id.text1, base, text + " (%s)", true);
            } else if (type >= REGISTER_NOTIFICATION) {
                if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                        org.sipdroid.sipua.ui.Settings.PREF_POS, org.sipdroid.sipua.ui.Settings.DEFAULT_POS))
                    contentView.setTextViewText(R.id.text2,
                            text + "/" + mContext.getString(R.string.settings_pos3));
                else
                    contentView.setTextViewText(R.id.text2, text);
                if (mSipdroidEngine != null)
                    contentView.setTextViewText(R.id.text1,
                            mSipdroidEngine.user_profiles[type - REGISTER_NOTIFICATION].username + "@"
                                    + mSipdroidEngine.user_profiles[type - REGISTER_NOTIFICATION].realm_orig);
            } else
                contentView.setTextViewText(R.id.text1, text);
            notification.contentView = contentView;
        }
        mNotificationMgr.notify(type, notification);
    } else {
        mNotificationMgr.cancel(type);
    }
    if (type != AUTO_ANSWER_NOTIFICATION)
        updateAutoAnswer();
    if (mSipdroidEngine != null && type >= REGISTER_NOTIFICATION
            && type != REGISTER_NOTIFICATION + mSipdroidEngine.pref)
        onText(REGISTER_NOTIFICATION + mSipdroidEngine.pref, cache_text, cache_res, 0);
}

From source file:edu.mit.viral.shen.DroidFish.java

/** Set/clear the "heavy CPU usage" notification. */
private final void setNotification(boolean show) {
    if (notificationActive == show)
        return;/*from   w ww  .j av a  2  s  .  com*/
    notificationActive = show;
    final int cpuUsage = 1;
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    if (show) {
        int icon = R.drawable.icon;
        CharSequence tickerText = getString(R.string.heavy_cpu_usage);
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        notification.flags |= Notification.FLAG_ONGOING_EVENT;

        Context context = getApplicationContext();
        CharSequence contentTitle = getString(R.string.background_processing);
        CharSequence contentText = getString(R.string.lot_cpu_power);
        Intent notificationIntent = new Intent(this, CPUWarning.class);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        mNotificationManager.notify(cpuUsage, notification);
    } else {
        mNotificationManager.cancel(cpuUsage);
    }
}

From source file:com.kasungunathilaka.sarigama.service.PlayerService.java

private void setupNotification(Song song, String notificationType) {
    Bitmap remote_picture = null;/*from  ww w  .  ja  va  2  s .  co m*/
    RemoteViews smallNotification;
    RemoteViews bigNotification;
    Notification notification;

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    if (song != null) {
        if (song.getSongImage().contentEquals("http://sarigama.lk/img/songs/default.jpg")) {
            remote_picture = BitmapFactory.decodeResource(PlayerService.this.getResources(),
                    R.drawable.default_song_art);
        } else {
            try {
                remote_picture = BitmapFactory
                        .decodeStream((InputStream) new URL(song.getSongImage()).getContent());
            } catch (Exception e) {
                remote_picture = BitmapFactory.decodeResource(PlayerService.this.getResources(),
                        R.drawable.default_song_art);
                e.printStackTrace();
            }
        }
    }

    switch (notificationType) {
    case HomeActivity.NOTIFICATION_TYPE_PLAY:
        try {
            smallNotification = new RemoteViews(getPackageName(), R.layout.notification_layout_small);
            smallNotification.setImageViewBitmap(R.id.ivSmallNotificationSongImage, remote_picture);
            smallNotification.setTextViewText(R.id.tvSmallNotificationSong, song.getSongTitle());
            smallNotification.setTextViewText(R.id.tvSmallNotificationArtist, song.getSongArtist());
            smallNotification.setImageViewResource(R.id.ibSmallPlay, R.drawable.ic_pause_white);
            smallNotification.setOnClickPendingIntent(R.id.flSmallPlay, playIntent);
            smallNotification.setOnClickPendingIntent(R.id.ivSmallNext, nextIntent);

            bigNotification = new RemoteViews(getPackageName(), R.layout.notification_layout_big);
            bigNotification.setImageViewBitmap(R.id.ivBigNotificationSongImage, remote_picture);
            bigNotification.setTextViewText(R.id.tvBigNotificationSong, song.getSongTitle());
            bigNotification.setTextViewText(R.id.tvBigNotificationArtist, song.getSongArtist());
            bigNotification.setImageViewResource(R.id.ibBigPlay, R.drawable.ic_pause_white);
            bigNotification.setOnClickPendingIntent(R.id.ibBigNext, nextIntent);
            bigNotification.setOnClickPendingIntent(R.id.ibBigPlay, playIntent);
            bigNotification.setOnClickPendingIntent(R.id.ibBigPrevious, previousIntent);

            notification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_play_white)
                    .setAutoCancel(false).setOngoing(true).setContent(smallNotification)
                    .setContentIntent(startIntent).build();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                notification.bigContentView = bigNotification;
            }
            notificationManager.notify(NOTIFICATION_ID, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    case HomeActivity.NOTIFICATION_TYPE_PAUSE:
        try {
            smallNotification = new RemoteViews(getPackageName(), R.layout.notification_layout_small);
            smallNotification.setImageViewResource(R.id.ibSmallPlay, R.drawable.ic_play_white);

            bigNotification = new RemoteViews(getPackageName(), R.layout.notification_layout_big);
            bigNotification.setImageViewBitmap(R.id.ivBigNotificationSongImage, remote_picture);
            bigNotification.setTextViewText(R.id.tvBigNotificationSong, song.getSongTitle());
            bigNotification.setTextViewText(R.id.tvBigNotificationArtist, song.getSongArtist());
            bigNotification.setImageViewResource(R.id.ibBigPlay, R.drawable.ic_play_white);
            bigNotification.setOnClickPendingIntent(R.id.ibBigNext, nextIntent);
            bigNotification.setOnClickPendingIntent(R.id.ibBigPlay, playIntent);
            bigNotification.setOnClickPendingIntent(R.id.ibBigPrevious, previousIntent);

            notification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_pause_white)
                    .setOngoing(false).setAutoCancel(false).setContent(smallNotification)
                    .setContentIntent(startIntent).build();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                notification.bigContentView = bigNotification;
            }
            notificationManager.notify(NOTIFICATION_ID, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    case HomeActivity.NOTIFICATION_TYPE_DISMISS:
        notificationManager.cancel(NOTIFICATION_ID);
        break;
    }
}

From source file:org.apache.cordova.plugins.DownloadManager.Downloader.java

public Boolean run() throws InterruptedException, JSONException {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            NotificationManager mNotifyManager;
            NotificationCompat.Builder mBuilder;
            Intent intent;/*from w  w  w. j a v a2 s. co  m*/
            PendingIntent pend;
            int mNotificationId;

            Log.d("PhoneGapLog", "dirName:  " + dirName);
            Log.d("PhoneGapLog", "fileName: " + fileName);
            try {

                File dir = new File(dirName);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                File file = new File(dirName, fileName);
                if (file.exists() && !overwrite) {
                    String temp_filename;
                    int i;
                    for (i = 1;; i++) { // test.txt -> test_1.txt -> test_2.tx -> ... while(file.exists())
                        temp_filename = fileName.substring(0, fileName.lastIndexOf('.')) + "_"
                                + String.valueOf(i) + fileName.substring(fileName.lastIndexOf('.'));
                        file = new File(dirName, temp_filename);
                        if (!file.exists()) {
                            fileName = temp_filename;
                            break;
                        }
                    }
                } else if (file.exists() && overwrite) {
                    file.getCanonicalFile().delete(); //Delete
                    file = new File(dirName, fileName); //Declare the same
                }

                intent = new Intent();
                intent.putExtra("cancel_download", 1);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                pend = PendingIntent.getActivity(cordova.getActivity(), 0, intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                mNotifyManager = (NotificationManager) cordova.getActivity()
                        .getSystemService(Activity.NOTIFICATION_SERVICE);
                mBuilder = new NotificationCompat.Builder(cordova.getActivity())
                        /*.setSmallIcon(android.R.drawable.ic_stat_notification)*/
                        .setContentTitle(notificationTitle)
                        /*.setSubText("Tap to CANCEL")*/
                        .setTicker(ticker).setContentIntent(pend).setContentText("0% - " + fileName);

                mNotificationId = new Random().nextInt(10000);

                URL url = new URL(fileUrl);
                HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
                ucon.setRequestMethod("GET");
                ucon.connect();
                InputStream is = ucon.getInputStream();
                byte[] buffer = new byte[1024];
                int readed = 0, progress = 0, totalReaded = 0, fileSize = ucon.getContentLength();

                // First Notification (id to Javascript) (not necessary necessary): 
                informProgress(id, true, fileSize, 0, dirName, fileName, callbackContext);

                FileOutputStream fos = new FileOutputStream(file);
                showToast(startToast, "short");
                int step = 0;
                while ((readed = is.read(buffer)) > 0 && downloading_ids.isId(id)) {
                    fos.write(buffer, 0, readed);
                    totalReaded += readed;
                    int newProgress = (int) (totalReaded * 100 / fileSize);
                    if (newProgress != progress & newProgress > step) {
                        if (useNotificationBar) {
                            mBuilder.setProgress(100, newProgress, false);
                            mBuilder.setContentText(step + "% - " + fileName);
                            mBuilder.setContentIntent(pend);
                            mNotifyManager.notify(mNotificationId, mBuilder.build());
                        }
                        informProgress(id, true, fileSize, step, dirName, fileName, callbackContext);
                        step = step + 1;
                    }
                }
                // Download canceled??
                if (!downloading_ids.isId(id)) {
                    showToast(cancelToast, "short");

                    fos.flush();
                    fos.close();
                    is.close();
                    ucon.disconnect();

                    if (useNotificationBar) {
                        mBuilder.setContentText("Download of \"" + fileName + "\" canceled").setProgress(0, 0,
                                false);
                        mNotifyManager.notify(mNotificationId, mBuilder.build());

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            Log.d("PhoneGapLog", "Downloader Plugin: Thread sleep error: " + e);
                        }

                        mNotifyManager.cancel(mNotificationId);
                    }

                    // Delete file:
                    file.getCanonicalFile().delete();

                    callbackContext.sendPluginResult(
                            new PluginResult(PluginResult.Status.OK, "Download properly canceled"));
                } else {
                    // Download Normal END (continue)
                    if (useNotificationBar) {
                        mBuilder.setContentText("Download of \"" + fileName + "\" completed").setProgress(0, 0,
                                false);
                        mNotifyManager.notify(mNotificationId, mBuilder.build());
                    }
                    showToast(endToast, "short");
                    informProgress(id, false, fileSize, step, dirName, fileName, callbackContext);
                    downloading_ids.del(id);
                }

                fos.flush();
                fos.close();
                is.close();
                ucon.disconnect();

                mNotifyManager.cancel(mNotificationId);

                if (!file.exists()) {
                    showToast("Download went wrong, please try again or contact the developer.", "long");
                    Log.e("PhoneGapLog", "Downloader Plugin: Error: Download went wrong.");
                }
                //callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
            } catch (FileNotFoundException e) {
                showToast(
                        "File does not exists or cannot connect to webserver, please try again or contact the developer.",
                        "long");
                Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR);
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
            } catch (IOException e) {
                showToast("Error downloading file, please try again or contact the developer.", "long");
                Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR);
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
            } catch (JSONException e) {
                e.printStackTrace();
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()));
            } catch (InterruptedException e) {
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage()));
            }
        }
    });
    return true;
}

From source file:org.distantshoresmedia.keyboard.LatinIME.java

private void setNotification(boolean visible) {
    final String ACTION = "org.distantshoresmedia.translationkeyboard.SHOW";
    final int ID = 1;
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

    if (visible && mNotificationReceiver == null) {
        int icon = R.drawable.icon;
        CharSequence text = "Keyboard notification enabled.";
        long when = System.currentTimeMillis();

        // TODO: clean this up?
        mNotificationReceiver = new NotificationReceiver(this);
        final IntentFilter pFilter = new IntentFilter(ACTION);
        registerReceiver(mNotificationReceiver, pFilter);

        Intent notificationIntent = new Intent(ACTION);

        PendingIntent contentIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, notificationIntent,
                0);/*from   w w  w. j  av  a  2 s.  c o m*/
        //PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        String title = "Show translationKeyboard Keyboard";
        String body = "Select this to open the keyboard. Disable in settings.";

        //            Notification notification = new Notification(icon, text, when);
        //
        //            notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
        //            notification.setLatestEventInfo(getApplicationContext(), title, body, contentIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());

        builder.setContentIntent(contentIntent).setSmallIcon(icon)
                .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), icon))
                .setTicker(body).setWhen(System.currentTimeMillis()).setAutoCancel(true).setContentTitle(title)
                .setContentText(body);
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;

        mNotificationManager.notify(ID, notification);
    } else if (mNotificationReceiver != null) {
        mNotificationManager.cancel(ID);
        unregisterReceiver(mNotificationReceiver);
        mNotificationReceiver = null;
    }
}