Example usage for android.content Context NOTIFICATION_SERVICE

List of usage examples for android.content Context NOTIFICATION_SERVICE

Introduction

In this page you can find the example usage for android.content Context NOTIFICATION_SERVICE.

Prototype

String NOTIFICATION_SERVICE

To view the source code for android.content Context NOTIFICATION_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.NotificationManager for informing the user of background events.

Usage

From source file:org.kaoriha.phonegap.plugins.releasenotification.Notifier.java

private void pollBackground() {
    if (getToken() == null) {
        rescheduleAfterFail();/*from  w  w  w.ja v  a2  s  .c o  m*/
        return;
    }

    ToNextReleasePolling tp = new ToNextReleasePolling();
    tp.poll();
    if (tp.isFailed) {
        Log.d(TAG, "ToNextReleasePolling failed");
        rescheduleAfterFail();
        return;
    }

    CataloguePolling cp = new CataloguePolling();
    cp.poll();
    if (cp.isFailed) {
        Log.d(TAG, "CataloguePolling failed");
        rescheduleAfterFail();
        return;
    }
    if (!cp.isNew) {
        if (tp.toNextRelease == -1) {
            schedule(RESCHEDULE_NEXT_UNKNOWN_SPAN);
        } else {
            schedule(tp.toNextRelease);
        }
        Log.d(TAG, "CataloguePolling not new");
        return;
    }

    String pushMessage;
    if (cp.catalogue.has(CATALOGUE_PUSH_MESSAGE_KEY)) {
        try {
            pushMessage = cp.catalogue.getString(CATALOGUE_PUSH_MESSAGE_KEY);
        } catch (JSONException e) {
            Log.i(TAG, "pollBackground()", e);
            pushMessage = pref.getString(SPKEY_DEFAULT_PUSH_MESSAGE, null);
        }
    } else {
        pushMessage = pref.getString(SPKEY_DEFAULT_PUSH_MESSAGE, null);
    }

    String lastSid;
    try {
        lastSid = getLastSid(cp.catalogue);
        if (lastSid.equals(pref.getString(SPKEY_LAST_SID, null))) {
            schedule(tp.toNextRelease);
        }
    } catch (JSONException e) {
        Log.d(TAG, "bad JSON", e);
        rescheduleAfterFail();
        return;
    }

    int icon = R.drawable.notification;
    Notification n = new Notification(icon, pushMessage, System.currentTimeMillis());
    n.flags = Notification.FLAG_AUTO_CANCEL;
    Intent i = new Intent(ctx, FlowerflowerActivity.class);
    i.setAction(Intent.ACTION_MAIN);
    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(ctx, 0, i, 0);
    n.setLatestEventInfo(ctx.getApplicationContext(), pref.getString(SPKEY_TITLE, null), pushMessage, pi);
    NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, n);

    pref.edit().putString(SPKEY_LAST_SID, lastSid).putString(SPKEY_LAST_CATALOGUE_ETAG, cp.etag).commit();

    clearFailRepeat();

    schedule(tp.toNextRelease);

    Log.d(TAG, "pollBackground() success");
}

From source file:com.miz.service.TraktTvShowsSyncService.java

private void showPostUpdateNotification() {
    // Remove the old one
    mNotificationManager.cancel(NOTIFICATION_ID);

    mBuilder = new NotificationCompat.Builder(getApplicationContext());
    mBuilder.setColor(getResources().getColor(R.color.color_primary));
    mBuilder.setTicker(getString(R.string.finishedTraktTvShowSync));
    mBuilder.setContentTitle(getString(R.string.finishedTraktTvShowSync));
    mBuilder.setSmallIcon(R.drawable.ic_done_white_24dp);
    mBuilder.setOngoing(false);//  w ww  . jav a 2s  .  c  o  m
    mBuilder.setAutoCancel(true);
    mBuilder.setOnlyAlertOnce(true);

    // Build notification
    Notification updateNotification = mBuilder.build();

    // Show the notification
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIFICATION_ID + 1000, updateNotification);
}

