Java tutorial
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.alerts.receiver; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.liferay.alerts.activity.MainActivity; import com.liferay.alerts.database.AlertDAO; import com.liferay.alerts.database.DatabaseException; import com.liferay.alerts.database.UserDAO; import com.liferay.alerts.model.Alert; import com.liferay.alerts.model.User; import com.liferay.alerts.util.GCMUtil; import com.liferay.alerts.util.NotificationUtil; import org.json.JSONException; import org.json.JSONObject; /** * @author Bruno Farache */ public class PushNotificationIntentService extends IntentService { public PushNotificationIntentService() { super(PushNotificationIntentService.class.getSimpleName()); } @Override protected void onHandleIntent(Intent intent) { GoogleCloudMessaging gcm = GCMUtil.getGoogleCloudMessaging(this); String type = gcm.getMessageType(intent); Bundle extras = intent.getExtras(); if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(type) && !extras.isEmpty()) { try { long parentPushNotificationsEntryId = Long .parseLong(extras.getString(Alert.PARENT_PUSH_NOTIFICATIONS_ENTRY_ID)); if (parentPushNotificationsEntryId != 0) { return; } long id = Long.parseLong(extras.getString(Alert.PUSH_NOTIFICATIONS_ENTRY_ID)); JSONObject userJSONObject = new JSONObject(extras.getString(Alert.USER)); User user = new User(userJSONObject); JSONObject payload = new JSONObject(extras.getString(Alert.PAYLOAD)); Alert alert = new Alert(id, user, payload); _insert(user, alert); NotificationUtil.notifyUnreadAlerts(this); MainActivity.addCard(this, alert); } catch (JSONException je) { Log.e(_TAG, "Couldn't parse alert JSON.", je); } finally { PushNotificationReceiver.completeWakefulIntent(intent); } } } private void _insert(User user, Alert alert) { try { UserDAO userDAO = UserDAO.getInstance(this); User existingUser = userDAO.get(user.getId()); if (existingUser == null) { userDAO.insert(user); } AlertDAO.getInstance(this).insert(alert); } catch (DatabaseException de) { Log.e(_TAG, "Couldn't insert user or alert.", de); } } private static final String _TAG = PushNotificationIntentService.class.getSimpleName(); }