Example usage for android.app Notification Notification

List of usage examples for android.app Notification Notification

Introduction

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

Prototype

@Deprecated
public Notification(int icon, CharSequence tickerText, long when) 

Source Link

Document

Constructs a Notification object with the information needed to have a status bar icon without the standard expanded view.

Usage

From source file:com.fanfou.app.opensource.service.DownloadService.java

private void showProgress() {
    this.notification = new Notification(R.drawable.ic_notify_download, "?",
            System.currentTimeMillis());
    this.notification.flags |= Notification.FLAG_ONGOING_EVENT;
    this.notification.flags |= Notification.FLAG_AUTO_CANCEL;
    this.notification.contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
    final RemoteViews view = new RemoteViews(getPackageName(), R.layout.download_notification);
    view.setTextViewText(R.id.download_notification_text, "? 0%");
    view.setProgressBar(R.id.download_notification_progress, 100, 0, false);
    this.notification.contentView = view;
    this.nm.notify(DownloadService.NOTIFICATION_PROGRESS_ID, this.notification);
}

From source file:edu.missouri.bas.service.SensorService.java

@SuppressWarnings("deprecation")
@Override/*from  w  w  w .  j  a v a 2  s.  co  m*/
public void onCreate() {

    super.onCreate();
    Log.d(TAG, "Starting sensor service");
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundsMap = new HashMap<Integer, Integer>();
    soundsMap.put(SOUND1, mSoundPool.load(this, R.raw.bodysensor_alarm, 1));
    soundsMap.put(SOUND2, mSoundPool.load(this, R.raw.voice_notification, 1));

    serviceContext = this;

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothMacAddress = mBluetoothAdapter.getAddress();
    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Get location manager
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    activityRecognition = new ActivityRecognitionScan(getApplicationContext());
    activityRecognition.startActivityRecognitionScan();

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    serviceWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorServiceLock");
    serviceWakeLock.acquire();

    //Initialize start time
    stime = System.currentTimeMillis();

    //Setup calendar object
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(stime);

    /*
     * Setup notification manager
     */

    notification = new Notification(R.drawable.icon2, "Recorded", System.currentTimeMillis());
    notification.defaults = 0;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
    notifyIntent.setClass(this, MainActivity.class);

    /*
     * Display notification that service has started
     */
    notification.tickerText = "Sensor Service Running";
    PendingIntent contentIntent = PendingIntent.getActivity(SensorService.this, 0, notifyIntent,
            Notification.FLAG_ONGOING_EVENT);
    notification.setLatestEventInfo(SensorService.this, getString(R.string.app_name),
            "Recording service started at: " + cal.getTime().toString(), contentIntent);

    notificationManager.notify(SensorService.SERVICE_NOTIFICATION_ID, notification);

    // locationControl = new LocationControl(this, mLocationManager, 1000 * 60, 200, 5000);   

    IntentFilter activityResultFilter = new IntentFilter(XMLSurveyActivity.INTENT_ACTION_SURVEY_RESULTS);
    SensorService.this.registerReceiver(alarmReceiver, activityResultFilter);

    IntentFilter sensorDataFilter = new IntentFilter(SensorService.ACTION_SENSOR_DATA);
    SensorService.this.registerReceiver(alarmReceiver, sensorDataFilter);
    Log.d(TAG, "Sensor service created.");

    try {
        prepareIO();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    prepareAlarms();

    Intent startSensors = new Intent(SensorService.ACTION_START_SENSORS);
    this.sendBroadcast(startSensors);

    Intent scheduleCheckConnection = new Intent(SensorService.ACTION_SCHEDULE_CHECK);
    scheduleCheck = PendingIntent.getBroadcast(serviceContext, 0, scheduleCheckConnection, 0);
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000 * 60 * 5, 1000 * 60 * 5, scheduleCheck);
    mLocationClient = new LocationClient(this, this, this);
}

From source file:cl.iluminadoschile.pako.floatingdiv.CustomOverlayService.java