From source file:edu.mit.mobile.android.locast.data.MediaSync.java

/**
 * Checks the local file system and checks to see if the given media
 * resource has been downloaded successfully already. If not, it will
 * download it from the server and store it in the filesystem. This uses the
 * last-modified header and file length to determine if a media resource is
 * up to date./* ww  w. ja  va2 s.co m*/
 *
 * This method blocks for the course of the download, but shows a progress
 * notification.
 *
 * @param pubUri
 *            the http:// uri of the public resource
 * @param saveFile
 *            the file that the resource will be saved to
 * @param castMediaUri
 *            the content:// uri of the cast
 * @return true if anything has changed. False if this function has
 *         determined it doesn't need to do anything.
 * @throws SyncException
 */
public boolean downloadMediaFile(String pubUri, File saveFile, Uri castMediaUri) throws SyncException {
    final NetworkClient nc = NetworkClient.getInstance(this);
    try {
        boolean dirty = true;
        //String contentType = null;

        if (saveFile.exists()) {
            final HttpResponse headRes = nc.head(pubUri);
            final long serverLength = Long.valueOf(headRes.getFirstHeader("Content-Length").getValue());
            // XXX should really be checking the e-tag too, but this will be
            // fine for our application.
            final Header remoteLastModifiedHeader = headRes.getFirstHeader("last-modified");

            long remoteLastModified = 0;
            if (remoteLastModifiedHeader != null) {
                remoteLastModified = DateUtils.parseDate(remoteLastModifiedHeader.getValue()).getTime();
            }

            final HttpEntity entity = headRes.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            if (saveFile.length() == serverLength && saveFile.lastModified() >= remoteLastModified) {
                if (DEBUG) {
                    Log.i(TAG, "Local copy of cast " + saveFile
                            + " seems to be the same as the one on the server. Not re-downloading.");
                }

                dirty = false;
            }
            // fall through and re-download, as we have a different size
            // file locally.
        }
        if (dirty) {
            final Uri castUri = CastMedia.getCast(castMediaUri);
            String castTitle = Cast.getTitle(this, castUri);
            if (castTitle == null) {
                castTitle = "untitled";
            }

            final HttpResponse res = nc.get(pubUri);
            final HttpEntity ent = res.getEntity();

            /*
            final ProgressNotification notification = new ProgressNotification(
                  this, getString(R.string.sync_downloading_cast,
                castTitle), ProgressNotification.TYPE_DOWNLOAD,
                  PendingIntent.getActivity(this, 0, new Intent(
                Intent.ACTION_VIEW, castUri)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0),
                  false);
            */
            final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            final NotificationProgressListener npl = new NotificationProgressListener(nm, null,
                    ent.getContentLength(), 0);
            final InputStreamWatcher is = new InputStreamWatcher(ent.getContent(), npl);

            try {
                if (DEBUG) {
                    Log.d(TAG, "Downloading " + pubUri + " and saving it in " + saveFile.getAbsolutePath());
                }
                final FileOutputStream fos = new FileOutputStream(saveFile);
                StreamUtils.inputStreamToOutputStream(is, fos);
                fos.close();

                // set the file's last modified to match the remote.
                // We can check this later to see if everything is up to
                // date.
                final Header lastModified = res.getFirstHeader("last-modified");
                if (lastModified != null) {
                    saveFile.setLastModified(DateUtils.parseDate(lastModified.getValue()).getTime());
                }

                //contentType = ent.getContentType().getValue();

            } finally {
                npl.done();
                ent.consumeContent();
                is.close();
            }

            // XXX avoid this to prevent adding to local collection
            // final String filePath = saveFile.getAbsolutePath();

            // scanMediaItem(castMediaUri, filePath, contentType);
            return true;
        }
    } catch (final Exception e) {
        final SyncException se = new SyncException("Error downloading content item.");
        se.initCause(e);
        throw se;
    }
    return false;
}

