com.playtech.ezpush.gcm.GcmIntentService.java Source code

Java tutorial

Introduction

Here is the source code for com.playtech.ezpush.gcm.GcmIntentService.java

Source

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.playtech.ezpush.gcm;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.playtech.ezpush.MainActivity;
import com.playtech.ezpush.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * This {@code IntentService} does the actual handling of the GCM message.
 * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 */
public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private static String[] excludes = new String[] { "from", "collapse_key", "android_header", "android_sound",
            "android.support.content.wakelockid", "message" };
    public static final String ACTION_NOTIFICATION_CLICK = "com.playtech.luck.c2dm.ACTION_NOTIFICATION_CLICK";
    public static final String ACTION_OPEN_NOTIFICATION = "com.playtech.luck.c2dm.ACTION_OPEN_NOTIFICATION";
    public static final String NOTIFICATION_TITLE = "EzPush";
    public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";

    public static final String EXTRA_MESSAGE = "message";
    public static final String EXTRA_SOUND = "android_sound"; // url to android sound here
    public static final String EXTRA_HEADER = "android_header"; //android header here
    public static final String EXTRA_ICON = "android_icon"; //url to android icon here
    public static final String EXTRA_CUSTOM_ICON = "android_custom_icon"; //url to android custom icon here
    public static final String EXTRA_BANNER = "android_banner"; //url to android banner here

    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;

    public GcmIntentService() {
        super("GcmIntentService");
    }

    public static final String TAG = "GCM Demo";

    private boolean containsKey(String s) {
        for (String option : excludes) {
            if (option.equals(s))
                return true;
        }
        return false;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) { // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM will be
             * extended in the future with new message types, just ignore any message types you're
             * not interested in, or that you don't recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString());
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i = 0; i < 5; i++) {
                    Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                showNotification(extras);

                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("GCM Notification").setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);

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

    }

    private void showNotification(Bundle extras) {

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);

        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(this.NOTIFICATION_SERVICE);
        CharSequence message = extras.getString(EXTRA_MESSAGE);
        intent.putExtra(NOTIFICATION_MESSAGE, message);

        CharSequence title = extras.getString(EXTRA_HEADER);
        if (title == null)
            title = NOTIFICATION_TITLE;

        String aid = extras.getString("application_id");
        intent.putExtra("APP_ID", aid);

        String nid = extras.getString("nid");
        intent.putExtra("NOTIFICATION_ID", nid);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        Notification.InboxStyle style = new Notification.InboxStyle();
        style.addLine(message);

        for (String s : extras.keySet()) {
            if (!containsKey(s)) {
                style.addLine(s + ":" + extras.getString(s));
            }
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(this, intent.hashCode(), intent,
                PendingIntent.FLAG_ONE_SHOT);
        Notification.Builder nb = new Notification.Builder(this).setContentTitle(title).setContentText(message)
                .setSmallIcon(R.mipmap.ezpush_logo)
                .setLargeIcon(loadBitmap("http://ursynoteka.pl/wp-content/uploads/2012/04/message_new.png"))
                .setStyle(style).setContentIntent(pendingIntent).setAutoCancel(true);

        if (extras.containsKey(EXTRA_SOUND)) {
            nb.setSound(Uri.parse(extras.getString(EXTRA_SOUND)));
        }
        if (extras.containsKey(EXTRA_BANNER)) {
            Bitmap bitmap = loadBitmap(extras.getString(EXTRA_BANNER));
            if (bitmap != null) {
                NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                        .setBigContentTitle(NOTIFICATION_TITLE).setSummaryText(message).bigPicture(bitmap);
            }
        }
        if (extras.containsKey(EXTRA_ICON)) {
            String iconUrl = extras.getString(EXTRA_ICON);
            Bitmap bitmap = loadBitmap(iconUrl);
            if (bitmap != null) {
                nb.setLargeIcon(bitmap);
            }
        }

        Notification notification = nb.build();

        notificationManager.notify(notification.hashCode(), notification);
    }

    private Bitmap loadBitmap(String imageUrl) {
        Bitmap bitmap;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(input);
        } catch (IOException e) {
            bitmap = null;
        }
        return bitmap;
    }

    private static boolean excludeKey(String s) {
        String[] excludes = new String[] { "from", "android_header", "android.support.content.wakelockid",
                "message" };
        for (String option : excludes) {
            if (option.equals(s))
                return true;
        }
        return false;
    }
}