@Override
protected Notification foregroundNotification(int notificationId) {
    Notification notification;//from  w  w  w.j  a v a  2  s.c o m

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && activation_method.equals(Constants.SETTINGS.ACTIVATION_METHOD_MANUAL)) {
        Intent settingsIntent = new Intent(Intent.ACTION_MAIN);
        settingsIntent.setClassName(Constants.ACTION.prefix, Constants.ACTION.prefix + ".SettingsActivity");
        settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, settingsIntent, 0);

        Intent startFgIntent = new Intent(this, CustomOverlayService.class);
        startFgIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
        PendingIntent pstartFgIntent = PendingIntent.getService(this, 0, startFgIntent, 0);

        Intent pauseFgIntent = new Intent(this, CustomOverlayService.class);
        pauseFgIntent.setAction(Constants.ACTION.PAUSEFOREGROUND_ACTION);
        PendingIntent ppauseFgIntent = PendingIntent.getService(this, 0, pauseFgIntent, 0);

        Intent stopFgIntent = new Intent(this, CustomOverlayService.class);
        stopFgIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
        PendingIntent pstopFgIntent = PendingIntent.getService(this, 0, stopFgIntent, 0);

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

        notification = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.title_notification))
                .setTicker(getString(R.string.title_notification))
                .setContentText(getString(R.string.message_notification)).setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)).setContentIntent(pendingIntent)
                .setOngoing(true).addAction(android.R.drawable.ic_media_play, "Start", pstartFgIntent)
                .addAction(android.R.drawable.ic_media_pause, "Pause", ppauseFgIntent)
                .addAction(android.R.drawable.ic_delete, "Stop", pstopFgIntent).build();

    } else {
        notification = new Notification(R.drawable.ic_launcher, getString(R.string.title_notification),
                System.currentTimeMillis());

        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT
                | Notification.FLAG_ONLY_ALERT_ONCE;

        notification.setLatestEventInfo(this, getString(R.string.title_notification),
                getString(R.string.message_notification_manual), notificationIntent());
    }
    return notification;
}

From source file:com.CPTeam.VselCalc.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");
    if (update_file.length() > 0) {
        // raise notification
        Notification notification = new Notification(appIcon, appName + " update", System.currentTimeMillis());
        notification.flags |= NOTIFICATION_FLAGS;

        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Select to install";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);/*  ww  w .  ja  va 2  s.c  o m*/
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        nm.notify(NOTIFICATION_ID, notification);
    } else {
        nm.cancel(NOTIFICATION_ID);
    }
}

From source file:com.github.vseguip.sweet.contacts.SweetContactSync.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Log.i(TAG, "onPerformSync()");
    // Get preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean fullSync = settings.getBoolean(mContext.getString(R.string.full_sync), false);
    if (fullSync)
        mAccountManager.setUserData(account, LAST_SYNC_KEY, null);
    performNetOperation(new SugarRunnable(account, syncResult, new ISugarRunnable() {
        @Override//from w ww .j  ava2  s. c o  m
        public void run() throws URISyntaxException, OperationCanceledException, AuthenticatorException,
                IOException, AuthenticationException {
            Log.i(TAG, "Running PerformSync closure()");

            mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, true);
            SugarAPI sugar = SugarAPIFactory.getSugarAPI(mAccountManager, account);
            String lastDate = mAccountManager.getUserData(account, LAST_SYNC_KEY);
            List<ISweetContact> contacts = null;
            try {
                contacts = fetchContacts(sugar, lastDate);
            } catch (AuthenticationException ex) {
                // maybe expired session, invalidate token and request new
                // one
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            } catch (NullPointerException npe) {
                // maybe expired session, invalidate token and request new
                // one               
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            }
            // try again, it could be due to an expired session
            if (contacts == null) {
                contacts = fetchContacts(sugar, lastDate);
            }
            List<ISweetContact> modifiedContacts = ContactManager.getLocallyModifiedContacts(mContext, account);
            List<ISweetContact> createdContacts = ContactManager.getLocallyCreatedContacts(mContext, account);
            // Get latest date from server
            for (ISweetContact c : contacts) {
                String contactDate = c.getDateModified();
                if ((lastDate == null) || (lastDate.compareTo(contactDate) < 0)) {
                    lastDate = contactDate;
                }
            }
            // Determine conflicting contacts
            Set<String> conflictSet = getConflictSet(contacts, modifiedContacts);
            Map<String, ISweetContact> conflictingSugarContacts = filterIds(contacts, conflictSet);
            Map<String, ISweetContact> conflictingLocalContacts = filterIds(modifiedContacts, conflictSet);

            if (modifiedContacts.size() > 0) {
                // Send modified local non conflicting contacts to the
                // server
                List<String> newIds = sugar.sendNewContacts(mAuthToken, modifiedContacts, false);
                if (newIds.size() != modifiedContacts.size()) {
                    throw new OperationCanceledException("Error updating local contacts in the remote server");
                }
                ContactManager.cleanDirtyFlag(mContext, modifiedContacts);
            }
            if (createdContacts.size() > 0) {
                List<String> newIds = sugar.sendNewContacts(mAuthToken, createdContacts, true);
                if (newIds.size() != createdContacts.size()) {
                    // something wrong happened, it's probable the user will
                    // have to clear the data
                    throw new OperationCanceledException("Error creating local contacts in the remote server");
                }
                ContactManager.assignSourceIds(mContext, createdContacts, newIds);
                ContactManager.cleanDirtyFlag(mContext, createdContacts);
            }
            // Sync remote contacts locally.
            if (contacts.size() > 0) {
                ContactManager.syncContacts(mContext, account, contacts);
            }
            // resolve remaining conflicts
            List<ISweetContact> resolvedContacts = new ArrayList<ISweetContact>();
            for (String id : conflictSet) {
                ISweetContact local = conflictingLocalContacts.get(id);
                ISweetContact remote = conflictingSugarContacts.get(id);
                if (local.equals(remote)) {
                    // no need to sync
                    resolvedContacts.add(local);
                    conflictingLocalContacts.remove(id);
                    conflictingSugarContacts.remove(id);
                } else {
                    Log.i(TAG, "Local contact differs from remote contact " + local.getFirstName() + " "
                            + local.getLastName());
                    if (local.equalUIFields(remote)) {
                        // Differed in a non visible field like the account
                        // id or similar, use server version and resolve
                        // automatically
                        resolvedContacts.add(remote);
                        conflictingLocalContacts.remove(id);
                        conflictingSugarContacts.remove(id);
                    }
                }

            }
            ContactManager.cleanDirtyFlag(mContext, resolvedContacts);
            if (conflictingLocalContacts.size() > 0) {
                // Create a notification that can launch an mActivity to
                // resolve the pending conflict
                NotificationManager nm = (NotificationManager) mContext
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.icon,
                        mContext.getString(R.string.notify_sync_conflict_ticket), System.currentTimeMillis());
                Intent intent = new Intent(mContext, SweetConflictResolveActivity.class);
                intent.putExtra("account", account);
                SweetConflictResolveActivity.storeConflicts(conflictingLocalContacts, conflictingSugarContacts);

                notify.setLatestEventInfo(mContext, mContext.getString(R.string.notify_sync_conflict_title),
                        mContext.getString(R.string.notify_sync_conflict_message),
                        PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
                nm.notify(SweetConflictResolveActivity.NOTIFY_CONFLICT,
                        SweetConflictResolveActivity.NOTIFY_CONTACT, notify);

                throw new OperationCanceledException("Pending conflicts");
            }
            // Save the last sync time in the account if all went ok
            mAccountManager.setUserData(account, LAST_SYNC_KEY, lastDate);
        }
    }));
}

From source file:indrora.atomic.irc.IRCService.java

/**
 * Update notification and vibrate and/or flash a LED light if needed
 *
 * @param text       The ticker text to display
 * @param contentText       The text to display in the notification dropdown
 *                          If null, this makes the notification update to be the connection status.
 * @param vibrate True if the device should vibrate, false otherwise
 * @param sound True if the device should make sound, false otherwise
 * @param light True if the device should flash a LED light, false otherwise
 *//*w w  w. ja  va 2  s  . c  o m*/