From source file:at.jclehner.rxdroid.NotificationReceiver.java

private NotificationManager getNotificationManager() {
    return (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}

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

static void displayNotification(Context context, TeakNotification teakNotif, Notification nativeNotification) {
    if (notificationManager == null) {
        try {/*from ww  w .  j  av a  2  s  .  c  om*/
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));
            return;
        }
    }

    // Send it out
    if (Teak.isDebug) {
        Log.d(LOG_TAG, "Showing Notification");
        Log.d(LOG_TAG, "       Teak id: " + teakNotif.teakNotifId);
        Log.d(LOG_TAG, "   Platform id: " + teakNotif.platformId);
    }
    notificationManager.notify(NOTIFICATION_TAG, teakNotif.platformId, nativeNotification);

    // TODO: Here is where any kind of thread/update logic will live
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncAutoGetAlbumArtTask.java

@Override
public void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);

    if (DIALOG_VISIBLE == true) {
        pd.setProgress(Integer.parseInt(values[1]));
        pd.setMessage(values[0]);//from   www  . j  a v a  2  s. c  om
    }

    //Update the notification.
    AutoFetchAlbumArtService.builder
            .setContentTitle(mContext.getResources().getString(R.string.downloading_missing_cover_art));
    AutoFetchAlbumArtService.builder.setSmallIcon(R.drawable.notif_icon);
    AutoFetchAlbumArtService.builder.setContentInfo(null);
    AutoFetchAlbumArtService.builder.setContentText(null);
    AutoFetchAlbumArtService.builder.setProgress(dataURIsList.size(), currentProgress, false);
    AutoFetchAlbumArtService.notification = AutoFetchAlbumArtService.builder.build();

    NotificationManager notifyManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notifyManager.notify(AutoFetchAlbumArtService.NOTIFICATION_ID, AutoFetchAlbumArtService.notification);

}

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

static void cancel(Context context, int platformId) {
    if (notificationManager == null) {
        try {//from w w  w  .j  a va2 s. c o  m
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));
            return;
        }
    }

    if (Teak.isDebug) {
        Log.d(LOG_TAG, "Canceling notification id: " + platformId);
    }

    notificationManager.cancel(NOTIFICATION_TAG, platformId);
    context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

    Thread updateThread = TeakNotification.notificationUpdateThread.get(platformId);
    if (updateThread != null) {
        updateThread.interrupt();
    }
}

From source file:com.example.SmartBoard.MQTTHandler.java

public void messageArrived(String topic, MqttMessage message) {
    MyActivity drawingActivity = (MyActivity) drawingContext;
    JSONObject recvMessage = null;/*from w w w. ja v a  2  s.  c o m*/

    if (message.toString().compareTo("") == 0) {
        //user went offline
        String[] topicStruct = topic.split("/");
        // System.out.println("user to be removed: "+topicStruct[2]);

        if (topicStruct[2].compareTo("users") == 0) {
            usersListHistory.remove(new OnlineStateMessage(null, topicStruct[3]));
            usersAdapter.notifyDataSetChanged();

        } else if (topicStruct[2].compareTo("objects") == 0) {
            drawingActivity.drawer.removeObject(topicStruct[3]);
        }
        return;
    }

    try {
        recvMessage = new JSONObject(message.toString());
    } catch (JSONException j) {
        j.printStackTrace();
    }

    if (recvMessage.optString("status").compareTo("online") == 0) {

        OnlineStateMessage newUser = new OnlineStateMessage(recvMessage.optString("selfie"),
                recvMessage.optString("userId"));
        // System.out.println("user added: "+ recvMessage.optString("userId"));
        usersListHistory.add(newUser);
        usersAdapter.notifyDataSetChanged();
        return;

    }

    String clientId = recvMessage.optString("clientId");

    if (clientId.compareTo(client.getClientId()) != 0) {

        switch (type.valueOf(recvMessage.optString("type"))) {

        case Point:
            drawingActivity.drawer.drawPoint((float) recvMessage.optDouble("mX"),
                    (float) recvMessage.optDouble("mY"), recvMessage.optInt("drawActionFlag"),
                    recvMessage.optInt("color"), recvMessage.optString("mode"), recvMessage.optInt("brushSize"),
                    recvMessage.optString("clientId"));
            break;
        case Eraser:
            float eSize = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateEraseSize(eSize);
            break;
        case Pencil: //shares topic with Eraser
            float size = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateBrushSize(size);
            break;

        case ColorChange:
            drawingActivity.drawer.updateColor(recvMessage.optInt("code"));
            break;

        case ClearScreen:
            drawingActivity.drawer.updateClearScreen();
            break;
        case Chat:
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(new long[] { 3, 100 }, -1);

            String[] nameMessage = recvMessage.optString("message").split(":");
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
                    .setLargeIcon(stringToBitmap(recvMessage.optString("selfie")))
                    .setSmallIcon(R.drawable.smart2).setContentTitle(nameMessage[0])
                    .setContentText(nameMessage[1]).setTicker("New Message Arrived").setAutoCancel(true)
                    .setNumber(++numMessages);

            NotificationManager mNotificationManager = (NotificationManager) ctx
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(1000, mBuilder.build());

            ChatMessageWithSelfie mChatMessage = new ChatMessageWithSelfie(recvMessage.optBoolean("direction"),
                    recvMessage.optString("message"), recvMessage.optString("selfie"),
                    recvMessage.optString("imageSent"), null);
            sessionHistory.add(mChatMessage);
            Chat.chatAdapter.add(mChatMessage);
            break;

        case Image:
            Vibrator v2 = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v2.vibrate(new long[] { 3, 100 }, -1);
            Toast.makeText(ctx, recvMessage.optString("username") + " has sent you a message!",
                    Toast.LENGTH_SHORT).show();
            ChatMessageWithSelfie mChatImageMessage = new ChatMessageWithSelfie(
                    recvMessage.optBoolean("direction"), null, recvMessage.optString("selfie"),
                    recvMessage.optString("image"), null);
            sessionHistory.add(mChatImageMessage);
            Chat.chatAdapter.add(mChatImageMessage);
            break;
        case Rectangle:
            drawingActivity.drawer.onDrawReceivedRectangle(recvMessage);
            break;
        case Circle:
            drawingActivity.drawer.onDrawReceivedCircle(recvMessage);
            break;
        case Line:
            drawingActivity.drawer.onDrawReceivedLine(recvMessage);
            break;
        case Text:
            drawingActivity.drawer.onDrawReceivedText(recvMessage);
            break;
        default:
            //ignore the message
        }
    }
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private boolean processRestrictions(Restrictions currRestr, Restrictions newRestr, Account account)
        throws OperationApplicationException {
    boolean resync = false;
    if (newRestr != null && (currRestr == null || !currRestr.equals(newRestr))) {
        // Notify User.
        NotificationManager notificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        if (currRestr != null && newRestr.isPhotoSyncSupported() && !currRestr.isPhotoSyncSupported()) {

            // Create ViewAccount-Intent
            Intent viewAccountsIntent = new Intent(mContext, ViewAccountsActivity.class);
            // Adds the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(ViewAccountsActivity.class);
            stackBuilder.addNextIntent(viewAccountsIntent);

            // Photo sync possible.
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(Constants.NOTIF_ICON)
                    .setContentTitle(mContext.getText(R.string.notif_photosyncenabled_title).toString())
                    .setContentText(account.name).setAutoCancel(true).setOnlyAlertOnce(true)
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
            notificationManager.notify(Constants.NOTIF_PHOTO_SYNC_SUPPORTED, mBuilder.build());
            // Resync to sync Photos
            resync = true;//w w w.ja va2s.  c o m

            setExplicitSavePhoto(account, true);
        }
        if (newRestr.isPhotoSyncSupported()) {
            notificationManager.cancel(Constants.NOTIF_PHOTO_NOT_SYNCED);
        }
        if (!newRestr.isPhotoSyncSupported()) {
            notificationManager.cancel(Constants.NOTIF_PHOTO_SYNC_SUPPORTED);
        }

        if (currRestr != null && newRestr.getMaxContactCount() != currRestr.getMaxContactCount()) {
            // Create ViewAccount-Intent
            Intent viewAccountsIntent = new Intent(mContext, ViewAccountsActivity.class);
            // Adds the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(ViewAccountsActivity.class);
            stackBuilder.addNextIntent(viewAccountsIntent);
            boolean moreAllowed = newRestr.getMaxContactCount() > currRestr.getMaxContactCount();
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(Constants.NOTIF_ICON)
                    .setContentTitle(moreAllowed ? getText(R.string.notif_contact_moresupported_title)
                            : getText(R.string.notif_contact_lesssupported_title))
                    .setContentText(String.format(getText(R.string.notif_contact_supported_content),
                            newRestr.getMaxContactCount(), account.name))
                    .setAutoCancel(true).setOnlyAlertOnce(true)
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
            notificationManager.notify(Constants.NOTIF_MAX_CONTACT_SUPPORTED, mBuilder.build());
            // Hide Contacts not syned, but allow the message to show up
            // again if there are still more than allowed.
            notificationManager.cancel(Constants.NOTIF_CONTACTS_NOT_SYNCED);
            unhideMaxContactMessage(mContext, account);
        }

        if (resync) {
            ContactManager.setDirtyFlag(mContext, account);
        }

        SyncUtils.saveRestrictions(account, mAccountManager, newRestr);
    }
    return resync;
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncAutoGetAlbumArtTask.java

@Override
protected void onPostExecute(Void arg0) {

    Intent intent = new Intent(mContext, AutoFetchAlbumArtService.class);
    mContext.stopService(intent);//from   ww  w  . j  a  v a 2  s. co  m

    if (pd.isShowing() && DIALOG_VISIBLE == true) {
        pd.dismiss();
    }

    //Dismiss the notification.
    AutoFetchAlbumArtService.builder
            .setTicker(mContext.getResources().getString(R.string.done_downloading_art));
    AutoFetchAlbumArtService.builder
            .setContentTitle(mContext.getResources().getString(R.string.done_downloading_art));
    AutoFetchAlbumArtService.builder.setSmallIcon(R.drawable.notif_icon);
    AutoFetchAlbumArtService.builder.setContentInfo(null);
    AutoFetchAlbumArtService.builder.setContentText(null);
    AutoFetchAlbumArtService.builder.setProgress(0, 0, false);
    AutoFetchAlbumArtService.notification = AutoFetchAlbumArtService.builder.build();
    AutoFetchAlbumArtService.notification.flags = Notification.FLAG_AUTO_CANCEL;

    NotificationManager notifyManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notifyManager.notify(AutoFetchAlbumArtService.NOTIFICATION_ID, AutoFetchAlbumArtService.notification);

    Toast.makeText(mContext, R.string.done_downloading_art, Toast.LENGTH_LONG).show();

    //Rescan for album art.
    //Seting the "RESCAN_ALBUM_ART" flag to true will force MainActivity to rescan the folders.
    sharedPreferences.edit().putBoolean("RESCAN_ALBUM_ART", true).commit();

    //Restart the app.
    final Intent i = mActivity.getBaseContext().getPackageManager()
            .getLaunchIntentForPackage(mActivity.getBaseContext().getPackageName());

    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    mActivity.startActivity(i);
    mActivity.finish();

}