Example usage for android.app Notification getClass

List of usage examples for android.app Notification getClass

Introduction

In this page you can find the example usage for android.app Notification getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:io.teak.sdk.NotificationBuilder.java

public static Notification createNativeNotification(final Context context, Bundle bundle,
        TeakNotification teakNotificaton) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Rich text message
    Spanned richMessageText = Html.fromHtml(teakNotificaton.message);

    // Configure notification behavior
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    builder.setDefaults(NotificationCompat.DEFAULT_ALL);
    builder.setOnlyAlertOnce(true);/*from w  w  w  .j a  v  a2 s . com*/
    builder.setAutoCancel(true);
    builder.setTicker(richMessageText);

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    Random rng = new Random();

    // Create intent to fire if/when notification is cleared
    Intent pushClearedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_CLEARED_INTENT_ACTION_SUFFIX);
    pushClearedIntent.putExtras(bundle);
    PendingIntent pushClearedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(),
            pushClearedIntent, PendingIntent.FLAG_ONE_SHOT);
    builder.setDeleteIntent(pushClearedPendingIntent);

    // Create intent to fire if/when notification is opened, attach bundle info
    Intent pushOpenedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_OPENED_INTENT_ACTION_SUFFIX);
    pushOpenedIntent.putExtras(bundle);
    PendingIntent pushOpenedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(), pushOpenedIntent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pushOpenedPendingIntent);

    // Because we can't be certain that the R class will line up with what is at SDK build time
    // like in the case of Unity et. al.
    class IdHelper {
        public int id(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "id", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.id." + identifier);
            }
            return ret;
        }

        public int layout(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "layout", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.layout." + identifier);
            }
            return ret;
        }
    }
    IdHelper R = new IdHelper(); // Declaring local as 'R' ensures we don't accidentally use the other R

    // Configure notification small view
    RemoteViews smallView = new RemoteViews(context.getPackageName(),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_notif_no_title_v21")
                    : R.layout("teak_notif_no_title"));

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        smallView.setImageViewResource(R.id("left_image"), ai.icon);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    // Set small view text
    smallView.setTextViewText(R.id("text"), richMessageText);

    // Check for Jellybean (API 16, 4.1)+ for expanded view
    RemoteViews bigView = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && teakNotificaton.longText != null
            && !teakNotificaton.longText.isEmpty()) {
        bigView = new RemoteViews(context.getPackageName(),
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_big_notif_image_text_v21")
                        : R.layout("teak_big_notif_image_text"));

        // Set big view text
        bigView.setTextViewText(R.id("text"), Html.fromHtml(teakNotificaton.longText));

        URI imageAssetA = null;
        try {
            imageAssetA = new URI(teakNotificaton.imageAssetA);
        } catch (Exception ignored) {
        }

        Bitmap topImageBitmap = null;
        if (imageAssetA != null) {
            try {
                URL aURL = new URL(imageAssetA.toString());
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                topImageBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap == null) {
            try {
                InputStream istr = context.getAssets().open("teak_notif_large_image_default.png");
                topImageBitmap = BitmapFactory.decodeStream(istr);
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap != null) {
            // Set large bitmap
            bigView.setImageViewBitmap(R.id("top_image"), topImageBitmap);
        } else {
            Log.e(LOG_TAG, "Unable to load image asset for Notification.");
            // Hide pulldown
            smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
        }
    } else {
        // Hide pulldown
        smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
    }

    // Voodoo from http://stackoverflow.com/questions/28169474/notification-background-in-android-lollipop-is-white-can-we-change-it
    int topId = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    int topBigLayout = Resources.getSystem().getIdentifier("notification_template_material_big_media_narrow",
            "layout", "android");
    int topSmallLayout = Resources.getSystem().getIdentifier("notification_template_material_media", "layout",
            "android");

    RemoteViews topBigView = null;
    if (bigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // This is invisible inner view - to have media_actions in hierarchy
        RemoteViews innerTopView = new RemoteViews("android", topBigLayout);
        bigView.addView(android.R.id.empty, innerTopView);

        // This should be on top - we need status_bar_latest_event_content as top layout
        topBigView = new RemoteViews("android", topBigLayout);
        topBigView.removeAllViews(topId);
        topBigView.addView(topId, bigView);
    } else if (bigView != null) {
        topBigView = bigView;
    }

    // This should be on top - we need status_bar_latest_event_content as top layout
    RemoteViews topSmallView;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        topSmallView = new RemoteViews("android", topSmallLayout);
        topSmallView.removeAllViews(topId);
        topSmallView.addView(topId, smallView);
    } else {
        topSmallView = smallView;
    }

    builder.setContent(topSmallView);

    Notification n = builder.build();
    if (topBigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // Use reflection to avoid compile-time issues, we check minimum API version above
        try {
            Field bigContentViewField = n.getClass().getField("bigContentView");
            bigContentViewField.set(n, topBigView);
        } catch (Exception ignored) {
        }
    }

    return n;
}

From source file:im.neon.util.NotificationUtils.java

/**
 * Build a message notification.//from w w w  .j ava  2 s  .c o  m
 * @param context the context
 * @param from the sender
 * @param matrixId the user account id;
 * @param displayMatrixId true to display the matrix id
 * @param largeIcon the notification icon
 * @param unseenNotifiedRoomsCount the number of notified rooms
 * @param body the message body
 * @param roomId the room id
 * @param roomName the room name
 * @param shouldPlaySound true when the notification as sound.
 * @param isInvitationEvent true if it is an invitation notification
 * @return the notification
 */
public static Notification buildMessageNotification(Context context, String from, String matrixId,
        boolean displayMatrixId, Bitmap largeIcon, int unseenNotifiedRoomsCount, String body, String roomId,
        String roomName, boolean shouldPlaySound, boolean isInvitationEvent) {

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setWhen(System.currentTimeMillis());

    if (!TextUtils.isEmpty(from)) {
        // don't display the room name for 1:1 room notifications.
        if (!TextUtils.isEmpty(roomName) && !roomName.equals(from)) {
            builder.setContentTitle(from + " (" + roomName + ")");
        } else {
            builder.setContentTitle(from);
        }
    } else {
        builder.setContentTitle(roomName);
    }

    builder.setContentText(body);
    builder.setAutoCancel(true);
    builder.setSmallIcon(R.drawable.message_notification_transparent);

    if (null != largeIcon) {
        largeIcon = createSquareBitmap(largeIcon);

        // add a bubble in the top right
        if (0 != unseenNotifiedRoomsCount) {
            try {
                android.graphics.Bitmap.Config bitmapConfig = largeIcon.getConfig();

                // set default bitmap config if none
                if (bitmapConfig == null) {
                    bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
                }

                // setLargeIcon must used a 64 * 64 pixels bitmap
                // rescale to have the same text UI.
                float densityScale = context.getResources().getDisplayMetrics().density;
                int side = (int) (64 * densityScale);

                Bitmap bitmapCopy = Bitmap.createBitmap(side, side, bitmapConfig);
                Canvas canvas = new Canvas(bitmapCopy);

                // resize the bitmap to fill in size
                int bitmapWidth = largeIcon.getWidth();
                int bitmapHeight = largeIcon.getHeight();

                float scale = Math.min((float) canvas.getWidth() / (float) bitmapWidth,
                        (float) canvas.getHeight() / (float) bitmapHeight);

                int scaledWidth = (int) (bitmapWidth * scale);
                int scaledHeight = (int) (bitmapHeight * scale);

                Bitmap rescaledBitmap = Bitmap.createScaledBitmap(largeIcon, scaledWidth, scaledHeight, true);
                canvas.drawBitmap(rescaledBitmap, (side - scaledWidth) / 2, (side - scaledHeight) / 2, null);

                String text = "" + unseenNotifiedRoomsCount;

                // prepare the text drawing
                Paint textPaint = new Paint();
                textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
                textPaint.setColor(Color.WHITE);
                textPaint.setTextSize(10 * densityScale);

                // get its size
                Rect textBounds = new Rect();

                if (-1 == mUnreadBubbleWidth) {
                    textPaint.getTextBounds("99", 0, 2, textBounds);
                    mUnreadBubbleWidth = textBounds.width();
                }

                textPaint.getTextBounds(text, 0, text.length(), textBounds);

                // draw a red circle
                int radius = mUnreadBubbleWidth;
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                canvas.drawCircle(canvas.getWidth() - radius, radius, radius, paint);

                // draw the text
                canvas.drawText(text,
                        canvas.getWidth() - textBounds.width() - (radius - (textBounds.width() / 2)),
                        -textBounds.top + (radius - (-textBounds.top / 2)), textPaint);

                // get the new bitmap
                largeIcon = bitmapCopy;
            } catch (Exception e) {
                Log.e(LOG_TAG, "## buildMessageNotification(): Exception Msg=" + e.getMessage());
            }
        }

        builder.setLargeIcon(largeIcon);
    }

    String name = ": ";
    if (!TextUtils.isEmpty(roomName)) {
        name = " (" + roomName + "): ";
    }

    if (displayMatrixId) {
        from = "[" + matrixId + "]\n" + from;
    }

    builder.setTicker(from + name + body);

    TaskStackBuilder stackBuilder;
    Intent intent;

    intent = new Intent(context, VectorRoomActivity.class);
    intent.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId);

    if (null != matrixId) {
        intent.putExtra(VectorRoomActivity.EXTRA_MATRIX_ID, matrixId);
    }

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

    // android 4.3 issue
    // use a generator for the private requestCode.
    // When using 0, the intent is not created/launched when the user taps on the notification.
    //
    PendingIntent pendingIntent = stackBuilder.getPendingIntent((new Random()).nextInt(1000),
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    // display the message with more than 1 lines when the device supports it
    NotificationCompat.BigTextStyle textStyle = new NotificationCompat.BigTextStyle();
    textStyle.bigText(from + ":" + body);
    builder.setStyle(textStyle);

    // do not offer to quick respond if the user did not dismiss the previous one
    if (!LockScreenActivity.isDisplayingALockScreenActivity()) {
        if (!isInvitationEvent) {
            // offer to type a quick answer (i.e. without launching the application)
            Intent quickReplyIntent = new Intent(context, LockScreenActivity.class);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_ROOM_ID, roomId);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_SENDER_NAME, from);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_MESSAGE_BODY, body);

            if (null != matrixId) {
                quickReplyIntent.putExtra(LockScreenActivity.EXTRA_MATRIX_ID, matrixId);
            }

            // the action must be unique else the parameters are ignored
            quickReplyIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
            PendingIntent pIntent = PendingIntent.getActivity(context, 0, quickReplyIntent, 0);
            builder.addAction(R.drawable.vector_notification_quick_reply,
                    context.getString(R.string.action_quick_reply), pIntent);
        } else {
            {
                // offer to type a quick reject button
                Intent leaveIntent = new Intent(context, JoinScreenActivity.class);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_ROOM_ID, roomId);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_MATRIX_ID, matrixId);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_REJECT, true);

                // the action must be unique else the parameters are ignored
                leaveIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, leaveIntent, 0);
                builder.addAction(R.drawable.vector_notification_reject_invitation,
                        context.getString(R.string.reject), pIntent);
            }

            {
                // offer to type a quick accept button
                Intent acceptIntent = new Intent(context, JoinScreenActivity.class);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_ROOM_ID, roomId);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_MATRIX_ID, matrixId);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_JOIN, true);

                // the action must be unique else the parameters are ignored
                acceptIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, acceptIntent, 0);
                builder.addAction(R.drawable.vector_notification_accept_invitation,
                        context.getString(R.string.join), pIntent);
            }
        }

        // Build the pending intent for when the notification is clicked
        Intent roomIntentTap;
        if (isInvitationEvent) {
            // for invitation the room preview must be displayed
            roomIntentTap = CommonActivityUtils.buildIntentPreviewRoom(matrixId, roomId, context,
                    VectorFakeRoomPreviewActivity.class);
        } else {
            roomIntentTap = new Intent(context, VectorRoomActivity.class);
            roomIntentTap.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId);
        }
        // the action must be unique else the parameters are ignored
        roomIntentTap.setAction(TAP_TO_VIEW_ACTION + ((int) (System.currentTimeMillis())));

        // Recreate the back stack
        TaskStackBuilder stackBuilderTap = TaskStackBuilder.create(context)
                .addParentStack(VectorRoomActivity.class).addNextIntent(roomIntentTap);

        builder.addAction(R.drawable.vector_notification_open, context.getString(R.string.action_open),
                stackBuilderTap.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
    }

    //extendForCar(context, builder, roomId, roomName, from, body);

    Notification n = builder.build();
    n.flags |= Notification.FLAG_SHOW_LIGHTS;
    n.defaults |= Notification.DEFAULT_LIGHTS;

    if (shouldPlaySound) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }

    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // some devices crash if this field is not set
        // even if it is deprecated

        // setLatestEventInfo() is deprecated on Android M, so we try to use
        // reflection at runtime, to avoid compiler error: "Cannot resolve method.."
        try {
            Method deprecatedMethod = n.getClass().getMethod("setLatestEventInfo", Context.class,
                    CharSequence.class, CharSequence.class, PendingIntent.class);
            deprecatedMethod.invoke(n, context, from, body, pendingIntent);
        } catch (Exception ex) {
            Log.e(LOG_TAG,
                    "## buildMessageNotification(): Exception - setLatestEventInfo() Msg=" + ex.getMessage());
        }
    }

    return n;
}

From source file:im.neon.services.EventStreamService.java

/**
 * @return the polling thread listener notification
 *//*from   w ww  .  j  ava2s. com*/
@SuppressLint("NewApi")
private Notification buildForegroundServiceNotification() {
    // build the pending intent go to the home screen if this is clicked.
    Intent i = new Intent(this, VectorHomeActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

    // build the notification builder
    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
    notifBuilder.setSmallIcon(R.drawable.permanent_notification_transparent);
    notifBuilder.setWhen(System.currentTimeMillis());
    notifBuilder.setContentTitle(getString(R.string.app_name));
    notifBuilder.setContentText(NOTIFICATION_SUB_TITLE);
    notifBuilder.setContentIntent(pi);

    // hide the notification from the status bar
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notifBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
    }

    Notification notification = notifBuilder.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;

    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // some devices crash if this field is not set
        // even if it is deprecated

        // setLatestEventInfo() is deprecated on Android M, so we try to use
        // reflection at runtime, to avoid compiler error: "Cannot resolve method.."
        try {
            Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class,
                    CharSequence.class, CharSequence.class, PendingIntent.class);
            deprecatedMethod.invoke(notification, this, getString(R.string.app_name), NOTIFICATION_SUB_TITLE,
                    pi);
        } catch (Exception ex) {
            Log.e(LOG_TAG, "## buildNotification(): Exception - setLatestEventInfo() Msg=" + ex.getMessage());
        }
    }

    return notification;
}

