Skip to content

Instantly share code, notes, and snippets.

@uziassantosferreira
Last active October 27, 2017 12:30
Show Gist options
  • Save uziassantosferreira/4a2ad15f77ea824477227f6a726f2a54 to your computer and use it in GitHub Desktop.
Save uziassantosferreira/4a2ad15f77ea824477227f6a726f2a54 to your computer and use it in GitHub Desktop.

Simple classes for manager your notification.

dependencies:

compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.code.gson:gson:2.7'

Add this class CircleTransform from https://gist.github.com/julianshen/5829333

in NotificationExampleListener change the name to match your context and implement the methods.

Usage

Call this method

  NotificationManager.createNotification(context, bundle, listener);

Json notification manager support:

  "title": "Title Notification",
    "message": "Message notification",
    "notification_id": "1", // to update the created notification
    "url": "/action/like/",  //to follow the navigation
    "type": "1",  //  1 open activity 0 open navigation // DEFAULT IS NAVIGATION
    "image": "http://www.planwallpaper.com/static/images/i-should-buy-a-boat.jpg",
    "image_large": "http://www.planwallpaper.com/static/images/i-should-buy-a-boat.jpg",
    "actions": [ // to create action buttons in the notification
        {
            "label": "button label 1",
            "url": "/button/one",
            "type": "0"
        },  
        {
            "label": "button label 2",
            "url": "/button/two",
            "type": "1"
        }
        ]
  }
