Example usage for android.support.v4.app NotificationManagerCompat from

List of usage examples for android.support.v4.app NotificationManagerCompat from

Introduction

In this page you can find the example usage for android.support.v4.app NotificationManagerCompat from.

Prototype

public static NotificationManagerCompat from(Context context) 

Source Link

Usage

From source file:at.bitfire.nophonespam.CallReceiver.java

protected void rejectCall(@NonNull Context context, Number number) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    Class c = null;// w  w w .j a v  a  2 s  .  c o m
    try {
        c = Class.forName(tm.getClass().getName());
        Method m = c.getDeclaredMethod("getITelephony");
        m.setAccessible(true);

        ITelephony telephony = (ITelephony) m.invoke(tm);

        telephony.endCall();
    } catch (Exception e) {
        e.printStackTrace();
    }

    Settings settings = new Settings(context);
    if (settings.showNotifications()) {
        Notification notify = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(context.getString(R.string.receiver_notify_call_rejected))
                .setContentText(number != null ? (number.name != null ? number.name : number.number)
                        : context.getString(R.string.receiver_notify_private_number))
                .setPriority(NotificationCompat.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_CALL)
                .setShowWhen(true).setAutoCancel(true)
                .setContentIntent(PendingIntent.getActivity(context, 0,
                        new Intent(context, BlacklistActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
                .addPerson("tel:" + number).setGroup("rejected").build();

        String tag = number != null ? number.number : "private";
        NotificationManagerCompat.from(context).notify(tag, NOTIFY_REJECTED, notify);
    }

}

From source file:com.morlunk.mumbleclient.service.PlumbleReconnectNotification.java

public void hide() {
    try {//from  w  w  w  .jav  a2  s . c  o m
        mContext.unregisterReceiver(mNotificationReceiver);
    } catch (IllegalArgumentException e) {
        // Thrown if receiver is not registered.
        e.printStackTrace();
    }
    NotificationManagerCompat nmc = NotificationManagerCompat.from(mContext);
    nmc.cancel(NOTIFICATION_ID);
}

From source file:cl.chihau.holaauto.MessagingService.java

private void sendNotificationForConversation(int conversationId, String sender, String message,
        long timestamp) {
    // A pending Intent for reads
    PendingIntent readPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), conversationId,
            getMessageReadIntent(conversationId), PendingIntent.FLAG_UPDATE_CURRENT);

    /// Add the code to create the UnreadConversation
    // Build a RemoteInput for receiving voice input in a Car Notification
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).build();

    // Building a Pending Intent for the reply action to trigger
    PendingIntent replyIntent = PendingIntent.getBroadcast(getApplicationContext(), conversationId,
            getMessageReplyIntent(conversationId), PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the UnreadConversation and populate it with the participant name,
    // read and reply intents.
    NotificationCompat.CarExtender.UnreadConversation.Builder unreadConversationBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
            sender).setLatestTimestamp(timestamp).setReadPendingIntent(readPendingIntent)
                    .setReplyAction(replyIntent, remoteInput);

    // Note: Add messages from oldest to newest to the UnreadConversation.Builder
    // Since we are sending a single message here we simply add the message.
    // In a real world application there could be multiple messages which should be ordered
    // and added from oldest to newest.
    unreadConversationBuilder.addMessage(message);

    /// End create UnreadConversation

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.drawable.notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
                    R.drawable.android_contact))
            .setContentText(message).setWhen(timestamp).setContentTitle(sender)
            .setContentIntent(readPendingIntent).setContentIntent(readPendingIntent)
            /// Extend the notification with CarExtender.
            .extend(new NotificationCompat.CarExtender()
                    .setUnreadConversation(unreadConversationBuilder.build()))
    /// End//from   ww w  .j  a va  2  s .c  om
    ;

    Log.d(TAG, "Sending notification " + conversationId + " conversation: " + message);

    NotificationManagerCompat.from(this).notify(conversationId, builder.build());
}

From source file:com.vinexs.eeb.receiver.BaseReceiverGCM.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public void onMessageTypeReceive(Context context, Intent intent) {
    notifyMgr = NotificationManagerCompat.from(context);
    SharedPreferences setting = PreferenceManager.getDefaultSharedPreferences(context);
    int notifyId = setting.getInt("notifyId", new Random().nextInt(65535));
    Bundle receIntent = intent.getExtras();
    try {/*from  ww w.j  a  va2 s. c  o m*/
        if (!receIntent.containsKey("contentTitle") || !receIntent.containsKey("contentText")) {
            throw new Exception("Message don't contain necessary data.");
        }

        if (builder == null) {
            builder = new NotificationCompat.Builder(context);
            contentTitle = receIntent.getCharSequence("contentTitle");
            contentText = receIntent.getCharSequence("contentText");

            builder.setDefaults(Notification.DEFAULT_ALL).setContentTitle(contentTitle)
                    .setContentText(contentText).setSmallIcon(getMonoColorIcon())
                    .setWhen(System.currentTimeMillis()).setAutoCancel(true).setOnlyAlertOnce(true);
            try {
                if (Build.VERSION.SDK_INT < 14 || !receIntent.containsKey("largeIcon")) {
                    throw new Exception("Message don't contain [largeIcon] or device SDK lower than 14.");
                }
                String bigIconUrl = receIntent.getString("largeIcon");
                if (bigIconUrl == null || bigIconUrl.isEmpty()) {
                    throw new Exception("Message [largeIcon] is empty.");
                }
                HttpURLConnection connection = (HttpURLConnection) new URL(bigIconUrl).openConnection();
                connection.setDoInput(true);
                connection.connect();
                Bitmap bigIcon = BitmapFactory.decodeStream(connection.getInputStream());
                builder.setLargeIcon(bigIcon);
                // Add backgroud to wearable
                NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
                wearableExtender.setBackground(bigIcon);
                builder.extend(wearableExtender);
                // Set accent color
                int[] attrs = new int[] { R.attr.colorAccent };
                TypedArray ta = context.obtainStyledAttributes(attrs);
                String colorAccent = ta.getString(0);
                ta.recycle();
                builder.setColor(Color.parseColor(colorAccent));
            } catch (Exception e) {
                builder.setLargeIcon(
                        BitmapFactory.decodeResource(context.getResources(), getApplicationIcon()));
            }
            try {
                if (!receIntent.containsKey("ticker")) {
                    throw new Exception("Message don't contain [ticker].");
                }
                builder.setTicker(receIntent.getCharSequence("ticker"));
            } catch (Exception e) {
                builder.setTicker(receIntent.getCharSequence("contentText"));
            }
            if (Build.VERSION.SDK_INT >= 16) {
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText));
            }
        } else {
            contentText = contentText + "\n" + receIntent.getCharSequence("contentText");
            messageNum++;
            builder.setContentTitle(Utility.getAppName(context)).setContentText(contentText)
                    .setTicker(receIntent.getCharSequence("contentText")).setNumber(messageNum);
        }

        if (Build.VERSION.SDK_INT >= 16) {
            builder.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText));
        }

        Intent actionIntent = new Intent(context, getLauncherClass());
        if (receIntent.containsKey("intentAction")) {
            actionIntent.putExtra("onNewIntentAction", receIntent.getCharSequence("intentAction"));
        }
        actionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, actionIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        notifyMgr.notify(notifyId, builder.build());
    } catch (Exception e) {
        Log.d("GoogleCloudMessaging",
                "Exception occurred while show message as notification -> " + e.toString());
        e.printStackTrace();
    }
}

From source file:com.developer.shade.sensors.SensorService.java

private void initNotification() {
    Log.v("Running initNot", "Method To Create Notification For Monitoring Service");
    NotificationCompat.Builder notiBuilder = new NotificationCompat.Builder(this);
    notiBuilder.setContentTitle("Running Fall Detection");
    notiBuilder.setSmallIcon(R.mipmap.ic_launcher);
    notiBuilder.setAutoCancel(false);//from  www. j ava 2  s.  co  m

    Notification noti = notiBuilder.build();
    noti.flags = Notification.FLAG_ONGOING_EVENT;

    notiManager = NotificationManagerCompat.from(this);
    notiManager.notify(NOTIFICATION_ID, noti);
}

From source file:zhenma.myapplication.DataLayerListenerService.java

public void btnShowNotificationClick(String friend_id, String name, boolean if_friend) {
    int notificationId = 101;

    // Create an intent for the reply action
    Intent actionIntent = new Intent(this, MainActivity.class);
    if (if_friend) {
        actionIntent.putExtra("methodName", "noAction");
    } else {//from  ww  w. jav  a  2  s.  c om
        actionIntent.putExtra("methodName", "sendAcceptMessage");
    }
    actionIntent.putExtra("friend_id", friend_id);
    actionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent actionPendingIntent = PendingIntent.getActivity(this, 0, actionIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the action
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_checked,
            getString(if_friend ? R.string.oldFriendRemind : R.string.acceptButt), actionPendingIntent).build();

    //Building notification layout
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(if_friend ? R.drawable.yellow_handshack : R.drawable.red_handshack)
            .setContentTitle(if_friend ? "Old Friend: " + name : "New Friend Request: " + name)
            .setDefaults(Notification.DEFAULT_ALL).setContentText("Swipe left!")
            .extend(new NotificationCompat.WearableExtender().addAction(action));

    // instance of the NotificationManager service
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    // Build the notification and notify it using notification manager.
    notificationManager.notify(notificationId, notificationBuilder.build());
    Log.d("Notification", "Notify Sent!");
}

