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:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Uploads the content, displaying a notification in the system tray. The notification will show
 * a progress bar as the upload goes on and will show a message when finished indicating whether
 * or not it was successful.//from ww w  .  jav  a 2  s  .c o m
 *
 * @param context
 * @param cast
 *            cast item
 * @param serverPath
 *            the path on which
 * @param localFile
 * @param contentType
 * @param uploadType
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws JSONException
 */
public JSONObject uploadContentWithNotification(Context context, Uri cast, String serverPath, Uri localFile,
        String contentType, UploadType uploadType) throws NetworkProtocolException, IOException, JSONException {
    String castTitle = Cast.getTitle(context, cast);
    if (castTitle == null) {
        castTitle = "untitled (cast #" + cast.getLastPathSegment() + ")";
    }
    JSONObject updatedCastMedia;
    final ProgressNotification notification = new ProgressNotification(context,
            context.getString(R.string.sync_uploading_cast, castTitle), ProgressNotification.TYPE_UPLOAD,
            PendingIntent.getActivity(context, 0,
                    new Intent(Intent.ACTION_VIEW, cast).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0),
            true);

    // assume fail: when successful, all will be reset.
    notification.successful = false;
    notification.doneTitle = context.getString(R.string.sync_upload_fail);
    notification.doneText = context.getString(R.string.sync_upload_fail_message, castTitle);

    notification.doneIntent = PendingIntent.getActivity(context, 0,
            new Intent(Intent.ACTION_VIEW, cast).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);

    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationProgressListener tpl = new NotificationProgressListener(nm, notification, 0,
            (int) ContentUris.parseId(cast));

    try {
        final AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(localFile, "r");
        final long max = afd.getLength();

        tpl.setSize(max);

        switch (uploadType) {
        case RAW_PUT:
            updatedCastMedia = uploadContent(context, tpl, serverPath, localFile, contentType);
            break;
        case FORM_POST:
            updatedCastMedia = uploadContentUsingForm(context, tpl, serverPath, localFile, contentType);
            break;

        default:
            throw new IllegalArgumentException("unhandled upload type: " + uploadType);
        }

        notification.doneTitle = context.getString(R.string.sync_upload_success);
        notification.doneText = context.getString(R.string.sync_upload_success_message, castTitle);
        notification.successful = true;

    } catch (final NetworkProtocolException e) {
        notification.setUnsuccessful(e.getLocalizedMessage());
        throw e;
    } catch (final IOException e) {
        notification.setUnsuccessful(e.getLocalizedMessage());
        throw e;
    } finally {
        tpl.done();
    }
    return updatedCastMedia;
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

/**
 * Handles setting up the notification./*from w w w  .  ja v a  2s.c om*/
 * There are two situation in which we send a notification
 * First if there is more recent news than the last sync
 * Second if the news is concerned with the favorite character
 * @param context to use for getting preference information
 * @param newsItem  contains the newsItem information used to build the notification
 * @param notification_id identifier for the notification
 */
private void notifyNews(Context context, GuildViewerNewsItem newsItem, int notification_id) {

    // determine if we should send a notification
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean notificationsEnabled = prefs.getBoolean(context.getString(R.string.pref_enable_notifications_key),
            Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));
    long lastNotification = prefs.getLong(context.getString(R.string.pref_last_notification), 0L);
    boolean timeToNotify = newsItem.getTimestamp() > lastNotification;

    // we can notify for both new news and for favorite character news
    if (notificationsEnabled
            && (timeToNotify || notification_id == GUILD_VIEWER_FAVORITE_CHARACTER_NOTIFICATION)) {

        // build the information to put into the notification
        int iconId = R.drawable.ic_launcher;
        String title = context.getString(R.string.app_name);

        String news = String.format("%s %s %s", newsItem.getCharacter(),
                Utility.getNewsTypeVerb(context, newsItem.getType()),
                Utility.containsItem(newsItem.getType())
                        ? ((newsItem.getItem() != null) ? newsItem.getItem().getName() : "")
                        : ((newsItem.getAchievement() != null) ? newsItem.getAchievement().getTitle() : ""));
        String contentText = String.format(context.getString(R.string.format_notification), news);

        // set the notification to clear after a click
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(iconId)
                .setContentTitle(title).setContentText(contentText).setOnlyAlertOnce(true).setAutoCancel(true);

        // Open the app when the user clicks on the notification.
        Intent resultIntent = new Intent(context, NewsListActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context).addParentStack(NewsListActivity.class)
                .addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(resultPendingIntent);

        // we can notify for two reasons but lets just always have one notification at a time
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(GUILD_VIEWER_NOTIFICATION_ID, mBuilder.build());
    }
}

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);
    ////from  w  w w  .j a va  2  s . c  o m
    notificationView.setOnClickPendingIntent(R.id.download_notification, pendingSwitchIntent);
    notificationManager.notify(1, notification);
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

private void cancelAllNotification() {
    NotificationManager notificationManager = (NotificationManager) appContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();// www  .  j  a  va  2s .c  o  m
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Creates a system notification.//from   ww w . j  a v a  2s . c o m
 *    
 * @param context            Context.
 * @param notSound            Enable or disable the sound
 * @param notSoundRawId         Custom raw sound id. If enabled and not set 
 *                         default notification sound will be used. Set to -1 to 
 *                         default system notification.
 * @param multipleNot         Setting to True allows showing multiple notifications.
 * @param groupMultipleNotKey   If is set, multiple notifications can be grupped by this key.
 * @param notAction            Action for this notification
 * @param notTitle            Title
 * @param notMessage         Message
 * @param notClazz            Class to be executed
 * @param extras            Extra information
 * 
 */
public static void notification_generate(Context context, boolean notSound, int notSoundRawId,
        boolean multipleNot, String groupMultipleNotKey, String notAction, String notTitle, String notMessage,
        Class<?> notClazz, Bundle extras, boolean wakeUp) {

    try {
        int iconResId = notification_getApplicationIcon(context);
        long when = System.currentTimeMillis();

        Notification notification = new Notification(iconResId, notMessage, when);

        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        if (notSound) {
            if (notSoundRawId > 0) {
                try {
                    notification.sound = Uri.parse("android.resource://"
                            + context.getApplicationContext().getPackageName() + "/" + notSoundRawId);
                } catch (Exception e) {
                    if (LOG_ENABLE) {
                        Log.w(TAG, "Custom sound " + notSoundRawId + "could not be found. Using default.");
                    }
                    notification.defaults |= Notification.DEFAULT_SOUND;
                    notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                }
            } else {
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
        }

        Intent notificationIntent = new Intent(context, notClazz);
        notificationIntent.setAction(notClazz.getName() + "." + notAction);
        if (extras != null) {
            notificationIntent.putExtras(extras);
        }

        //Set intent so it does not start a new activity
        //
        //Notes:
        //   - The flag FLAG_ACTIVITY_SINGLE_TOP makes that only one instance of the activity exists(each time the
        //      activity is summoned no onCreate() method is called instead, onNewIntent() is called.
        //  - If we use FLAG_ACTIVITY_CLEAR_TOP it will make that the last "snapshot"/TOP of the activity it will 
        //     be this called this intent. We do not want this because the HOME button will call this "snapshot". 
        //     To avoid this behaviour we use FLAG_ACTIVITY_BROUGHT_TO_FRONT that simply takes to foreground the 
        //     activity.
        //
        //See http://developer.android.com/reference/android/content/Intent.html           
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        int REQUEST_UNIQUE_ID = 0;
        if (multipleNot) {
            if (groupMultipleNotKey != null && groupMultipleNotKey.length() > 0) {
                REQUEST_UNIQUE_ID = groupMultipleNotKey.hashCode();
            } else {
                if (random == null) {
                    random = new Random();
                }
                REQUEST_UNIQUE_ID = random.nextInt();
            }
            PendingIntent.getActivity(context, REQUEST_UNIQUE_ID, notificationIntent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        notification.setLatestEventInfo(context, notTitle, notMessage, intent);

        //This makes the device to wake-up is is idle with the screen off.
        if (wakeUp) {
            powersaving_wakeUp(context);
        }

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

        //We check if the sound is disabled to enable just for a moment
        AudioManager amanager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int previousAudioMode = amanager.getRingerMode();
        ;
        if (notSound && previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            amanager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

        notificationManager.notify(REQUEST_UNIQUE_ID, notification);

        //We restore the sound setting
        if (previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            //We wait a little so sound is played
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
            }
        }
        amanager.setRingerMode(previousAudioMode);

        Log.d(TAG, "Android Notification created.");

    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "The notification could not be created (" + e.getMessage() + ")", e);
    }
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

/**
 * Creates or updates the notification in the Notification Manager. Sends broadcast with given progress or error state to the activity.
 * /*from ww  w.  j a  v  a 2s  .co  m*/
 * @param progress
 *            the current progress state or an error number, can be one of {@link #PROGRESS_CONNECTING}, {@link #PROGRESS_STARTING}, {@link #PROGRESS_VALIDATING}, {@link #PROGRESS_DISCONNECTING},
 *            {@link #PROGRESS_COMPLETED} or {@link #ERROR_FILE_CLOSED}, {@link #ERROR_FILE_INVALID} , etc
 */
private void updateProgressNotification(final int progress) {
    final String deviceAddress = mDeviceAddress;
    final String deviceName = mDeviceName != null ? mDeviceName : getString(R.string.dfu_unknown_name);

    final Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.stat_dfu);

    final Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(android.R.drawable.stat_sys_upload).setOnlyAlertOnce(true).setLargeIcon(largeIcon);
    switch (progress) {
    case PROGRESS_CONNECTING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_connecting))
                .setContentText(getString(R.string.dfu_status_connecting_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_STARTING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_starting))
                .setContentText(getString(R.string.dfu_status_starting_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_VALIDATING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_validating))
                .setContentText(getString(R.string.dfu_status_validating_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_DISCONNECTING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_disconnecting))
                .setContentText(getString(R.string.dfu_status_disconnecting_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_COMPLETED:
        builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_completed))
                .setContentText(getString(R.string.dfu_status_completed_msg)).setAutoCancel(true);
        break;
    case PROGRESS_ABORTED:
        builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_abored))
                .setContentText(getString(R.string.dfu_status_aborted_msg)).setAutoCancel(true);
        break;
    default:
        if (progress >= ERROR_MASK) {
            // progress is an error number
            builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_error))
                    .setContentText(getString(R.string.dfu_status_error_msg)).setAutoCancel(true);
        } else {
            // progress is in percents
            builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_uploading))
                    .setContentText(getString(R.string.dfu_status_uploading_msg, deviceName))
                    .setProgress(100, progress, false);
        }
    }
    // send progress or error broadcast
    if (progress < ERROR_MASK)
        sendProgressBroadcast(progress);
    else
        sendErrorBroadcast(progress);

    // We cannot set two activities at once (using PendingIntent.getActivities(...)) because we have to start the BluetoothLeService first. Service is created in DeviceListActivity.
    // When creating activities the parent Activity is not created, it's just inserted to the history stack.
    final Intent intent = new Intent(this, NotificationActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(DfuActivity.EXTRA_DEVICE_ADDRESS, deviceAddress);
    intent.putExtra(DfuActivity.EXTRA_DEVICE_NAME, deviceName);
    intent.putExtra(DfuActivity.EXTRA_PROGRESS, progress); // this may contains ERROR_CONNECTION_MASK bit!
    if (mLogSession != null)
        intent.putExtra(DfuActivity.EXTRA_LOG_URI, mLogSession.getSessionUri());
    final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_ID, builder.build());
}

