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:com.iniciacomunicacion.devicenotification.DeviceNotification.java

/**
 * Cancel a specific notification that was previously registered.
 * //from www .  ja v  a 2s . c  o  m
 * @param callbackContext, Callback context of the request from Cordova
 * @param id, notification id registered using add()
 * @see add
 */
public void cancel(CallbackContext callbackContext, int id) {
    NotificationManager notificationManager = (NotificationManager) cordova.getActivity()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(id);
}

From source file:jahirfiquitiva.iconshowcase.services.NotificationsService.java

@SuppressWarnings("ResourceAsColor")
private void pushNotification(String content, int type, int ID) {

    Preferences mPrefs = new Preferences(this);

    String appName = Utils.getStringFromResources(this, R.string.app_name);

    String title = appName, notifContent = null;

    switch (type) {
    case 1:/*w w w .  j ava2  s .  co  m*/
        title = getResources().getString(R.string.new_walls_notif_title, appName);
        notifContent = getResources().getString(R.string.new_walls_notif_content, content);
        break;
    case 2:
        title = appName + " " + getResources().getString(R.string.news).toLowerCase();
        notifContent = content;
        break;
    }

    // Send Notification
    NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
    notifBuilder.setAutoCancel(true);
    notifBuilder.setContentTitle(title);
    if (notifContent != null) {
        notifBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notifContent));
        notifBuilder.setContentText(notifContent);
    }
    notifBuilder.setTicker(title);
    Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    notifBuilder.setSound(ringtoneUri);

    if (mPrefs.getNotifsVibrationEnabled()) {
        notifBuilder.setVibrate(new long[] { 500, 500 });
    } else {
        notifBuilder.setVibrate(null);
    }

    int ledColor = ThemeUtils.darkTheme ? ContextCompat.getColor(this, R.color.dark_theme_accent)
            : ContextCompat.getColor(this, R.color.light_theme_accent);

    notifBuilder.setColor(ledColor);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notifBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    Class appLauncherActivity = getLauncherClass(getApplicationContext());

    if (appLauncherActivity != null) {
        Intent appIntent = new Intent(this, appLauncherActivity);
        appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        appIntent.putExtra("notifType", type);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(appLauncherActivity);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(appIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        notifBuilder.setContentIntent(resultPendingIntent);
    }

    notifBuilder.setOngoing(false);

    notifBuilder.setSmallIcon(R.drawable.ic_notifications);

    Notification notif = notifBuilder.build();

    if (mPrefs.getNotifsLedEnabled()) {
        notif.ledARGB = ledColor;
    }

    notifManager.notify(ID, notif);
}

From source file:br.com.imovelhunter.imovelhunterwebmobile.GcmIntentService.java

private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent in = new Intent(this, ChatActivity.class);

    Bundle extras = new Bundle();
    extras.putSerializable(Parametros.MENSAGEM_JSON.name(), this.mensagem);
    extras.putSerializable(ParametrosSessao.USUARIO_CHAT_ATUAL.name(), this.mensagem.getUsuarioRemetente());

    in.putExtras(extras);//from   w w w  .  ja va  2  s . com
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, in, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icone)
            .setContentTitle("Imovel Hunter - " + mensagem.getUsuarioRemetente().getNomeUsuario())
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

    mBuilder.setAutoCancel(true);

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

    this.vibrar();
}

From source file:com.keylesspalace.tusky.util.NotificationManager.java

/**
 * Takes a given Mastodon notification and either creates a new Android notification or updates
 * the state of the existing notification to reflect the new interaction.
 *
 * @param context  to access application preferences and services
 * @param notifyId an arbitrary number to reference this notification for any future action
 * @param body     a new Mastodon notification
 *///  ww  w  . ja  v a2  s.  co m
public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;
    }

    createNotificationChannels(context);

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).apply();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getChannelId(body))
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setColor(ContextCompat.getColor(context, (R.color.primary)))
            .setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    setupPreferences(preferences, builder);

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        //load the avatar synchronously
        Bitmap accountAvatar;
        try {
            accountAvatar = Picasso.with(context).load(body.account.avatar)
                    .transform(new RoundedTransformation(7, 0)).get();
        } catch (IOException e) {
            Log.d(TAG, "error loading account avatar", e);
            accountAvatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.avatar_default);
        }

        builder.setLargeIcon(accountAvatar);

    } else {
        try {
            String format = context.getString(R.string.notification_title_summary);
            String title = String.format(format, currentNotifications.length());
            String text = truncateWithEllipses(joinNames(context, currentNotifications), 40);
            builder.setContentTitle(title).setContentText(text);
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    android.app.NotificationManager notificationManager = (android.app.NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    //noinspection ConstantConditions
    notificationManager.notify(notifyId, builder.build());
}

From source file:com.handshake.notifications.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *///from www .j av  a  2  s .  com
private void sendNotification(final Bundle data, long userId, boolean isContact) {
    Intent intent;
    if (userId == 0) {
        intent = new Intent(this, MainActivity.class);
    } else if (isContact) {
        intent = new Intent(this, ContactUserProfileActivity.class);
    } else {
        intent = new Intent(this, GenericUserProfileActivity.class);
    }
    intent.putExtra("userId", userId);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    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("Handshake")
            .setContentText(data.getString("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:ca.rmen.android.poetassistant.PoemAudioExport.java

private void notifyPoemAudioInProgress() {
    Log.v(TAG, "notifyPoemAudioInProgress");
    cancelNotifications();//from ww  w. jav a2 s.c  o  m
    Notification notification = new NotificationCompat.Builder(mContext).setAutoCancel(false).setOngoing(true)
            .setContentIntent(getMainActivityIntent())
            .setContentTitle(mContext.getString(R.string.share_poem_audio_progress_notification_title))
            .setContentText(mContext.getString(R.string.share_poem_audio_progress_notification_message))
            .setSmallIcon(Share.getNotificationIcon()).build();
    NotificationManager notificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(EXPORT_PROGRESS_NOTIFICATION_ID, notification);
}

From source file:butter.droid.base.ButterApplication.java

@Override
public void updateAvailable(String updateFile) {
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (updateFile.length() > 0) {
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notif_logo).setContentTitle(getString(R.string.update_available))
                .setContentText(getString(R.string.press_install)).setAutoCancel(true)
                .setDefaults(NotificationCompat.DEFAULT_ALL);

        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(Uri.parse("file://" + updateFile), ButterUpdater.ANDROID_PACKAGE);

        notificationBuilder.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0));

        nm.notify(ButterUpdater.NOTIFICATION_ID, notificationBuilder.build());
    }//w ww.ja  v  a  2s. c  o m
}

From source file:com.chess.genesis.net.GenesisNotifier.java

private void SendNotification(final int id, final String text) {
    final Intent intent;
    if (Pref.getBool(this, R.array.pf_tabletMode)) {
        intent = new Intent(this, MainMenuTablet.class);

        final Bundle bundle = new Bundle();
        bundle.putInt("loadFrag", Enums.ONLINE_LIST);
        intent.putExtras(bundle);//w  ww  .j av a  2 s .c  om
    } else {
        intent = new Intent(this, GameListOnline.class);
    }

    final PendingIntent pintent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    final Notification note = createNotification(id, text, pintent);

    nm.notify(id, note);
}

From source file:ar.fiuba.jobify.JobifyChat.java

/**
 * Called when message is received./*from   w  w w  .  ja v  a  2  s. c o  m*/
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing both notification
    // and data payloads are treated as notification messages. The Firebase console always sends notification
    // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
    // [END_EXCLUDE]
    // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        String body = remoteMessage.getData() + "";
        Log.d(TAG, "Message data payload: " + body);
        JsonParser parser = new JsonParser();
        //JsonObject message = parser.parse(body).getAsJsonObject();
        JSONObject message = null;
        try {
            message = new JSONObject(body);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (message.has("mensaje")) {

            long sender = 0, receiver = 0;
            try {
                receiver = message.getJSONObject("mensaje").getLong("to");
                sender = message.getJSONObject("mensaje").getLong("from");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            long currentId = getSharedPreferences(getString(R.string.shared_pref_connected_user), 0)
                    .getLong(getString(R.string.stored_connected_user_id), -1);
            //Log.d("MYTAG", editor.g getLong( getString(R.string.stored_connected_user_id)));

            if (receiver != currentId) {
                // la app no esta abierta
                return;
            }

            if (!(ConversacionActivity.activityVisible && ConversacionActivity.corresponsalID == sender)) {
                NotificationCompat.Builder mBuilder = null;
                try {
                    mBuilder = new NotificationCompat.Builder(this).setContentTitle("Nuevo mensaje")
                            .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setAutoCancel(true)
                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.mensaje))
                            .setSmallIcon(R.drawable.logo_v2_j_square)
                            .setContentText(message.getJSONObject("mensaje").getString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //ConversacionActivity.

                Intent resultIntent = new Intent(this, ConversacionActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addParentStack(ConversacionActivity.class);

                // Adds the Intent that starts the Activity to the top of the stack
                stackBuilder.addNextIntent(resultIntent);
                resultIntent.putExtra(ConversacionActivity.CORRESPONSAL_ID_MESSAGE, (long) sender);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);

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

                Random r = new Random();
                mNotificationManager.notify(r.nextInt(1000000000), mBuilder.build());

            }
            // notify chat
            try {
                EventBus.getDefault().post(new MessageEvent(message.getJSONObject("mensaje")));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (message.has("solicitud")) {

            long receiver = 0;
            try {
                receiver = message.getJSONObject("solicitud").getLong("toId");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            long currentId = getSharedPreferences(getString(R.string.shared_pref_connected_user), 0)
                    .getLong(getString(R.string.stored_connected_user_id), -1);
            //Log.d("MYTAG", editor.g getLong( getString(R.string.stored_connected_user_id)));

            if (receiver != currentId) {
                // la app no esta abierta
                return;
            }

            NotificationCompat.Builder mBuilder = null;
            try {
                mBuilder = new NotificationCompat.Builder(this).setContentTitle("Nueva solicitud")
                        .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setAutoCancel(true)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.solicitud))
                        .setSmallIcon(R.drawable.logo_v2_j_square)
                        .setContentText(message.getJSONObject("solicitud").getString("fromNombre"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Intent resultIntent = new Intent(this, UserListActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(UserListActivity.class);

            // Adds the Intent that starts the Activity to the top of the stack
            stackBuilder.addNextIntent(resultIntent);
            resultIntent.putExtra(UserListActivity.LIST_MODE_MESSAGE, UserListActivity.MODE_SOLICITUDES);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);

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

            Random r = new Random();
            mNotificationManager.notify(r.nextInt(1000000000), mBuilder.build());

        }
        // if this is a notification:
        // TODO
        // here we call the callback to the activity

        // if this is a message:

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

From source file:br.com.bioscada.apps.biotracks.io.sendtogoogle.SendToGoogleUtils.java

/**
 * Sends a notification to request permission.
 * // w w  w.  j ava 2  s .  c  om
 * @param context the context
 * @param accountName the account name
 * @param intent the intent
 * @param notificaitonId the notification id
 */
public static void sendNotification(Context context, String accountName, Intent intent, int notificaitonId) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_FROM_BACKGROUND);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setContentText(context.getString(R.string.permission_request_message, accountName))
            .setContentTitle(context.getString(R.string.permission_request_title))
            .setSmallIcon(android.R.drawable.ic_dialog_alert)
            .setTicker(context.getString(R.string.permission_request_title));
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificaitonId, builder.build());
}