From source file:com.rafamaya.imagesearch.DataLayerListenerService.java

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    LOGD(TAG, "onMessageReceived: " + messageEvent);

    // Check to see if the message is to start an activity
    if (messageEvent.getPath().equals(START_ACTIVITY_PATH)) {

        Intent startIntent = new Intent(this, PhotoActivity.class).setAction(Intent.ACTION_MAIN)
                .setData(Uri.fromParts("NODEID", messageEvent.getSourceNodeId(), ""));
        PendingIntent startPendingIntent = PendingIntent.getActivity(this, 0, startIntent, 0);
        long[] pattern = { 0, 100, 1000 };

        Notification notify = new NotificationCompat.Builder(this).setAutoCancel(false)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("View or Search images and sync navigation!"))
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setVibrate(pattern)//from  w ww  .j  a v a 2 s.  c  o m
                //.addAction(android.R.drawable.ic_menu_gallery, "View", startPendingIntent)
                .setSmallIcon(R.drawable.ic_launcher).setContentIntent(startPendingIntent).build();

        notify.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(0, notify);
    }
}

From source file:com.example.android.wearable.wear.wearnotifications.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMainRelativeLayout = (RelativeLayout) findViewById(R.id.mainRelativeLayout);
    mNotificationDetailsTextView = (TextView) findViewById(R.id.notificationDetails);
    mSpinner = (Spinner) findViewById(R.id.spinner);

    mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,
            NOTIFICATION_STYLES);//w w w  .jav  a  2 s . c o m
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    mSpinner.setAdapter(adapter);
    mSpinner.setOnItemSelectedListener(this);
}

From source file:com.alchemiasoft.book.service.SuggestionService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG_LOG, "Starting a new book suggestion...");
    final ContentResolver cr = getContentResolver();
    final Cursor c = cr.query(BookDB.Book.CONTENT_URI, null, SELECTION, SELECT_NOT_OWNED, null);
    Book book = null;/*ww  w .j a va  2  s  .  c  o  m*/
    try {
        if (c.moveToNext()) {
            book = Book.oneFrom(c);
        }
    } finally {
        c.close();
    }
    // Showing a notification if a not owned book is found
    if (book != null) {
        Log.d(TAG_LOG, "Found book that can be suggested: " + book);
        final String content = getString(R.string.content_book_suggestion, book.getTitle(), book.getAuthor());
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
                .setContentTitle(getString(R.string.title_book_suggestion)).setContentText(content);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(content));
        builder.setContentIntent(PendingIntent.getActivity(this, 0, HomeActivity.createFor(this, book),
                PendingIntent.FLAG_UPDATE_CURRENT));

        // ONLY 4 WEARABLE(s)
        final NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        // SECOND PAGE WITH BOOK DESCRIPTION
        wearableExtender
                .addPage(new NotificationCompat.Builder(this).setContentTitle(getString(R.string.description))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(book.getDescrition())).build());
        wearableExtender.setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.background));
        // ACTION TO PURCHASE A BOOK FROM A WEARABLE
        final PendingIntent purchaseIntent = PendingIntent.getService(this, 0, BookActionService.IntentBuilder
                .buy(this, book).notificationId(ID_SUGGESTION).wearableInput().build(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_buy,
                getString(R.string.action_buy), purchaseIntent).build());
        // ACTION TO ADD NOTES VIA VOICE REPLY
        final RemoteInput input = BookActionService.RemoteInputBuilder.create(this)
                .options(R.array.note_options).build();
        final PendingIntent notesIntent = PendingIntent
                .getService(
                        this, 0, BookActionService.IntentBuilder.addNote(this, book)
                                .notificationId(ID_SUGGESTION).wearableInput().build(),
                        PendingIntent.FLAG_UPDATE_CURRENT);
        wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_notes,
                getString(R.string.action_notes), notesIntent).addRemoteInput(input).build());
        // Finally extending the notification
        builder.extend(wearableExtender);

        // Sending the notification
        NotificationManagerCompat.from(this).notify(ID_SUGGESTION, builder.build());
    }
    // Completing the Wakeful Intent
    SuggestionReceiver.completeWakefulIntent(intent);
}

From source file:google.example.com.googletraning.sample.android6.activenotifications.ActiveNotificationFragment.java

/**
 * Request the current number of notifications from the {@link NotificationManager} and
 * display them to the user./*from   www .ja v a2s.co m*/
 */
protected void updateNumberOfNotifications() {
    int numberOfNotifications = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // [BEGIN get_active_notifications]
        // Query the currently displayed notifications.
        final StatusBarNotification[] activeNotifications = mNotificationManager.getActiveNotifications();
        // [END get_active_notifications]
        numberOfNotifications = activeNotifications.length;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
        if (getContext() != null) {
            numberOfNotifications = NotificationManagerCompat.from(getContext())
                    .getEnabledListenerPackages(getContext()).size();
        }
    }
    mNumberOfNotifications.setText(getString(R.string.active_notifications, numberOfNotifications));
    Log.i(TAG, getString(R.string.active_notifications, numberOfNotifications));
}