Last active
September 28, 2017 12:49
-
-
Save nillsondg/b88a55bd74018d088083358fbd255a05 to your computer and use it in GitHub Desktop.
GCM Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.evendate.android.gcm; | |
import android.app.NotificationManager; | |
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.Bundle; | |
import android.support.v4.app.NotificationCompat; | |
import android.util.Log; | |
import com.google.android.gms.gcm.GcmListenerService; | |
import com.squareup.picasso.Picasso; | |
import java.io.IOException; | |
import ru.evendate.android.EventDetailActivity; | |
import ru.evendate.android.R; | |
import ru.evendate.android.data.EvendateContract; | |
/** | |
* Created by Dmitry on 29.11.2015. | |
*/ | |
public class EvendateGCMListenerService extends GcmListenerService { | |
private static final String LOG_TAG = EvendateGCMListenerService.class.getSimpleName(); | |
private final String EVENT_ID = "event_id"; | |
private final String MESSAGE = "message"; | |
private final String ORGANIZATION_LOGO = "organization_logo"; | |
/** | |
* Called when message is received. | |
* | |
* @param from SenderID of the sender. | |
* @param data Data bundle containing message data as key/value pairs. | |
* For Set of keys use data.keySet(). | |
*/ | |
//{"data":{"message":"Testing long text:\nСияла призрачно луна,\nМерцаньем звёзд окружена. | |
// \nОставив крепость ту, Аврора\nСкорее поспешила к морю.","event_id":1211, | |
// "organization_logo":"http://evendate.ru/organizations_images/logos/small/1.png"},"to":"/topics/global"} | |
@Override | |
public void onMessageReceived(String from, Bundle data) { | |
String message = data.getString(MESSAGE); | |
int eventId = Integer.valueOf(data.getString(EVENT_ID)); | |
String orgLogoUrl = data.getString(ORGANIZATION_LOGO); | |
Log.d(LOG_TAG, "From: " + from); | |
Log.d(LOG_TAG, "Message: " + message); | |
if (from.startsWith("/topics/")) { | |
// message received from some topic. | |
} else { | |
// normal downstream message. | |
} | |
/** | |
* Production applications would usually process the message here. | |
* Eg: - Syncing with server. | |
* - Store message in local database. | |
* - Update UI. | |
*/ | |
/** | |
* In some cases it may be useful to show a notification indicating to the user | |
* that a message was received. | |
*/ | |
sendNotification(message, eventId, orgLogoUrl); | |
} | |
/** | |
* Create and show a simple notification containing the received GCM message. | |
* | |
* @param message GCM message received. | |
*/ | |
private void sendNotification(String message, int eventId, String logoUrl) { | |
Intent intent = new Intent(this, EventDetailActivity.class); | |
intent.setData(EvendateContract.EventEntry.getContentUri(eventId)); | |
//TODO local? | |
intent.putExtra(EventDetailActivity.IS_LOCAL, false); | |
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); | |
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, | |
PendingIntent.FLAG_ONE_SHOT); | |
//load icon | |
Bitmap logo; | |
try{ | |
logo = Picasso.with(getBaseContext()) | |
.load(logoUrl) | |
.error(R.drawable.default_background) | |
.get(); | |
}catch (IOException e){ | |
logo = null; | |
} | |
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); | |
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) | |
.setSmallIcon(R.drawable.ic_stat_ic_notification) | |
.setLargeIcon(logo) | |
.setContentTitle("Evendate") | |
.setContentText(message) | |
//just expand message to multi row | |
.setStyle(new NotificationCompat.BigTextStyle().bigText(message)) | |
.setAutoCancel(true) | |
.setSound(defaultSoundUri) | |
.setContentIntent(pendingIntent); | |
NotificationManager notificationManager = | |
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); | |
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.evendate.android.gcm; | |
import android.content.Intent; | |
import com.google.android.gms.iid.InstanceIDListenerService; | |
/** | |
* Created by Dmitry on 29.11.2015. | |
*/ | |
public class EvendateInstanceIDListener extends InstanceIDListenerService { | |
/** | |
* Called if InstanceID token is updated. This may occur if the security of | |
* the previous token had been compromised. This call is initiated by the | |
* InstanceID provider. | |
*/ | |
@Override | |
public void onTokenRefresh() { | |
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable). | |
Intent intent = new Intent(this, RegistrationGCMIntentService.class); | |
startService(intent); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.evendate.android.gcm; | |
import android.accounts.Account; | |
import android.accounts.AccountManager; | |
import android.accounts.AuthenticatorException; | |
import android.accounts.OperationCanceledException; | |
import android.app.IntentService; | |
import android.content.Intent; | |
import android.util.Log; | |
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 ru.evendate.android.R; | |
import ru.evendate.android.sync.EvendateApiFactory; | |
import ru.evendate.android.sync.EvendateService; | |
import ru.evendate.android.sync.EvendateSyncAdapter; | |
import ru.evendate.android.sync.ServerDataFetcher; | |
/** | |
* Created by Dmitry on 29.11.2015. | |
*/ | |
public class RegistrationGCMIntentService extends IntentService { | |
private static final String LOG_TAG = RegistrationGCMIntentService.class.getSimpleName(); | |
private static final String[] TOPICS = {"global"}; | |
public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; | |
public static final String REGISTRATION_COMPLETE = "registrationComplete"; | |
public RegistrationGCMIntentService() { | |
super(LOG_TAG); | |
} | |
@Override | |
protected void onHandleIntent(Intent intent) { | |
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); | |
try { | |
// [START register_for_gcm] | |
// Initially this call goes out to the network to retrieve the token, subsequent calls | |
// are local. | |
// R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json. | |
// See https://developers.google.com/cloud-messaging/android/start for details on this file. | |
// [START get_token] | |
InstanceID instanceID = InstanceID.getInstance(this); | |
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), | |
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); | |
// [END get_token] | |
Log.i(LOG_TAG, "GCM Registration Token: " + token); | |
// TODO: Implement this method to send any registration to your app's servers. | |
sendRegistrationToServer(token); | |
// Subscribe to topic channels | |
subscribeTopics(token); | |
// You should store a boolean that indicates whether the generated token has been | |
// sent to your server. If the boolean is false, send the token to your server, | |
// otherwise your server should have already received the token. | |
//sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply(); | |
Log.d(LOG_TAG, "GCM REGISTERED"); | |
// [END register_for_gcm] | |
} catch (Exception e) { | |
Log.d(LOG_TAG, "Failed to complete token refresh", e); | |
// If an exception happens while fetching the new token or updating our registration data | |
// on a third-party server, this ensures that we'll attempt the update at a later time. | |
//sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply(); | |
} | |
// Notify UI that registration has completed, so the progress indicator can be hidden. | |
//Intent registrationComplete = new Intent(REGISTRATION_COMPLETE); | |
//LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); | |
} | |
/** | |
* Persist registration to third-party servers. | |
* | |
* Modify this method to associate the user's GCM registration token with any server-side account | |
* maintained by your application. | |
* | |
* @param token The new token. | |
*/ | |
private void sendRegistrationToServer(String token) { | |
EvendateService evendateService = EvendateApiFactory.getEvendateService(); | |
Account account = EvendateSyncAdapter.getSyncAccount(getBaseContext()); | |
AccountManager accountManager = AccountManager.get(getBaseContext()); | |
try { | |
String authToken = accountManager.blockingGetAuthToken(account, getBaseContext().getString(R.string.account_type), false); | |
ServerDataFetcher.putDeviceToken(evendateService, authToken, token); | |
}catch (IOException|OperationCanceledException|AuthenticatorException e){ | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* Subscribe to any GCM topics of interest, as defined by the TOPICS constant. | |
* | |
* @param token GCM token | |
* @throws IOException if unable to reach the GCM PubSub service | |
*/ | |
// [START subscribe_topics] | |
private void subscribeTopics(String token) throws IOException { | |
GcmPubSub pubSub = GcmPubSub.getInstance(this); | |
for (String topic : TOPICS) { | |
pubSub.subscribe(token, "/topics/" + topic, null); | |
} | |
} | |
// [END subscribe_topics] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment