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:de.yaacc.upnp.server.YaaccUpnpServerService.java

/**
 * Displays the notification./*from   ww  w  . ja  v  a2s .c om*/
 */
private void showNotification() {
    Intent notificationIntent = new Intent(this, YaaccUpnpServerControlActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Yaacc Upnp Server")
            .setContentText(preferences
                    .getString(getApplicationContext().getString(R.string.settings_local_server_name_key), ""));
    mBuilder.setContentIntent(contentIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(NotificationId.UPNP_SERVER.getId(), mBuilder.build());
}

From source file:at.bitfire.davdroid.syncadapter.DavSyncAdapter.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override// ww w.j a v a 2 s.c o m
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Performing sync for authority " + authority);

    /* Set class loader for iCal4j ResourceLoader  this is required because the various
     * sync adapters (contacts, events, tasks) share the same :sync process (see AndroidManifest */
    Thread.currentThread().setContextClassLoader(getContext().getClassLoader());

    // create httpClient, if necessary
    httpClientLock.writeLock().lock();
    if (httpClient == null) {
        Log.d(TAG, "Creating new DavHttpClient");
        httpClient = DavHttpClient.create();
    }

    // prevent httpClient shutdown until we're ready by holding a read lock
    // acquiring read lock before releasing write lock will downgrade the write lock to a read lock
    httpClientLock.readLock().lock();
    httpClientLock.writeLock().unlock();

    Exception exceptionToShow = null; // exception to show notification for
    Intent exceptionIntent = null; // what shall happen when clicking on the exception notification
    try {
        // get local <-> remote collection pairs
        Map<LocalCollection<?>, WebDavCollection<?>> syncCollections = getSyncPairs(account, provider);
        if (syncCollections == null)
            Log.i(TAG, "Nothing to synchronize");
        else
            try {
                for (Map.Entry<LocalCollection<?>, WebDavCollection<?>> entry : syncCollections.entrySet())
                    new SyncManager(entry.getKey(), entry.getValue())
                            .synchronize(extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL), syncResult);

            } catch (DavException ex) {
                syncResult.stats.numParseExceptions++;
                Log.e(TAG, "Invalid DAV response", ex);
                exceptionToShow = ex;

            } catch (HttpException ex) {
                if (ex.getCode() == HttpStatus.SC_UNAUTHORIZED) {
                    Log.e(TAG, "HTTP Unauthorized " + ex.getCode(), ex);
                    syncResult.stats.numAuthExceptions++; // hard error

                    exceptionToShow = ex;
                    exceptionIntent = new Intent(context, AccountActivity.class);
                    exceptionIntent.putExtra(AccountActivity.EXTRA_ACCOUNT, account);
                } else if (ex.isClientError()) {
                    Log.e(TAG, "Hard HTTP error " + ex.getCode(), ex);
                    syncResult.stats.numParseExceptions++; // hard error
                    exceptionToShow = ex;
                } else {
                    Log.w(TAG, "Soft HTTP error " + ex.getCode() + " (Android will try again later)", ex);
                    syncResult.stats.numIoExceptions++; // soft error
                }
            } catch (LocalStorageException ex) {
                syncResult.databaseError = true; // hard error
                Log.e(TAG, "Local storage (content provider) exception", ex);
                exceptionToShow = ex;
            } catch (IOException ex) {
                syncResult.stats.numIoExceptions++; // soft error
                Log.e(TAG, "I/O error (Android will try again later)", ex);
                if (ex instanceof SSLException) // always notify on SSL/TLS errors
                    exceptionToShow = ex;
            } catch (URISyntaxException ex) {
                syncResult.stats.numParseExceptions++; // hard error
                Log.e(TAG, "Invalid URI (file name) syntax", ex);
                exceptionToShow = ex;
            }
    } finally {
        // allow httpClient shutdown
        httpClientLock.readLock().unlock();
    }

    // show sync errors as notification
    if (exceptionToShow != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (exceptionIntent == null)
            exceptionIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.WEB_URL_VIEW_LOGS));

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, exceptionIntent, 0);
        Notification.Builder builder = new Notification.Builder(context).setSmallIcon(R.drawable.ic_launcher)
                .setPriority(Notification.PRIORITY_LOW).setOnlyAlertOnce(true)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(context.getString(R.string.sync_error_title))
                .setContentText(exceptionToShow.getLocalizedMessage()).setContentInfo(account.name)
                .setStyle(new Notification.BigTextStyle()
                        .bigText(account.name + ":\n" + ExceptionUtils.getStackTrace(exceptionToShow)))
                .setContentIntent(contentIntent);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(account.name.hashCode(), builder.build());
    }

    Log.i(TAG, "Sync complete for " + authority);
}

From source file:eu.codeplumbers.cosi.services.CosiNoteService.java

public void showNotification() {
    //PendingIntent pendingIntent = PendingIntent.getActivity(this, notification_id, this,PendingIntent.FLAG_UPDATE_CURRENT);

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(getString(R.string.lbl_files))
            .setContentText(getString(R.string.lbl_files_downloading)).setSmallIcon(R.drawable.ic_fa_file)
            //.addAction(R.drawable.ic_action_cancel, "Dismiss", getPendingIntent())
            .setOngoing(true);/*w ww. j a v  a  2  s.com*/
}

From source file:de.fahrgemeinschaft.BaseActivity.java

@Override
public void onSuccess(String what, int number) {
    if (what == null)
        return;/*from   ww  w .  jav  a 2  s  . c  o  m*/
    if (what.equals(ConnectorService.MYRIDES) && ic_myrides != null) {
        ic_myrides.setActionView(null);
        if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(ProfileFragment.INIT_CONTACTS,
                false)) {
            new GetContactsFromMyridesTask().execute(new String[] {});
        }
    } else if (what.equals(ConnectorService.AUTH) & ic_profile != null) {
        Crouton.makeText(this, getString(R.string.auth_success), Style.CONFIRM).show();
        ic_profile.setActionView(null);
        startService(new Intent(this, ConnectorService.class).setAction(ConnectorService.SEARCH));
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(42);
    }
    setProfileIcon();
}

From source file:com.pti.mates.GcmIntentService.java

private void sendNotificationMate(String msg) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    /*Cursor caux;//from  w ww.  ja  v a  2 s  .  c o  m
    caux = getApplicationContext().getContentResolver().query(DataProvider.CONTENT_URI_PROFILE, new String[] {DataProvider.COL_ID}, DataProvider.COL_FBID + "=" + senderid, null, null);
    Intent intent = new Intent(this, ChatActivity.class);
    intent.putExtra(Common.PROFILE_ID, caux.getString(caux.getColumnIndex(DataProvider.COL_ID)));*/
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(getApplicationContext(), MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Congratulations!")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:net.kourlas.voipms_sms.Notifications.java

public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
        Conversation[] conversations = Database.getInstance(applicationContext)
                .getConversations(preferences.getDid());
        for (Conversation conversation : conversations) {
            if (!conversation.isUnread() || !contacts.contains(conversation.getContact())
                    || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                            && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                                    .getContact().equals(conversation.getContact()))) {
                continue;
            }/*from  ww w  .j  ava 2  s.  c  o m*/

            String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
            if (smsContact == null) {
                smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
            }

            String allSmses = "";
            String mostRecentSms = "";
            boolean initial = true;
            for (Message message : conversation.getMessages()) {
                if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
                    if (initial) {
                        allSmses = message.getText();
                        mostRecentSms = message.getText();
                        initial = false;
                    } else {
                        allSmses = message.getText() + "\n" + allSmses;
                    }
                } else {
                    break;
                }
            }

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext);

            notificationBuilder.setContentTitle(smsContact);
            notificationBuilder.setContentText(mostRecentSms);
            notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
            notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
            notificationBuilder
                    .setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
            notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
            if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
                notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
            } else {
                notificationBuilder.setVibrate(new long[] { 0 });
            }
            notificationBuilder.setColor(0xFFAA0000);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

            Bitmap largeIconBitmap;
            try {
                largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                        Uri.parse(Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
                largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
                largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
                notificationBuilder.setLargeIcon(largeIconBitmap);
            } catch (Exception ignored) {

            }

            Intent intent = new Intent(applicationContext, ConversationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
            stackBuilder.addParentStack(ConversationActivity.class);
            stackBuilder.addNextIntent(intent);
            notificationBuilder
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

            Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
            } else {
                //noinspection deprecation
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            }
            replyIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent replyPendingIntent = PendingIntent.getActivity(applicationContext, 0, replyIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_reply_white_24dp,
                    applicationContext.getString(R.string.notifications_button_reply), replyPendingIntent);
            notificationBuilder.addAction(replyAction.build());

            Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
            markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast(applicationContext, 0,
                    markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_drafts_white_24dp,
                    applicationContext.getString(R.string.notifications_button_mark_read),
                    markAsReadPendingIntent);
            notificationBuilder.addAction(markAsReadAction.build());

            int id;
            if (notificationIds.get(conversation.getContact()) != null) {
                id = notificationIds.get(conversation.getContact());
            } else {
                id = notificationIdCount++;
                notificationIds.put(conversation.getContact(), id);
            }
            NotificationManager notificationManager = (NotificationManager) applicationContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static String create(Context p_context, DatabaseAdapter p_dba, DefaultHttpClient p_http) {
    startTimestamp = System.currentTimeMillis();

    if (isRunning == true) {
        isCanceled = true;//  w w w .j  av a 2 s . co m
        isRunning = false;
    }
    isRunning = true;
    boolean recordSyncTime = true;

    dba = p_dba;
    db = dba.db();
    em = dba.em();
    http_client = p_http;
    context = p_context;

    last_sync_ts = MyPreferences.getFlowzrLastSync(context);
    FLOWZR_BASE_URL = "https://" + MyPreferences.getSyncApiUrl(context);
    FLOWZR_API_URL = FLOWZR_BASE_URL + "/financisto3/";

    nsString = MyPreferences.getFlowzrAccount(context).replace("@", "_"); //urlsafe

    Log.i(TAG, "init sync engine, last sync was " + new Date(last_sync_ts).toLocaleString());
    //if (true) {
    if (!checkSubscriptionFromWeb()) {
        Intent notificationIntent = new Intent(context, FlowzrSyncActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon)
                .setTicker(context.getString(R.string.flowzr_subscription_required))
                .setContentTitle(context.getString(R.string.flowzr_sync_error))
                .setContentText(context.getString(R.string.flowzr_subscription_required,
                        MyPreferences.getFlowzrAccount(context)))
                .setContentIntent(pendingIntent).setAutoCancel(true).build();
        notificationManager.notify(0, notification);

        Log.w("flowzr", "subscription rejected from web");
        isCanceled = true;
        MyPreferences.unsetAutoSync(context);
        return null;
    } else {
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        // Sets an ID for the notification, so it can be updated

        mNotifyBuilder = new NotificationCompat.Builder(context).setAutoCancel(true)
                .setContentTitle(context.getString(R.string.flowzr_sync))
                .setContentText(context.getString(R.string.flowzr_sync_inprogress))
                .setSmallIcon(R.drawable.icon);
    }

    if (!isCanceled) {
        notifyUser("fix created entities", 5);
        fixCreatedEntities();
    }
    /**
     * pull delete
     */
    if (!isCanceled) {
        notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 10);
        try {
            pullDelete(last_sync_ts);
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }
    /**
     * push delete
     */
    if (!isCanceled) {
        notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 15);
        try {
            pushDelete();
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }
    /**
     * pull update
     */
    if (!isCanceled && last_sync_ts == 0) {
        notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20);
        try {
            pullUpdate();
        } catch (IOException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (JSONException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }
    /**
     * push update
     */
    if (!isCanceled) {
        notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 35);
        try {
            pushUpdate();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (IOException e) {
            e.printStackTrace();
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (JSONException e) {
            e.printStackTrace();
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (Exception e) {
            e.printStackTrace();
            recordSyncTime = false;
        }
    }
    /**
     * pull update
     */
    if (!isCanceled && last_sync_ts > 0) {
        notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20);
        try {
            pullUpdate();
        } catch (IOException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (JSONException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }

    notifyUser(context.getString(R.string.integrity_fix), 80);
    new IntegrityFix(dba).fix();
    /**
     * send account balances boundaries
     */
    if (!isCanceled) {
        //if (true) { //will generate a Cloud Messaging request if prev. aborted
        notifyUser(context.getString(R.string.flowzr_sync_sending) + "...", 85);
        //nm.notify(NOTIFICATION_ID, mNotifyBuilder.build());
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("action", "balancesRecalc"));
        nameValuePairs.add(new BasicNameValuePair("last_sync_ts", String.valueOf(last_sync_ts)));

        String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL
                : Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        nameValuePairs.add(new BasicNameValuePair("serialNumber", serialNumber));
        List<Account> accountsList = em.getAllAccountsList();
        for (Account account : accountsList) {
            nameValuePairs.add(new BasicNameValuePair(account.remoteKey, String.valueOf(account.totalAmount)));
            Log.i("flowzr", account.remoteKey + " " + String.valueOf(account.totalAmount));
        }
        try {
            httpPush(nameValuePairs, "balances");
        } catch (Exception e) {
            sendBackTrace(e);
        }
    }

    notifyUser("Widgets ...", 90);
    AccountWidget.updateWidgets(context);

    Handler refresh = new Handler(Looper.getMainLooper());
    refresh.post(new Runnable() {
        public void run() {
            if (currentActivity != null) {
                //currentActivity.refreshCurrentTab();
            }
        }
    });

    if (!isCanceled && MyPreferences.doGoogleDriveUpload(context)) {
        notifyUser(context.getString(R.string.flowzr_sync_sending) + " Google Drive", 95);
        pushAllBlobs();
    } else {
        Log.i("flowzr", "picture upload desactivated in prefs");
    }
    notifyUser(context.getString(R.string.flowzr_sync_success), 100);
    if (isCanceled == false) {
        if (recordSyncTime == true) {
            last_sync_ts = System.currentTimeMillis();
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
            editor.putLong("PROPERTY_LAST_SYNC_TIMESTAMP", last_sync_ts);
            editor.commit();
        }
    }
    //
    mNotificationManager.cancel(NOTIFICATION_ID);
    isRunning = false;
    isCanceled = false;
    if (context instanceof FlowzrSyncActivity) {
        ((FlowzrSyncActivity) context).setIsFinished();
    }
    return FLOWZR_BASE_URL;

}

From source file:io.indy.drone.service.ScheduledService.java

public void createNotification() {
    // get the id of the latest strike
    String region = SQLDatabase.regionFromIndex(0); // worldwide
    String id = mDatabase.getRecentStrikeIdInRegion(region);
    Strike strike = mDatabase.getStrike(id);

    String title = getString(R.string.notification_preface) + " " + strike.getCountry();
    String droneSummary = strike.getDroneSummary();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notification).setContentTitle(title).setContentText(droneSummary)
            .setAutoCancel(true);/*from  w  ww . j a  v  a 2 s.  co m*/

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, StrikeDetailActivity.class);
    resultIntent.putExtra(SQLDatabase.KEY_ID, id);
    resultIntent.putExtra(SQLDatabase.REGION, region);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(StrikeDetailActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle(title);
        bigTextStyle.bigText(strike.getBijSummaryShort());
        bigTextStyle.setSummaryText(droneSummary);

        // Moves the big view style object into the notification object.
        mBuilder.setStyle(bigTextStyle);
    }

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

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

private void generateNotification(Context context, String ticker, String title, String msg, int icon,
        Intent intent, String sound, int notificationId, MFPInternalPushMessage message) {

    int androidSDKVersion = Build.VERSION.SDK_INT;
    long when = System.currentTimeMillis();
    Notification notification = null;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    if (message.getGcmStyle() != null && androidSDKVersion > 21) {
        NotificationCompat.Builder mBuilder = null;
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        try {/*from  ww  w .j  ava 2 s  .c o  m*/
            JSONObject gcmStyleObject = new JSONObject(message.getGcmStyle());
            String type = gcmStyleObject.getString(TYPE);

            if (type != null && type.equalsIgnoreCase(PICTURE_NOTIFICATION)) {
                Bitmap remote_picture = null;
                NotificationCompat.BigPictureStyle notificationStyle = new NotificationCompat.BigPictureStyle();
                notificationStyle.setBigContentTitle(ticker);
                notificationStyle.setSummaryText(gcmStyleObject.getString(TITLE));

                try {
                    remote_picture = new getBitMapBigPictureNotification()
                            .execute(gcmStyleObject.getString(URL)).get();
                } catch (Exception e) {
                    logger.error(
                            "MFPPushIntentService:generateNotification() - Error while fetching image file.");
                }
                if (remote_picture != null) {
                    notificationStyle.bigPicture(remote_picture);
                }

                mBuilder = new NotificationCompat.Builder(context);
                notification = mBuilder.setSmallIcon(icon).setLargeIcon(remote_picture).setAutoCancel(true)
                        .setContentTitle(title)
                        .setContentIntent(PendingIntent.getActivity(context, notificationId, intent,
                                PendingIntent.FLAG_UPDATE_CURRENT))
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentText(msg).setStyle(notificationStyle).build();

            } else if (type != null && type.equalsIgnoreCase(BIGTEXT_NOTIFICATION)) {
                NotificationCompat.BigTextStyle notificationStyle = new NotificationCompat.BigTextStyle();
                notificationStyle.setBigContentTitle(ticker);
                notificationStyle.setSummaryText(gcmStyleObject.getString(TITLE));
                notificationStyle.bigText(gcmStyleObject.getString(TEXT));

                mBuilder = new NotificationCompat.Builder(context);
                notification = mBuilder.setSmallIcon(icon).setAutoCancel(true).setContentTitle(title)
                        .setContentIntent(PendingIntent.getActivity(context, notificationId, intent,
                                PendingIntent.FLAG_UPDATE_CURRENT))
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentText(msg).setStyle(notificationStyle).build();
            } else if (type != null && type.equalsIgnoreCase(INBOX_NOTIFICATION)) {
                NotificationCompat.InboxStyle notificationStyle = new NotificationCompat.InboxStyle();
                notificationStyle.setBigContentTitle(ticker);
                notificationStyle.setSummaryText(gcmStyleObject.getString(TITLE));

                String lines = gcmStyleObject.getString(LINES).replaceAll("\\[", "").replaceAll("\\]", "");
                String[] lineArray = lines.split(",");

                for (String line : lineArray) {
                    notificationStyle.addLine(line);
                }

                mBuilder = new NotificationCompat.Builder(context);
                notification = mBuilder.setSmallIcon(icon).setAutoCancel(true).setContentTitle(title)
                        .setContentIntent(PendingIntent.getActivity(context, notificationId, intent,
                                PendingIntent.FLAG_UPDATE_CURRENT))
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentText(msg).setStyle(notificationStyle).build();
            }

            notification.flags = Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(notificationId, notification);
        } catch (JSONException e) {
            logger.error("MFPPushIntentService:generateNotification() - Error while parsing JSON.");
        }

    } else {
        if (androidSDKVersion > 10) {
            builder.setContentIntent(PendingIntent.getActivity(context, notificationId, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT)).setSmallIcon(icon).setTicker(ticker).setWhen(when)
                    .setAutoCancel(true).setContentTitle(title).setContentText(msg)
                    .setSound(getNotificationSoundUri(context, sound));

            if (androidSDKVersion > 15) {
                int priority = getPriorityOfMessage(message);
                builder.setPriority(priority);
                notification = builder.build();
            }

            if (androidSDKVersion > 19) {
                //As new material theme is very light, the icon is not shown clearly
                //hence setting the background of icon to black
                builder.setColor(Color.BLACK);
                Boolean isBridgeSet = message.getBridge();
                if (!isBridgeSet) {
                    // show notification only on current device.
                    builder.setLocalOnly(true);
                }

                notification = builder.build();
                int receivedVisibility = 1;
                String visibility = message.getVisibility();
                if (visibility != null && visibility.equalsIgnoreCase(MFPPushConstants.VISIBILITY_PRIVATE)) {
                    receivedVisibility = 0;
                }
                if (receivedVisibility == Notification.VISIBILITY_PRIVATE && message.getRedact() != null) {
                    builder.setContentIntent(PendingIntent.getActivity(context, notificationId, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT)).setSmallIcon(icon).setTicker(ticker)
                            .setWhen(when).setAutoCancel(true).setContentTitle(title)
                            .setContentText(message.getRedact())
                            .setSound(getNotificationSoundUri(context, sound));

                    notification.publicVersion = builder.build();
                }
            }

            if (androidSDKVersion > 21) {
                String setPriority = message.getPriority();
                if (setPriority != null && setPriority.equalsIgnoreCase(MFPPushConstants.PRIORITY_MAX)) {
                    //heads-up notification
                    builder.setContentText(msg).setFullScreenIntent(PendingIntent.getActivity(context,
                            notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT), true);
                    notification = builder.build();
                }
            }

        } else {
            notification = builder
                    .setContentIntent(
                            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
                    .setSmallIcon(icon).setTicker(ticker).setWhen(when).setAutoCancel(true)
                    .setContentTitle(title).setContentText(msg)
                    .setSound(getNotificationSoundUri(context, sound)).build();
        }

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

        notificationManager.notify(notificationId, notification);
    }
}

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

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();/*from w ww .jav  a  2  s  .  c  o  m*/
    try {
        if (bundle.getString("type").equals("mail")) {
            sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            if (!sharedPrefs.getBoolean("notification_mail", 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_mail", true);

            if (notify == false)
                return;

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

            String origin_name = bundle.getString("senderName").equals("") ? bundle.getString("senderMail")
                    : bundle.getString("senderName");

            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();

            int lastIndex = bundle.getString("subject").lastIndexOf("=");
            if (lastIndex > 0 && Base64.isBase64(bundle.getString("subject").substring(0, lastIndex))) {
                mBuilder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                        .setColor(0xFFFF5722)
                        .setContentText(res.getString(R.string.sms_receiver_new_encrypted_mail))
                        .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 {

                if (bundle.getString("subject").charAt(0) == '%' && (bundle.getString("subject").length() == 10
                        || bundle.getString("subject").length() == 9)) {
                    if (lastIndex > 0 && Base64.isBase64(bundle.getString("subject").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFFFF5722)
                                .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("subject").charAt(0) == '%'
                        && bundle.getString("subject").length() >= 120
                        && bundle.getString("subject").length() < 125) {
                    if (lastIndex > 0 && Base64.isBase64(bundle.getString("subject").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFFFF5722)
                                .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(0xFFFF5722).setContentText(bundle.getString("subject"))
                            .setAutoCancel(true).setStyle(
                                    new NotificationCompat.BigTextStyle().bigText(bundle.getString("subject")));

                    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("MAIL", bundle.getString("senderMail"));

            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(9, mBuilder.build());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}