private void updateNotification(String text, String contentText, boolean vibrate, boolean sound,
        boolean light) {
    if (foreground) {
        // I give up. Android changed how this works -- Hope it never goes away.
        notification = new Notification(R.drawable.ic_service_icon, text, System.currentTimeMillis());

        Intent notifyIntent = new Intent(this, ServersActivity.class);
        //notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //conetntText is null when you have nothing to display; by default, if you supply any, it will
        //use whatever is handed as the body of the notification.
        // If you hand it null, you are given a status line that describes what is going on.
        if (contentText == null) {
            if (newMentions >= 1) {
                StringBuilder sb = new StringBuilder();
                for (Conversation conv : mentions.values()) {
                    sb.append(conv.getName() + " (" + conv.getNewMentions() + "), ");
                }
                contentText = getString(R.string.notification_mentions, sb.substring(0, sb.length() - 2));

                // We're going to work through the mentions keys. The first half is
                // the server ID, the other half
                // is the channel that the mention belongs to.

                int ServerID = -1;
                String Convo = "";
                for (String convID : mentions.keySet()) {
                    ServerID = Integer.parseInt(convID.substring(0, convID.indexOf(':')));
                    Convo = convID.substring(convID.indexOf(':') + 1);
                }

                Log.d("IRCService", "Jump target is '" + Convo + "'");
                notifyIntent.setClass(this, ConversationActivity.class);
                notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                notifyIntent.putExtra("serverId", ServerID);
                notifyIntent.putExtra(ConversationActivity.EXTRA_TARGET, "" + Convo);

            } else {
                if (!connectedServerTitles.isEmpty()) {
                    StringBuilder sb = new StringBuilder();
                    for (String title : connectedServerTitles) {
                        sb.append(title + ", ");
                    }
                    contentText = getString(R.string.notification_connected, sb.substring(0, sb.length() - 2));
                } else {
                    contentText = getString(R.string.notification_not_connected);
                }
            }
        }

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(this, getText(R.string.app_name), contentText, contentIntent);

        // We only want to vibrate if it's been $ARBITRARY_AMOUNT_OF_TIME
        // since we last buzzed.

        vibrate = vibrate && (System.currentTimeMillis() - lastVibrationTime > 2000);

        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            lastVibrationTime = System.currentTimeMillis();
        }

        if (sound) {
            // buzz the user with an audible sound.
            notification.sound = settings.getHighlightSoundLocation();

        }

        if (light) {
            notification.ledARGB = NOTIFICATION_LED_COLOR;
            notification.ledOnMS = NOTIFICATION_LED_ON_MS;
            notification.ledOffMS = NOTIFICATION_LED_OFF_MS;
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        }

        notification.number = newMentions;

        notificationManager.notify(FOREGROUND_NOTIFICATION, notification);
    }
}

From source file:org.mythdroid.util.UpdateService.java

private void notify(String title, String message) {

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

    Notification notification = new Notification(R.drawable.logo, title, System.currentTimeMillis());

    notification.flags = Notification.FLAG_AUTO_CANCEL;

    notification.setLatestEventInfo(getApplicationContext(), title, message,
            PendingIntent.getActivity(Globals.appContext, 0, new Intent(), 0));

    nm.notify(-1, notification);//  w w  w .  j  av a  2s. co m
}

From source file:io.coldstart.android.GCMIntentService.java

private void SendCombinedNotification(String EventCount) {
    Notification notification = new Notification(R.drawable.ic_stat_alert, EventCount + " new SNMP Traps!",
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;

    notification.ledARGB = 0xffff0000;//from   w w  w  .j  a  va 2s . com

    notification.ledOnMS = 300;
    notification.ledOffMS = 1000;

    notification.defaults |= Notification.DEFAULT_SOUND;

    Context context = getApplicationContext();
    Intent notificationIntent = new Intent(this, TrapListActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("forceRefresh", true);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, EventCount + " SNMP Traps", "Click to launch ColdStart.io",
            contentIntent);
    mNM.notify(43523, notification);//NotificationID++ 
}

From source file:com.andrewshu.android.reddit.common.Common.java

public static void newMailNotification(Context context, String mailNotificationStyle, int count) {
    Intent nIntent = new Intent(context, InboxActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, nIntent, 0);
    Notification notification = new Notification(R.drawable.mail, Constants.HAVE_MAIL_TICKER,
            System.currentTimeMillis());
    if (Constants.PREF_MAIL_NOTIFICATION_STYLE_BIG_ENVELOPE.equals(mailNotificationStyle)) {
        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.big_envelope_notification);
        notification.contentView = contentView;
    } else {/*from  ww w.java  2s  . c  om*/
        notification.setLatestEventInfo(context, Constants.HAVE_MAIL_TITLE,
                count + (count == 1 ? " unread message" : " unread messages"), contentIntent);
    }
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    notification.contentIntent = contentIntent;
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Constants.NOTIFICATION_HAVE_MAIL, notification);
}

From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java

private void showBatchUploadNotification(String text, int progress, boolean noClear) {
    if (notification == null) {
        notification = new Notification(R.drawable.ic_icon_export, text, System.currentTimeMillis());

        // final Intent appIntent = new Intent(this, SIDE.class);
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, 0);

        notification.setLatestEventInfo(this, getString(R.string.app_name), text, contentIntent);

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.batch_upload_notification_layout);
        contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_icon_export);
        notification.contentView = contentView;
    }/*  ww  w  .ja v  a  2 s.  c  o  m*/

    notification.contentView.setTextViewText(R.id.status_text, text);
    notification.contentView.setProgressBar(R.id.progress_bar, MAX_PROGRESS, progress, false);

    if (noClear) {
        notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    } else {
        notificationManager.cancel(R.id.batch_upload);

        notification.flags ^= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    }
    notificationManager.notify(R.id.batch_upload, notification);
}