/*
* Copyright 2014-2015 GameUp
*
* 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 io.gameup.android.push;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/**
* Processes the incoming notification data and may generate a notification or
* trigger a background broadcast.
*/
public class NotificationBundleProcessor {
/**
* Process incoming GCM message data. This will send a background broadcast
* and/or create and display a notification, based on the incoming message
* contents.
*
* @param context The receiver context.
* @param bundle The incoming bundle data.
*/
public static void process(final Context context, final Bundle bundle) {
if (Push.isValidAndNotDuplicated(context, bundle)) {
prepareBundle(bundle);
// If the background flag is set, send a background broadcast.
if (bundle.containsKey("bgn") &&
"1".equals(bundle.getString("bgn"))) {
final Intent intent = new Intent();
intent.setAction(
"io.gameup.android.push.BackgroundBroadcast.RECEIVE");
intent.setPackage(context.getPackageName());
intent.putExtra("data", bundle);
context.sendBroadcast(intent);
}
// If there is no alert data, skip the notification.
if (!bundle.containsKey("alert") ||
bundle.getString("alert") == null ||
bundle.getString("alert").equals("")) {
return;
}
GenerateNotification.fromBundle(context, bundle);
}
}
// Format short keys into more readable ones.
private static void prepareBundle(final Bundle gcmBundle) {
if (gcmBundle.containsKey("o")) {
try {
final JSONObject customJSON = new JSONObject(
gcmBundle.getString("custom"));
JSONObject additionalDataJSON;
if (customJSON.has("a")) {
additionalDataJSON = customJSON.getJSONObject("a");
}
else {
additionalDataJSON = new JSONObject();
}
if (!customJSON.has("a")) {
customJSON.put("a", additionalDataJSON);
}
gcmBundle.putString("custom", customJSON.toString());
} catch (final JSONException e) {
e.printStackTrace();
}
}
}
}