import java.io.Serializable;
public class Action implements Serializable {
public String label;
public String url;
public String type;
public Type getType(){
return Type.fromInt(Integer.parseInt(type));
}
}
import android.os.Bundle;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Random;
public class Notification {
public String title;
public String url;
public String message;
public String image;
public String imageLarge;
public int notificationId;
public int type;
public List<Action> actions;
public Type getType(){
return Type.fromInt(type);
}
public static Notification fromBundle(Bundle bundle) {
Notification notification = new Notification();
notification.title = getStringBundle(bundle, "title");
notification.url = getStringBundle(bundle, "url");
notification.message = getStringBundle(bundle, "message");
notification.image = getStringBundle(bundle, "image");
notification.imageLarge = getStringBundle(bundle, "image_large");
notification.type = getIntBundle(bundle, "type");
notification.notificationId = getIntBundle(bundle, "notification_id");
notification.notificationId = notification.notificationId == 0 ? new Random().nextInt() : notification.notificationId;
String jsonActions = getStringBundle(bundle, "actions");
if (!TextUtils.isEmpty(jsonActions)){
notification.actions = new Gson().fromJson(jsonActions, new TypeToken<List<Action>>(){}.getType());
}
return notification;
}
private static String getStringBundle(Bundle bundle, String name){
if (bundle.containsKey(name)){
return bundle.getString(name);
}
return null;
}
private static int getIntBundle(Bundle bundle, String name){
if (bundle.containsKey(name)){
return Integer.parseInt(bundle.getString(name));
}
return 0;
}
public static Notification fromJson(String json) {
Notification notification = new Gson().fromJson(json, Notification.class);
if (!TextUtils.isEmpty(notification.actionString)){
try {
JSONArray jsonArray = new JSONArray(notification.actionString);
notification.actions = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<Action>>(){}.getType());
} catch (JSONException e) {
e.printStackTrace();
}
}
notification.notificationId = notification.notificationId == 0 ? new Random().nextInt() : notification.notificationId;
return notification;
}
}
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
public class NotificationExampleListener implements NotificationListener {
@Override
public Intent openNavigator(Context context, String url) {
//TODO
return new Intent();
}
@Override
public Intent openActivity(Context context, String url) {
//TODO
return new Intent();
}
}
import android.content.Context;
import android.content.Intent;
public interface NotificationListener {
Intent openNavigator(Context context, String url);
Intent openActivity(Context context, String url);
}
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.Random;
public class NotificationManager {
private static android.app.NotificationManager notificationManager;
public static void createNotification(final Context context, Bundle bundle, NotificationListener notificationListener) {
final Notification notification = Notification.fromBundle(bundle);
String title = !TextUtils.isEmpty(notification.title) ? notification.title : context.getString(R.string.app_name);
PendingIntent pendingIntent = PendingIntent.getActivity(context, new Random().nextInt(), getIntentByType(notification.url, notification.getType(), notificationListener, context),
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = createSimpleNotification(context, notification.message, title);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder = createActions(notificationBuilder, notification, notificationListener);
if (!TextUtils.isEmpty(notification.image)) {
loadImageAndCreateNotification(notification.image, notification.imageLarge, notificationBuilder, notification.notificationId, false);
}else if(!TextUtils.isEmpty(notification.imageLarge)){
loadImageAndCreateNotification(null, notification.imageLarge, notificationBuilder, notification.notificationId, true);
}else{
getNotificationManager(notificationBuilder.mContext).notify(notification.notificationId, notificationBuilder.build());
}
}
private static void loadImageAndCreateNotification(final String image, final String imageLarge, final NotificationCompat.Builder notificationBuilder, final int notificationId, final boolean isImageLarge){
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Bitmap bitmap;
if (isImageLarge){
bitmap = Picasso.with(notificationBuilder.mContext).load(imageLarge).resize(400, 400).get();
}else{
bitmap = Picasso.with(notificationBuilder.mContext).load(image).resize(400, 400).transform(new CircleTransform()).get();
}
if (isImageLarge){
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap));
getNotificationManager(notificationBuilder.mContext).notify(notificationId, notificationBuilder.build());
}else{
notificationBuilder.setLargeIcon(bitmap);
if (!TextUtils.isEmpty(imageLarge)){
loadImageAndCreateNotification(null, imageLarge, notificationBuilder, notificationId, true);
}else{
getNotificationManager(notificationBuilder.mContext).notify(notificationId, notificationBuilder.build());
}
}
} catch (IOException e) {
e.printStackTrace();
if (!TextUtils.isEmpty(imageLarge) && !isImageLarge){
loadImageAndCreateNotification(null, imageLarge, notificationBuilder, notificationId, true);
}else{
getNotificationManager(notificationBuilder.mContext).notify(notificationId, notificationBuilder.build());
}
}
return null;
}
}.execute();
}
private static NotificationCompat.Builder createSimpleNotification(Context context, String message, String title){
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
return new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification_ico)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setSound(defaultSoundUri);
}
private static NotificationCompat.Builder createActions(NotificationCompat.Builder notificationBuilder, Notification notification, NotificationListener notificationListener){
if (notification.actions != null && !notification.actions.isEmpty()) {
for (Action action : notification.actions) {
PendingIntent pendingAction = PendingIntent.getActivity(notificationBuilder.mContext , 0, getIntentByType(action.url, action.getType(), notificationListener, notificationBuilder.mContext),
PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder = notificationBuilder.addAction(0, action.label, pendingAction);
}
}
return notificationBuilder;
}
private static android.app.NotificationManager getNotificationManager(Context context){
if (notificationManager == null){
notificationManager = (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
return notificationManager;
}
private static Intent getIntentByType(String url, Type type, NotificationListener notificationListener, Context context) {
if (TextUtils.isEmpty(url)){
return new Intent();
}
switch (type) {
case ACTIVITY:
return notificationListener.openActivity(context, url);
case NAVIGATOR:
return notificationListener.openNavigator(context, url);
default:
return new Intent();
}
}
}
public enum Type {
NAVIGATOR(0),
ACTIVITY(1);
public final int type;
Type(int type) {
this.type = type;
}
public static Type fromInt(int type) {
for (Type b : Type.values()) {
if (b.type == type) {
return b;
}
}
return Type.NAVIGATOR;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment