Gilad Neiger
Gilad Neiger

Reputation: 643

What to write in MyGCMListenerService?

I'm trying to add GCM to my new application with this guide: https://developers.google.com/cloud-messaging/android/client#manifest

When I add these lines to my Manifest, It errors and do not recognize the lines android:name="com.example.MyGcmListenerService" android:name="com.example.MyInstanceIDListenerService"

yes, I've changed the com.example to my project details.

 <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.gcm" />
        </intent-filter>
    </receiver>
    <service
        android:name="com.example.MyGcmListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>
    <service
        android:name="com.example.MyInstanceIDListenerService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID" />
        </intent-filter>
    </service>

As i read, I have to create my own Java Class for MyGcmListenerService and for MyInstanceIDListenerService, but I have no idea what to write in it?

I got really confused about all this GCM stuff.

Upvotes: 2

Views: 782

Answers (3)

Kushal
Kushal

Reputation: 805

Step 1. Make GCM Utility Class

import android.content.Context;
import android.content.Intent;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;

public class GCMUtils
{
    static String TAG               =   "GCM";
    static int NOTIFICATION_ID      =   99;
    public static String SENDER_ID  =   "YOUR SENDER ID";
    Context context;

    public GCMUtils(Context context)
    {
        this.context = context;

        if (checkPlayServices())
        {
            Intent intent = new Intent(context, RegisterDeviceService.class);
            context.startService(intent);
        }
    }

    private boolean checkPlayServices()
    {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS)
        {
            return false;
        }
        return true;
    }
}

Step 2. Make Register Device Class

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

public class RegisterDeviceService extends IntentService
{

    public RegisterDeviceService() {
        super(GCMUtils.TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        try
        {
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(GCMUtils.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.i(GCMUtils.TAG, "GCM Registration Token: " + token);

        }
        catch (Exception e)
        {
            Log.d(GCMUtils.TAG, "Failed to complete token refresh", e);
        }
    }
}

Step 3 . Make Instance ID Service

import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;

public class InstanceIdService extends InstanceIDListenerService
{
    @Override
    public void onTokenRefresh()
    {
        Intent intent = new Intent(this, RegisterDeviceService.class);
        startService(intent);
    }
}

Step 4. Make GCMListenerService

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;

public class GCMmessageListener extends GcmListenerService
{
    @Override
    public void onMessageReceived(String from, Bundle data)
    {

        String message = data.getString("price");
        Log.d(GCMUtils.TAG, "From: " + from);
        Log.d(GCMUtils.TAG, "Message: " + data);

        sendNotification(message);
    }
    private void sendNotification(String message)
    {
        Intent intent = new Intent(this, HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, GCMUtils.NOTIFICATION_ID /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(getNotificationIcon())
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(message).setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(GCMUtils.NOTIFICATION_ID /* ID of notification */, notificationBuilder.build());
    }

    private int getNotificationIcon()
    {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.icon_lolipop : R.drawable.icon;
    }
}

Step 5 Add this to your Mainefest

Add these permission

        <uses-permission android:name="com.dspl.keyvendors.permission.C2D_MESSAGE" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

and register these Receiver and Services

<receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="YOUR PACKAGE NAME" />
            </intent-filter>
        </receiver>
        <service
            android:name=".gcm.RegisterDeviceService"
            android:exported="false">
        </service>
        <service
            android:name=".gcm.InstanceIdService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>
        <service
            android:name=".gcm.GCMmessageListener"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

Hope this will help you out...

Upvotes: 1

Raghav Satyadev
Raghav Satyadev

Reputation: 748

MyGcmListenerService.java

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.google.android.gms.gcm.GcmListenerService;

public class MyGcmListenerService extends GcmListenerService {

    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;
    private Uri defaultSoundUri;

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onMessageReceived(String from, Bundle data) {

        String message = data.getString("message");

        if (from.startsWith("/topics/")) {
            String topic = from.replace("/topics/", "");
            try {
                if (new SharedPreferencesHelper(this).getGCMTopics().contains(topic)) {
                    sendNotification(message, 0);
                }
            } catch (NullPointerException ignored) {

            }
        } else {
            if (message != null) {
                switch (message) {
                    case "0":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.WHOLE_UPDATE)
                                .putExtra(Constants.CLEAR_UPDATE, true));
                        break;
                    case "1":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.BOOKING_UPDATE));
                        sendNotification(Constants.BOOKING_NOTIFY, Integer.parseInt(message));
                        break;
                    case "2":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.PACKAGE_UPDATE));
                        break;
                    case "3":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.LOCATION_UPDATE));
                        break;
                    case "4":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.MEETING_UPDATE));
                        sendNotification(Constants.MEETING_NOTIFY, Integer.parseInt(message));
                        break;
                    case "5":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.MANAGER_UPDATE));
                        break;
                    case "6":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.USER_UPDATE));
                        break;
                    case "7":
                        startService(new Intent(this, BackgroundUpdateService.class)
                                .putExtra(Constants.UPDATE, Constants.WHOLE_UPDATE));
                        break;
                    default:
                        sendNotification(message, 0);
                        break;
                }
            }

        }
    }

    private void sendNotification(String message, int i) {
        Intent intent = new Intent(this, ActivityDrawer.class).putExtra(Constants.CLEAR_NOTIFICATION, true);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Context context = this;
        SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper(context);

        notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Book That!")
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentText(message)
                .setContentIntent(pendingIntent);
        int notificationNumber;
        if (i == 1) {
            notificationNumber = sharedPreferencesHelper.getBookingNotificationNumber();

            sharedPreferencesHelper.setBookingNotificationNumber(++notificationNumber);
        } else if (i == 4) {
            notificationNumber = sharedPreferencesHelper.getMeetingNotificationNumber();

            sharedPreferencesHelper.setMeetingNotificationNumber(++notificationNumber);
        } else {
            notificationNumber = sharedPreferencesHelper.getNotificationNumber();

            sharedPreferencesHelper.setNotificationNumber(++notificationNumber);
        }
        notificationBuilder.setNumber(notificationNumber - 1);
        notificationManager.notify(i, notificationBuilder.build());
    }
}

MyInstanceIDListenerService.java

import android.content.Intent;

import com.google.android.gms.iid.InstanceIDListenerService;

public class MyInstanceIDListenerService extends InstanceIDListenerService {
    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}

RegistrationIntentService.java

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

import java.io.IOException;
import java.util.TreeSet;

public class RegistrationIntentService extends IntentService {


    Intent registrationComplete;
    private SharedPreferencesHelper sharedPreferencesHelper;

    public RegistrationIntentService() {
        super("TokenRegistration");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        sharedPreferencesHelper = new SharedPreferencesHelper(this);

        registrationComplete = new Intent(GCMConstants.REGISTRATION_COMPLETE);

        InstanceID instanceID = InstanceID.getInstance(this);

        try {
            String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

            sharedPreferencesHelper.setGCMID(token);

            subscribeTopics(token);

            sharedPreferencesHelper.tokenStatus(true);
        } catch (IOException e) {
            if (e.getMessage().equals("SERVICE_NOT_AVAILABLE")) {
                registrationComplete.putExtra("Error", Constants.NO_INTERNET);
            }
            sharedPreferencesHelper.tokenStatus(false);
        }

        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void subscribeTopics(String token) throws IOException {
        TreeSet<String> TOPICS = new TreeSet<>();

        TOPICS.add("BookThatUpdates");

        sharedPreferencesHelper.setGCMTopics(TOPICS);

        GcmPubSub pubSub = GcmPubSub.getInstance(this);
        for (String topic : TOPICS) {
            pubSub.subscribe(token, "/topics/" + topic, null);
        }
    }
}

GCMConstants.java

public class GCMConstants {
    public static final String TOKEN_SAVED_IN_PREFERENCES = "tokenSavedInPreferences";
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String TOKEN = "Token";
    public static final String TOPICS = "Topics";
}

If anything is missing please tell in comments.

Upvotes: 0

Mustanser Iqbal
Mustanser Iqbal

Reputation: 5097

this is what you need to write in MyGcmListenerService

public class MyGcmListenerService extends GcmListenerService {

    private static final String TAG = "MyGcmListenerService";


    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        Log.e(TAG, "From: " + from);
        Log.e(TAG, "Message: " + message);
       sendNotification(message );

    }

    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.logo)
                .setContentTitle("Sorry!!")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0, notificationBuilder.build());
    }

this service will listen for GCM messages. and when a message will receive then onMessageReceived will trigger and then its your responsibility to handle the GCM Message. you generate any notification or what ever you want.

Upvotes: 1

Related Questions