From source file:android.app.Activity.java

/**
 * Called as part of the activity lifecycle when an activity is going into
 * the background, but has not (yet) been killed.  The counterpart to
 * {@link #onResume}./*from  www .  j a v a2 s.  c  o  m*/
 *
 * <p>When activity B is launched in front of activity A, this callback will
 * be invoked on A.  B will not be created until A's {@link #onPause} returns,
 * so be sure to not do anything lengthy here.
 *
 * <p>This callback is mostly used for saving any persistent state the
 * activity is editing, to present a "edit in place" model to the user and
 * making sure nothing is lost if there are not enough resources to start
 * the new activity without first killing this one.  This is also a good
 * place to do things like stop animations and other things that consume a
 * noticeable amount of CPU in order to make the switch to the next activity
 * as fast as possible, or to close resources that are exclusive access
 * such as the camera.
 * 
 * <p>In situations where the system needs more memory it may kill paused
 * processes to reclaim resources.  Because of this, you should be sure
 * that all of your state is saved by the time you return from
 * this function.  In general {@link #onSaveInstanceState} is used to save
 * per-instance state in the activity and this method is used to store
 * global persistent data (in content providers, files, etc.)
 * 
 * <p>After receiving this call you will usually receive a following call
 * to {@link #onStop} (after the next activity has been resumed and
 * displayed), however in some cases there will be a direct call back to
 * {@link #onResume} without going through the stopped state.
 * 
 * <p><em>Derived classes must call through to the super class's
 * implementation of this method.  If they do not, an exception will be
 * thrown.</em></p>
 * 
 * @see #onResume
 * @see #onSaveInstanceState
 * @see #onStop
 */
protected void onPause() {
    if (DEBUG_LIFECYCLE)
        Slog.v(TAG, "onPause " + this);
    getApplication().dispatchActivityPaused(this);
    mCalled = true;

    /* remove the migration notification */
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(Process.myUid());

    /* set Bundle for migration */
    if (isAvailable()) {
        Bundle tmpBundle = new Bundle();
        performSaveInstanceState(tmpBundle);
        systemMigrate(tmpBundle);
    }
}

From source file:com.wso2.mobile.mdm.services.Operation.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from   ww  w .ja  v a2  s  .  co  m*/
private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, NotifyActivity.class);
    notificationIntent.putExtra("notification", message);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notificationManager.notify(0, notification);
    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

From source file:jmri.enginedriver.threaded_application.java

/**
 * Display OnGoing Notification that indicates EngineDriver is Running.
 * Should only be called when ED is going into the background.
 * Currently call this from each activity onPause, passing the current intent 
 * to return to when reopening.  */
void addNotification(Intent notificationIntent) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon)
            .setContentTitle(this.getString(R.string.notification_title))
            .setContentText(this.getString(R.string.notification_text)).setOngoing(true);

    PendingIntent contentIntent = PendingIntent.getActivity(this, ED_NOTIFICATION_ID, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(ED_NOTIFICATION_ID, builder.build());
}