From source file:com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient.java

private boolean displayNotification(final Bundle pushBundle, final Class<?> targetClass, String imageUrl,
        String iconImageUrl, String iconSmallImageUrl, Map<String, String> campaignAttributes,
        String intentAction) {//from ww w.ja va  2  s  .c  o m
    log.info("Display Notification: " + pushBundle.toString());

    final String title = pushBundle.getString(NOTIFICATION_TITLE_PUSH_KEY);
    final String message = pushBundle.getString(NOTIFICATION_BODY_PUSH_KEY);

    final String campaignId = campaignAttributes.get(CAMPAIGN_ID_ATTRIBUTE_KEY);
    final String activityId = campaignAttributes.get(CAMPAIGN_ACTIVITY_ID_ATTRIBUTE_KEY);

    final int requestID = (campaignId + ":" + activityId + ":" + System.currentTimeMillis()).hashCode();

    final int iconResId = getNotificationIconResourceId(pushBundle.getString(NOTIFICATION_ICON_PUSH_KEY));
    if (iconResId == 0) {
        return false;
    }

    final Notification notification = createNotification(iconResId, title, message, imageUrl, iconImageUrl,
            iconSmallImageUrl,
            this.createOpenAppPendingIntent(pushBundle, targetClass, campaignId, requestID, intentAction));

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;

    if (android.os.Build.VERSION.SDK_INT >= ANDROID_LOLLIPOP) {
        log.info("SDK greater than 21 detected: " + android.os.Build.VERSION.SDK_INT);

        final String colorString = pushBundle.getString(NOTIFICATION_COLOR_PUSH_KEY);
        if (colorString != null) {
            int color;
            try {
                color = Color.parseColor(colorString);
            } catch (final IllegalArgumentException ex) {
                log.warn("Couldn't parse campaign notification color.", ex);
                color = 0;
            }
            Exception exception = null;
            try {
                final Field colorField = notification.getClass().getDeclaredField("color");
                colorField.setAccessible(true);
                colorField.set(notification, color);
            } catch (final IllegalAccessException ex) {
                exception = ex;
            } catch (final NoSuchFieldException ex) {
                exception = ex;
            }
            if (exception != null) {
                log.error("Couldn't set campaign notification color : " + exception.getMessage(), exception);
            }
        }
    }

    final NotificationManager notificationManager = (NotificationManager) pinpointContext
            .getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(requestID, notification);
    return true;
}