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.securecomcode.text.service.KeyCachingService.java

private void foregroundServiceLegacy() {
    Notification notification = new Notification(R.drawable.icon_cached,
            getString(R.string.KeyCachingService_textsecure_passphrase_cached), System.currentTimeMillis());
    notification.setLatestEventInfo(getApplicationContext(),
            getString(R.string.KeyCachingService_passphrase_cached),
            getString(R.string.KeyCachingService_textsecure_passphrase_cached), buildLaunchIntent());
    notification.tickerText = null;//from www  . ja  va2s  .  com

    stopForeground(true);
    startForeground(SERVICE_RUNNING_ID, notification);
}

From source file:org.chirpradio.mobile.PlaybackService.java

private void setNotification(String title, String message) {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    CharSequence tickerText = message;
    long when = System.currentTimeMillis();

    int icon = R.drawable.icon;
    Notification notification = new Notification(icon, tickerText, when);
    notification.flags = Notification.FLAG_ONGOING_EVENT;
    Context context = getApplicationContext();
    CharSequence contentTitle = title;
    CharSequence contentText = message;
    Intent notificationIntent = new Intent(this, Playing.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

    mNotificationManager.notify(CHIRP_ID, notification);
}

From source file:com.pandoroid.PandoraRadioService.java

public void setNotification() {
    if (!m_paused) {
        try {//from  ww  w  . ja va 2  s . c o m
            Song tmp_song;
            tmp_song = m_song_playback.getSong();
            Notification notification = new Notification(R.drawable.icon, "Pandoroid Radio",
                    System.currentTimeMillis());
            Intent notificationIntent = new Intent(this, PandoroidPlayer.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_SONG_PLAYING,
                    notificationIntent, 0);
            notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;
            notification.setLatestEventInfo(getApplicationContext(), tmp_song.getTitle(),
                    tmp_song.getArtist() + " on " + tmp_song.getAlbum(), contentIntent);
            startForeground(NOTIFICATION_SONG_PLAYING, notification);
        } catch (Exception e) {
        }
    }
}

From source file:com.vendsy.bartsy.venue.GCMIntentService.java

/**
 * To generate a notification to inform the user that server has sent a message.
 * /*from  ww  w  . ja  v  a 2s .c o  m*/
 * @param count
 * @param count 
 */
private static void generateNotification(Context context, String message, String count) {
    int icon = R.drawable.ic_launcher;
    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, MainActivity.class);
    // 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_AUTO_CANCEL;
    try {
        int countValue = Integer.parseInt(count);
        notification.number = countValue;
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    // // Play default notification sound
    notification.defaults = Notification.DEFAULT_SOUND;
    notificationManager.notify(0, notification);
}

From source file:gpsalarm.app.service.PostMonitor.java

private void showProximityNotification(String string) {
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification note = new Notification(R.drawable.status, "Friend@ notification!",
            System.currentTimeMillis());
    Intent i = new Intent(this, AlertList.class);

    //      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
    //                      Intent.FLAG_ACTIVITY_SINGLE_TOP);
    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
    note.setLatestEventInfo(this, "Friend@ notification", string, pi);

    mgr.notify(NOTIFICATION_ID, note);/*from w w w  .  j a va 2s.  co  m*/

}

From source file:com.android.python27.ScriptService.java

@Override
protected Notification createNotification() {
    Notification notification = new Notification(R.drawable.icon, this.getString(R.string.loading),
            System.currentTimeMillis());
    // This contentIntent is a noop.
    PendingIntent contentIntent = PendingIntent.getService(this, 0, new Intent(), 0);
    notification.setLatestEventInfo(this, this.getString(R.string.app_name), this.getString(R.string.loading),
            contentIntent);/*from   ww w  .j  a  v a 2 s  . co  m*/
    notification.flags = Notification.FLAG_AUTO_CANCEL;
    return notification;
}

From source file:free.yhc.netmbuddy.model.NotiManager.java

private Notification buildNotificationGB(NotiType ntype, CharSequence videoTitle) {
    Intent intent = new Intent(Utils.getAppContext(), NotiManager.NotiIntentReceiver.class);
    intent.setAction(NOTI_INTENT_DELETE);
    PendingIntent piDelete = PendingIntent.getBroadcast(Utils.getAppContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    intent = new Intent(Utils.getAppContext(), NotiManager.NotiIntentReceiver.class);
    intent.setAction(NOTI_INTENT_ACTION);
    intent.putExtra("type", ntype.name());
    PendingIntent piContent = PendingIntent.getBroadcast(Utils.getAppContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    /*//from w w w  .  j  av a 2s  .  c om
     * NOTE
     * Below way is deprecated but works well better than using recommended way - notification builder.
     * (See commends below about using builder)
     */
    Notification n = new Notification(ntype.getIcon(), null, System.currentTimeMillis());
    n.setLatestEventInfo(Utils.getAppContext(), Utils.getResString(R.string.app_name), videoTitle, piContent);
    n.deleteIntent = piDelete;
    n.flags = 0;

    return n;
    /* Below code generates "java.lang.NoClassDefFoundError : android.support.v4.app.NotificationCompat$Builder"
     * So, comment out!
     * (Damn Android!
     *
    NotificationCompat.Builder nbldr = new NotificationCompat.Builder(Utils.getAppContext());
    nbldr.setSmallIcon(ntype.getIcon())
     .setTicker(null)
     .setContentTitle(title)
     .setContentText(desc)
     .setAutoCancel(true)
     .setContentIntent(piContent)
     .setDeleteIntent(piDelete);
    return nbldr.build();
    */
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * /*from w w w .j a v a  2s .c om*/
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();
        hout.println(API_KEY);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Make notification and post it to the NotificationManager
 * // ww  w.j  a  v  a  2s .co m
 * @param tickerIcon
 *            Icon shown in notification bar
 * @param contentIcon
 *            Icon shown in notification
 * @param tickerText
 *            Text shown in notification bar
 * @param contentTitle
 *            Title shown in notification
 * @param contentText
 *            Description shown in notification
 * @param contentTime
 *            Time shown in notification
 * @param when2
 */
private void makeNotification(int tickerIcon, int contentIcon, CharSequence tickerText,
        CharSequence contentTitle, CharSequence contentText, CharSequence contentTime, long when2,
        Float temperature) {
    final long when = System.currentTimeMillis();
    // Make notification
    Notification notification = null;

    final Intent notificationIntent = new Intent(WeatherNotificationService.this,
            WeatherNotificationService.class);
    final PendingIntent contentIntent = PendingIntent.getService(WeatherNotificationService.this, 0,
            notificationIntent, 0);

    // Check if Notification.Builder exists (11+)
    if (Build.VERSION.SDK_INT >= 11) {
        // Honeycomb ++
        NotificationBuilder builder = new NotificationBuilder(this);
        builder.setAutoCancel(false);
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setTicker(tickerText);
        builder.setWhen(when2);
        builder.setSmallIcon(tickerIcon);
        builder.setOngoing(true);
        builder.setContentIntent(contentIntent);
        if (temperature != null)
            builder.makeContentView(contentTitle, contentText, when2, temperature, tickerIcon);
        notification = builder.getNotification();
    } else {
        // Gingerbread --
        notification = new Notification(tickerIcon, tickerText, when);
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.weathernotification);
        contentView.setImageViewResource(R.id.icon, contentIcon);
        contentView.setTextViewText(R.id.title, contentTitle);
        contentView.setTextViewText(R.id.title, contentTitle);
        contentView.setTextViewText(R.id.text, contentText);
        contentView.setTextViewText(R.id.time, contentTime);
        notification.contentView = contentView;
    }
    notification.contentIntent = contentIntent;

    // Post notification
    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, notification);
}

From source file:com.pixmob.r2droid.DeviceRegistrationService.java

private void onC2DMRegistered() {
    final String regId = Preferences.getRegistrationId(getApplicationContext());
    if (DEV) {/*from  ww w .  java2s  .co  m*/
        Log.i(TAG, "Device registered to C2DM with id " + regId);
    }

    int event = CONNECTED_EVENT;
    String error = null;

    // TODO get device name
    final String deviceName = "Unknown Device";
    try {
        final String url = "https://r2droidhq.appspot.com/api/1/register?regid=" + urlEncode(regId) + "&name="
                + urlEncode(deviceName);
        if (DEV) {
            Log.d(TAG, "Register URL: " + url);
        }
        final HttpGet req = new HttpGet(url);
        if (!configureClient()) {
            event = DISCONNECTED_EVENT;
            error = AUTH_FAILED_ERROR;
        } else {
            final int statusCode = gaeClient.execute(req).getStatusLine().getStatusCode();
            if (statusCode != HTTP_SC_OK) {
                if (DEV) {
                    Log.w(TAG, "Failed to register device: statusCode=" + statusCode);
                }
                event = DISCONNECTED_EVENT;
                error = DEVICE_REGISTRATION_ERROR;
            }
        }
    } catch (AppEngineAuthenticationException e) {
        if (e.isAuthenticationPending()) {
            if (DEV) {
                Log.i(TAG, "User must give permission to use authentication token: " + "registration aborted");
            }
            event = DISCONNECTED_EVENT;
            error = AUTH_PENDING;
        } else {
            if (DEV) {
                Log.w(TAG, "Authentication error", e);
            }
            event = DISCONNECTED_EVENT;
            error = AUTH_FAILED_ERROR;
        }
    } catch (IOException e) {
        if (DEV) {
            Log.w(TAG, "Network error", e);
        }
        event = DISCONNECTED_EVENT;
        error = NETWORK_ERROR;
    } catch (Exception e) {
        Log.wtf(TAG, "Unexpected error", e);
        event = DISCONNECTED_EVENT;
        error = DEVICE_REGISTRATION_ERROR;
    }

    fireEvent(event, error);

    int ticketRes = R.string.device_is_online;
    if (event != CONNECTED_EVENT) {
        ticketRes = R.string.updating_device_failed;
    }
    final Notification notification = new Notification(R.drawable.ic_stat_icon, getString(ticketRes),
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, getString(R.string.app_name), getString(ticketRes), dashboardIntent);
    nm.notify(STATUS_UPDATE_DONE, notification);
}