Example usage for android.app NotificationManager notify

List of usage examples for android.app NotificationManager notify

Introduction

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

Prototype

public void notify(int id, Notification notification) 

Source Link

Document

Post a notification to be shown in the status bar.

Usage

From source file:com.haha01haha01.harail.DatabaseDownloader.java

@Override
protected void onHandleIntent(Intent workIntent) {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);

    NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("HaRail GTFS Database").setContentText("Downloading file")
            .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(0, 0, true);
    notifyManager.notify(1, builder.build());

    wakeLock.acquire();/*from  w  w  w. j  a  va 2  s .c om*/
    try {
        String filename = "harail_irw_gtfs_" + Utils.getCurrentDateString() + ".zip";
        File zip_file = new File(
                new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOWNLOADS), filename);
        if (downloadFile(irw_gtfs_server, irw_gtfs_port, "anonymous", "", irw_gtfs_filename, zip_file)) {
            sendFinished(extractDb(zip_file, notifyManager, builder));
        } else {
            sendFinished(false);
        }
        wakeLock.release();
    } catch (IOException e) {
        sendFinished(false);
        builder.setContentText("Download failed").setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setProgress(0, 0, false);
        notifyManager.notify(1, builder.build());
        wakeLock.release();
    }
}

From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java

private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) {
    // TODO factor out common code for creating notifications
    boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
    if (!enabled) {
        return;//from   ww  w .j av  a  2 s .c  om
    }

    // Strategy:
    // a. If there is a single failure notification, tapping on the notification goes
    //    to the compose view.
    // b. If there are two failure it stays in the thread view. Selecting one undelivered
    //    thread will dismiss one undelivered notification but will still display the
    //    notification.If you select the 2nd undelivered one it will dismiss the notification.

    long[] msgThreadId = { 0, 1 }; // Dummy initial values, just to initialize the memory
    int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId);
    if (totalFailedCount == 0 && !isDownload) {
        return;
    }
    // The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all
    // failures are from the same thread.
    // If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are
    // indeed in the same thread since there's only 1.
    boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload;

    Intent failedIntent;
    Notification notification = new Notification();
    String title;
    String description;
    if (totalFailedCount > 1) {
        description = context.getString(R.string.notification_failed_multiple,
                Integer.toString(totalFailedCount));
        title = context.getString(R.string.notification_failed_multiple_title);
    } else {
        title = isDownload ? context.getString(R.string.message_download_failed_title)
                : context.getString(R.string.message_send_failed_title);

        description = context.getString(R.string.message_failed_body);
    }

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    if (allFailedInSameThread) {
        failedIntent = new Intent(context, ComposeMessageActivity.class);
        if (isDownload) {
            // When isDownload is true, the valid threadId is passed into this function.
            failedIntent.putExtra("failed_download_flag", true);
        } else {
            threadId = msgThreadId[0];
            failedIntent.putExtra("undelivered_flag", true);
        }
        failedIntent.putExtra("thread_id", threadId);
        taskStackBuilder.addParentStack(ComposeMessageActivity.class);
    } else {
        failedIntent = new Intent(context, ConversationList.class);
    }
    taskStackBuilder.addNextIntent(failedIntent);

    notification.icon = R.drawable.stat_notify_sms_failed;

    notification.tickerText = title;

    notification.setLatestEventInfo(context, title, description,
            taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

    if (noisy) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
                false /* don't vibrate by default */);
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
    }

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

    if (isDownload) {
        notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
    } else {
        notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
    }
}

From source file:br.com.arlsoft.pushclient.PushClientModule.java

public static void sendNotification(Bundle extras) {
    if (extras == null || extras.isEmpty())
        return;//  w w w .  ja  v  a 2  s .  com

    TiApplication appContext = TiApplication.getInstance();
    int appIconId = appContext.getResources().getIdentifier("appicon", "drawable", appContext.getPackageName());
    String appName = appContext.getAppInfo().getName();

    Bundle extrasRoot = extras;

    int badgeCount = -1;
    int notificationId = 0;
    String notificationTitle = null;
    String notificationText = null;
    String notificationTicker = null;
    Uri notificationSound = null;
    int notificationDefaults = 0;

    // TEXT
    if (extras.containsKey("text")) {
        notificationText = extras.getString("text");
    } else if (extras.containsKey("alert")) {
        notificationText = extras.getString("alert");
    } else if (extras.containsKey("message")) {
        notificationText = extras.getString("message");
    } else if (extras.containsKey("data")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("data"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("data");
            if (text != null) {
                notificationText = text;
            }
        }
    } else if (extras.containsKey("msg")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("msg"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("msg");
            if (text != null) {
                notificationText = text;
            }
        }
    } else if (extras.containsKey("default")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("default"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("default");
            if (text != null) {
                notificationText = text;
            }
        }
    } else if (extras.containsKey("payload")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("payload"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("payload");
            if (text != null) {
                notificationText = text;
            }
        }
    }

    // TITLE
    if (extras.containsKey("title")) {
        notificationTitle = extras.getString("title");
    } else {
        notificationTitle = appName;
    }

    // TICKER
    if (extras.containsKey("ticker")) {
        notificationTicker = extras.getString("ticker");
    } else {
        notificationTicker = notificationText;
    }

    // SOUND
    if (extras.containsKey("sound")) {
        if (extras.getString("sound").equalsIgnoreCase("default")) {
            notificationDefaults |= Notification.DEFAULT_SOUND;
        } else {
            File file = null;
            // getResourcesDirectory
            file = new File("app://" + extras.getString("sound"));
            if (file != null && file.exists()) {
                notificationSound = Uri.fromFile(file);
            } else {
                // getResourcesDirectory + sound folder
                file = new File("app://sound/" + extras.getString("sound"));
                if (file != null && file.exists()) {
                    notificationSound = Uri.fromFile(file);
                } else {
                    // getExternalStorageDirectory
                    file = new File("appdata://" + extras.getString("sound"));
                    if (file != null && file.exists()) {
                        notificationSound = Uri.fromFile(file);
                    } else {
                        // getExternalStorageDirectory + sound folder
                        file = new File("appdata://sound/" + extras.getString("sound"));
                        if (file != null && file.exists()) {
                            notificationSound = Uri.fromFile(file);
                        } else {
                            // res folder
                            int soundId = appContext.getResources().getIdentifier(extras.getString("sound"),
                                    "raw", appContext.getPackageName());
                            if (soundId != 0) {
                                notificationSound = Uri.parse("android.resource://"
                                        + appContext.getPackageName() + "/raw/" + soundId);
                            } else {
                                // res folder without file extension
                                String soundFile = extras.getString("sound").split("\\.")[0];
                                soundId = appContext.getResources().getIdentifier(soundFile, "raw",
                                        appContext.getPackageName());
                                if (soundId != 0) {
                                    notificationSound = Uri.parse("android.resource://"
                                            + appContext.getPackageName() + "/raw/" + soundId);
                                }
                            }
                        }
                    }
                }
            }
        }
    } else if (extrasRoot.containsKey("sound")) {
        if (extrasRoot.getString("sound").equalsIgnoreCase("default")) {
            notificationDefaults |= Notification.DEFAULT_SOUND;
        } else {
            File file = null;
            // getResourcesDirectory
            file = new File("app://" + extrasRoot.getString("sound"));
            if (file != null && file.exists()) {
                notificationSound = Uri.fromFile(file);
            } else {
                // getResourcesDirectory + sound folder
                file = new File("app://sound/" + extrasRoot.getString("sound"));
                if (file != null && file.exists()) {
                    notificationSound = Uri.fromFile(file);
                } else {
                    // getExternalStorageDirectory
                    file = new File("appdata://" + extrasRoot.getString("sound"));
                    if (file != null && file.exists()) {
                        notificationSound = Uri.fromFile(file);
                    } else {
                        // getExternalStorageDirectory + sound folder
                        file = new File("appdata://sound/" + extrasRoot.getString("sound"));
                        if (file != null && file.exists()) {
                            notificationSound = Uri.fromFile(file);
                        } else {
                            // res folder
                            int soundId = appContext.getResources().getIdentifier(extrasRoot.getString("sound"),
                                    "raw", appContext.getPackageName());
                            if (soundId != 0) {
                                notificationSound = Uri.parse("android.resource://"
                                        + appContext.getPackageName() + "/raw/" + soundId);
                            } else {
                                // res folder without file extension
                                String soundFile = extrasRoot.getString("sound").split("\\.")[0];
                                soundId = appContext.getResources().getIdentifier(soundFile, "raw",
                                        appContext.getPackageName());
                                if (soundId != 0) {
                                    notificationSound = Uri.parse("android.resource://"
                                            + appContext.getPackageName() + "/raw/" + soundId);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // VIBRATE
    if (extras.containsKey("vibrate") && extras.getString("vibrate").equalsIgnoreCase("true")) {
        notificationDefaults |= Notification.DEFAULT_VIBRATE;
    }

    // LIGHTS
    if (extras.containsKey("lights") && extras.getString("lights").equalsIgnoreCase("true")) {
        notificationDefaults |= Notification.DEFAULT_LIGHTS;
    }

    // NOTIFICATION ID
    if (extras.containsKey("notificationId")) {
        try {
            notificationId = Integer.parseInt(extras.getString("notificationId"));
        } catch (NumberFormatException nfe) {
        }
    }
    if (notificationId == 0) {
        notificationId = appContext.getAppProperties().getInt(PROPERTY_NOTIFICATION_ID, 0);
        notificationId++;
        appContext.getAppProperties().setInt(PROPERTY_NOTIFICATION_ID, notificationId);
    }

    // BADGE
    if (extras.containsKey("badge")) {
        try {
            badgeCount = Integer.parseInt(extras.getString("badge"));
        } catch (NumberFormatException nfe) {
        }
    }

    // LARGE ICON
    Bitmap largeIcon = null;
    if (extras.containsKey("largeIcon")) {
        largeIcon = getBitmap(extras.getString("largeIcon"));
    } else if (extras.containsKey("licon")) {
        largeIcon = getBitmap(extras.getString("licon"));
    } else if (extrasRoot.containsKey("largeIcon")) {
        largeIcon = getBitmap(extrasRoot.getString("largeIcon"));
    } else if (extrasRoot.containsKey("licon")) {
        largeIcon = getBitmap(extrasRoot.getString("licon"));
    }

    // SMALL ICON
    if (extras.containsKey("smallIcon")) {
        appIconId = appContext.getResources().getIdentifier(extras.getString("smallIcon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom smallIcon : "
                    + extras.getString("smallIcon"));
        }
    } else if (extras.containsKey("sicon")) {
        appIconId = appContext.getResources().getIdentifier(extras.getString("sicon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom sicon : " + extras.getString("sicon"));
        }
    } else if (extrasRoot.containsKey("smallIcon")) {
        appIconId = appContext.getResources().getIdentifier(extrasRoot.getString("smallIcon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom smallIcon : "
                    + extrasRoot.getString("smallIcon"));
        }
    } else if (extrasRoot.containsKey("sicon")) {
        appIconId = appContext.getResources().getIdentifier(extrasRoot.getString("sicon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom smallIcon : "
                    + extrasRoot.getString("sicon"));
        }
    }

    if (notificationText != null) {
        // Intent launch = getLauncherIntent(extras);
        Intent launch = new Intent(appContext, PendingNotificationActivity.class);
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (extrasRoot != null && !extrasRoot.isEmpty()) {
            launch.putExtra(PROPERTY_EXTRAS, extrasRoot);
        }
        launch.setAction("dummy_unique_action_identifyer:" + notificationId);

        PendingIntent contentIntent = PendingIntent.getActivity(appContext, 0, launch,
                PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext);

        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText));
        mBuilder.setContentText(notificationText);

        if (notificationTitle != null) {
            mBuilder.setContentTitle(notificationTitle);
        }
        if (notificationTicker != null) {
            mBuilder.setTicker(notificationTicker);
        }
        if (notificationDefaults != 0) {
            mBuilder.setDefaults(notificationDefaults);
        }
        if (notificationSound != null) {
            mBuilder.setSound(notificationSound);
        }
        if (badgeCount >= 0) {
            mBuilder.setNumber(badgeCount);
        }
        if (largeIcon != null) {
            mBuilder.setLargeIcon(largeIcon);
        }

        if (appIconId == 0) {
            appIconId = appContext.getResources().getIdentifier("appicon", "drawable",
                    appContext.getPackageName());
        }

        mBuilder.setSmallIcon(appIconId);
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setAutoCancel(true);
        mBuilder.setWhen(System.currentTimeMillis());

        // ledARGB, ledOnMS, ledOffMS
        boolean customLight = false;
        int argb = 0xFFFFFFFF;
        int onMs = 1000;
        int offMs = 2000;
        if (extras.containsKey("ledARGB")) {
            try {
                argb = TiColorHelper.parseColor(extras.getString("ledARGB"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extras.getString("ledARGB"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extras.containsKey("ledc")) {
            try {
                argb = TiColorHelper.parseColor(extras.getString("ledc"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extras.getString("ledc"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("ledARGB")) {
            try {
                argb = TiColorHelper.parseColor(extrasRoot.getString("ledARGB"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extrasRoot.getString("ledARGB"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("ledc")) {
            try {
                argb = TiColorHelper.parseColor(extrasRoot.getString("ledc"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extrasRoot.getString("ledc"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        }
        if (extras.containsKey("ledOnMS")) {
            try {
                onMs = Integer.parseInt(extras.getString("ledOnMS"));
                customLight = true;
            } catch (NumberFormatException nfe) {
            }
        }
        if (extras.containsKey("ledOffMS")) {
            try {
                offMs = Integer.parseInt(extras.getString("ledOffMS"));
                customLight = true;
            } catch (NumberFormatException nfe) {
            }
        }
        if (customLight) {
            mBuilder.setLights(argb, onMs, offMs);
        }

        //Visibility
        if (extras.containsKey("visibility")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extras.getString("visibility")));
            } catch (NumberFormatException nfe) {
            }
        } else if (extras.containsKey("vis")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extras.getString("vis")));
            } catch (NumberFormatException nfe) {
            }
        } else if (extrasRoot.containsKey("visibility")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extrasRoot.getString("visibility")));
            } catch (NumberFormatException nfe) {
            }
        } else if (extrasRoot.containsKey("vis")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extrasRoot.getString("vis")));
            } catch (NumberFormatException nfe) {
            }
        }

        //Icon background color
        int accent_argb = 0xFFFFFFFF;
        if (extras.containsKey("accentARGB")) {
            try {
                accent_argb = TiColorHelper.parseColor(extras.getString("accentARGB"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extras.getString("accentARGB"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extras.containsKey("bgac")) {
            try {
                accent_argb = TiColorHelper.parseColor(extras.getString("bgac"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extras.getString("bgac"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("accentARGB")) {
            try {
                accent_argb = TiColorHelper.parseColor(extrasRoot.getString("accentARGB"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extrasRoot.getString("accentARGB"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("bgac")) {
            try {
                accent_argb = TiColorHelper.parseColor(extrasRoot.getString("bgac"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extrasRoot.getString("bgac"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        }

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

        nm.notify(notificationId, mBuilder.build());
    }
}

From source file:com.example.android.basicsyncadapter.SyncAdapter.java

/**
 * Called by the Android system in response to a request to run the sync adapter. The work required to read data from the network,
 * parse it, and store it in the content provider is done here. Extending AbstractThreadedSyncAdapter ensures that all methods
 * within SyncAdapter run on a background thread. For this reason, blocking I/O and other long-running tasks can be run
 * <em>in situ</em>, and you don't have to set up a separate thread for them.
 *
 * <p>This is where we actually perform any work required to perform a sync. {@link android.content.AbstractThreadedSyncAdapter}
 * guarantees that this will be called on a non-UI thread, so it is safe to peform blocking I/O here.
 *
 * <p>The syncResult argument allows you to pass information back to the method that triggered the sync.
 *//*from  w w  w .ja  v  a 2 s  .  c o m*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Beginning network synchronization");
    try {
        InputStream stream = null;

        try {
            //Log.i(TAG, "Streaming data from network: " + FEED_URL);
            //stream = downloadUrl(location);
            stream = downloadUrl(FEED_URL);
            updateLocalFeedData(stream, syncResult);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "Feed URL is malformed", e);
        syncResult.stats.numParseExceptions++;
        return;
    } catch (IOException e) {
        Log.e(TAG, "Error reading from network: " + e.toString());
        syncResult.stats.numIoExceptions++;
        return;
    } catch (XmlPullParserException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (ParseException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (RemoteException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    }
    Log.i(TAG, "Network synchronization complete");

    //Throw notification

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext())
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Alerta de cicln tropical")
            .setContentText("Hello World!").setAutoCancel(true).setLights(0xff00ff00, 300, 100)
            .setPriority(Notification.PRIORITY_MAX);

    Intent resultIntent = new Intent(getContext(), EntryListActivity.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getContext(), 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Add sound
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    //Add vibrate pattern
    long[] pattern = { 0, 200, 500 };

    mBuilder.setVibrate(pattern);
    mBuilder.setSound(alarmSound);
    mBuilder.setContentIntent(resultPendingIntent);

    int mNotificationId = 001;
    NotificationManager mNotifyMgr = (NotificationManager) getContext()
            .getSystemService(Service.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

    //Wake screen
    /*WakeLock screenOn = ((PowerManager)getContext().getSystemService(Service.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK| PowerManager.ACQUIRE_CAUSES_WAKEUP, "example");
    screenOn.acquire();
            
    long endTime = System.currentTimeMillis() + 6*1000;
    while (System.currentTimeMillis() < endTime) {
    synchronized (this) {
        try {
            wait(endTime - System.currentTimeMillis());
        } catch (Exception e) {
        }
    }
    }
            
    screenOn.release();*/
}

From source file:com.jiee.smartplug.services.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received./*from  w w  w .j av  a 2  s. co m*/
 */
private void sendNotification(String message) {

    System.out.println(message);

    NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notify = new Notification(R.drawable.svc_0_small_off, "title", System.currentTimeMillis());
    PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);

    notify.setLatestEventInfo(getApplicationContext(), "Subject", message, pending);
    notif.notify(0, notify);

    //        Intent intent = new Intent(this, MainActivity.class);
    //        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    //        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
    //                PendingIntent.FLAG_ONE_SHOT);
    //
    //        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    //        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
    //                .setSmallIcon(R.drawable.ic_stat_ic_notification)
    //                .setContentTitle("GCM Message")
    //                .setContentText(message)
    //                .setAutoCancel(true)
    //                .setSound(defaultSoundUri)
    //                .setContentIntent(pendingIntent);
    //
    //        NotificationManager notificationManager =
    //                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    //
    //        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

From source file:ch.nexuscomputing.android.osciprimeics.OsciPrimeService.java

/** switch state to idle **/
private void terminateAndClean() {
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    sNotification = new Notification();
    nm.notify(NOTIFICATION_ID, sNotification);
    mState = IDLE;/*w  w w.ja v  a2 s .  c o  m*/
    status();
}

From source file:at.flack.receiver.FacebookReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();/*from w  w  w.j av  a 2 s  . c om*/
    try {
        if (main instanceof FbMessageOverview && bundle.getString("type").equals("message")) {
            ((FbMessageOverview) main).addNewMessage(
                    new FacebookMessage(bundle.getString("fb_name"), bundle.getString("fb_message"),
                            bundle.getString("fb_img"), bundle.getLong("fb_id"), bundle.getString("fb_tid")));
        } else if (main instanceof FbMessageOverview && bundle.getString("type").equals("readreceipt")) {
            ((FbMessageOverview) main).changeReadReceipt(bundle.getLong("fb_time"),
                    bundle.getLong("fb_reader"));
        } else if (main instanceof FbMessageOverview && bundle.getString("type").equals("typ")) {
            ((FbMessageOverview) main).changeTypingStatus(bundle.getLong("my_id"), bundle.getLong("fb_id"),
                    bundle.getBoolean("fb_from_mobile"), bundle.getInt("fb_status"));
        } else if (main instanceof FbMessageOverview && bundle.getString("type").equals("img_message")) {
            ((FbMessageOverview) main).addNewMessage(new FacebookImageMessage(bundle.getString("fb_name"),
                    bundle.getString("fb_image"), bundle.getString("fb_preview"), bundle.getString("fb_img"),
                    bundle.getLong("fb_id"), bundle.getString("fb_tid")));
        } else if (bundle.getString("type").equals("read")) {
            killNotification(context,
                    new MarkAsRead(bundle.getString("fb_tid"), bundle.getBoolean("fb_markas")));
        } else if (bundle.getString("type").equals("message")
                || bundle.getString("type").equals("img_message")) {
            sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            if (!sharedPrefs.getBoolean("notification_fbs", true))
                return;
            notify = sharedPrefs.getBoolean("notifications", true);
            vibrate = sharedPrefs.getBoolean("vibration", true);
            headsup = sharedPrefs.getBoolean("headsup", true);
            led_color = sharedPrefs.getInt("notification_light", -16776961);
            boolean all = sharedPrefs.getBoolean("all_fb", true);

            if (notify == false)
                return;
            if (bundle.getLong("fb_id") == bundle.getLong("my_id")) {
                return;
            }

            NotificationCompat.Builder mBuilder = null;
            boolean use_profile_picture = false;
            Bitmap profile_picture = null;

            String origin_name = bundle.getString("fb_name");

            try {
                profile_picture = RoundedImageView.getCroppedBitmap(Bitmap.createScaledBitmap(
                        ProfilePictureCache.getInstance(context).get(origin_name), 200, 200, false), 300);
                use_profile_picture = true;
            } catch (Exception e) {
                use_profile_picture = false;
            }

            Resources res = context.getResources();

            if (bundle.getString("type").equals("img_message")) {
                bundle.putString("fb_message", res.getString(R.string.fb_notification_new_image));
            }

            int lastIndex = bundle.getString("fb_message").lastIndexOf("=");
            if (lastIndex > 0 && Base64.isBase64(bundle.getString("fb_message").substring(0, lastIndex))) {
                mBuilder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                        .setColor(0xFF175ea2)
                        .setContentText(res.getString(R.string.sms_receiver_new_encrypted_fb))
                        .setAutoCancel(true);
                if (use_profile_picture && profile_picture != null) {
                    mBuilder = mBuilder.setLargeIcon(profile_picture);
                } else {
                    mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                            context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                }
            } else { // normal or handshake

                if (bundle.getString("fb_message").charAt(0) == '%'
                        && (bundle.getString("fb_message").length() == 10
                                || bundle.getString("fb_message").length() == 9)) {
                    if (lastIndex > 0
                            && Base64.isBase64(bundle.getString("fb_message").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFF175ea2)
                                .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                                .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
                        if (use_profile_picture && profile_picture != null) {
                            mBuilder = mBuilder.setLargeIcon(profile_picture);
                        } else {
                            mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                    context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                        }
                    } else {
                        return;
                    }
                } else if (bundle.getString("fb_message").charAt(0) == '%'
                        && bundle.getString("fb_message").length() >= 120
                        && bundle.getString("fb_message").length() < 125) {
                    if (lastIndex > 0
                            && Base64.isBase64(bundle.getString("fb_message").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFF175ea2)
                                .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                                .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
                        if (use_profile_picture && profile_picture != null) {
                            mBuilder = mBuilder.setLargeIcon(profile_picture);
                        } else {
                            mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                    context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                        }
                    } else {
                        return;
                    }
                } else if (all) { // normal message
                    mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                            .setColor(0xFF175ea2).setContentText(bundle.getString("fb_message"))
                            .setAutoCancel(true).setStyle(new NotificationCompat.BigTextStyle()
                                    .bigText(bundle.getString("fb_message")));

                    if (use_profile_picture && profile_picture != null) {
                        mBuilder = mBuilder.setLargeIcon(profile_picture);
                    } else {
                        mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                    }
                } else {
                    return;
                }
            }
            // }
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(alarmSound);
            mBuilder.setLights(led_color, 750, 4000);
            if (vibrate) {
                mBuilder.setVibrate(new long[] { 0, 100, 200, 300 });
            }

            Intent resultIntent = new Intent(context, MainActivity.class);
            resultIntent.putExtra("FACEBOOK_NAME", origin_name);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(1,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            if (Build.VERSION.SDK_INT >= 16 && headsup)
                mBuilder.setPriority(Notification.PRIORITY_HIGH);
            if (Build.VERSION.SDK_INT >= 21)
                mBuilder.setCategory(Notification.CATEGORY_MESSAGE);

            final NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);

            if (!MainActivity.isOnTop)
                mNotificationManager.notify(8, mBuilder.build());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:at.univie.sensorium.SensorService.java

@Override
public void onCreate() {
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SensoriumActivity.class),
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.ic_launcher)
            .setWhen(System.currentTimeMillis()).setAutoCancel(true).setContentTitle(SensorRegistry.TAG)
            .setContentText("running");
    Notification n = builder.build();
    nm.notify(NOTIFICATION, n);
}

From source file:com.android.settings.locationprivacy.LocationPrivacyAdvancedSettings.java

private void addNotification(int id, int textID) {
    String text = getResources().getString(textID);
    Intent intent = new Intent(getActivity(), getActivity().getClass());
    intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, LocationPrivacySettings.class.getName());
    intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);

    Notification noti = new Notification.Builder(getActivity())
            .setContentTitle(getResources().getString(R.string.lp_webservice_notification_title))
            .setSmallIcon(R.drawable.ic_settings_locationprivacy)
            .setStyle(new Notification.BigTextStyle().bigText(text)).setContentIntent(pIntent)
            .setAutoCancel(true).build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            getActivity().NOTIFICATION_SERVICE);
    notificationManager.cancel(WEBSERVICE_ERROR);
    notificationManager.cancel(WEBSERVICE_OK);
    notificationManager.cancel(GOOGLE_PLAY);
    notificationManager.notify(id, noti);
}

From source file:barqsoft.footballscores.service.FetchScores.java

/**
 * Method to make a notification/*from   w  w w .  j  a v  a  2s.c om*/
 */
public void notifyUser(String info) {
    Context context = getApplicationContext();
    Resources resources = context.getResources();

    //build your notification here.
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
            .setColor(resources.getColor(R.color.green01)).setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle(getString(R.string.updated) + " " + info)
            .setContentText(getString(R.string.updated_descr))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.updated_descr)))
            .setAutoCancel(true);

    // Intent ti open the app
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    //stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}