Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Push Notifications (Android)
Started by chinmay5 Jun 07 2013 03:52 AM

* * * * * 1 votes
10 replies to this topic
push notifications custom notification android notification handle notification corona android gcm push notification notification custom messages
[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

chinmay5

[GLOBAL: userInfoPane.html]
chinmay5
  • Observer

  • 21 posts
  • Corona SDK

Hi,

 

Is there any way to add custom messages in push notifications in android via corona SDK.

 

Currently i am able to send push notification to other devices but i am unable to add any custom messages (like notification details) in my push notifications .

 

When i send the notification to other devices, it shows my app name along with a triangle and exclamatory sign in it.

 

Any help is highly appreciated.



[TOPIC: post.html]
#2

Gooner87

[GLOBAL: userInfoPane.html]
Gooner87
  • Contributor

  • 161 posts
  • Corona SDK

Hi chinmay5 ,

 

Are you using the googlePushNotification sample code?

 

	local jsonMessage =
		[[
		{
			"registration_ids": ["]] .. tostring(playerDeviceID) .. [["],
			"data":
			{
				"alert": "Do you want to play?",
				"sound": "notification.wav",
				"custom":
				{
					"boolean": true,
					"number": 123.456,
					"string": "Custom data test.",
					"array": [ true, false, 0, 1, "", "This is a test." ],
					"table": { "x": 1, "y": 2 }
				}
			}
		}
		]]
			sendNotification(jsonMessage)
	end

This is the json that is sent, if you're asking how to access the custom data when the notification is received, I would like to know too. 

 

You say you just get your app name and the alert icon, but there should also be a message. The message from the sample app should say hello world.



[TOPIC: post.html]
#3

chinmay5

[GLOBAL: userInfoPane.html]
chinmay5
  • Observer

  • 21 posts
  • Corona SDK

Hi,

 

I am using the same code, but the notification is same app name along with a triangle and exclamatory sign in it. Also it is showing an error. Please find attached a screenshot of the error displayed.

notification error.png
 

 



[TOPIC: post.html]
#4

Gooner87

[GLOBAL: userInfoPane.html]
Gooner87
  • Contributor

  • 161 posts
  • Corona SDK

I am using the code from sample app but I am not getting that error, I don't know maybe maybe it is something you missed setting up GCM? What build are you using? I am using build 1095



[TOPIC: post.html]
#5

chinmay5

[GLOBAL: userInfoPane.html]
chinmay5
  • Observer

  • 21 posts
  • Corona SDK

I follow these steps.

http://www.coronalabs.com/blog/2012/12/25/corona-holiday-gifts-android-push-and-more/

 

I dont know where I am lacking. I am using version 2013.1076 and I also tested it on 2012.1135 but the notification error is same. It seems that there is some error in the json message format we are sending.



[TOPIC: post.html]
#6

chinmay5

[GLOBAL: userInfoPane.html]
chinmay5
  • Observer

  • 21 posts
  • Corona SDK

Can anyone please help me in resolving the issue? I am not at all able to send any push notification on my android phone.



[TOPIC: post.html]
#7

jonjonsson

[GLOBAL: userInfoPane.html]
jonjonsson
  • Corona Geek

  • 1,051 posts
  • Corona SDK

Try to simplify the message a bit and see if it makes any difference. Paste your device ID in there, just to see if it works.

 

jsonMessage = '{"data":{"alert":"test message"}, "registration_ids":["****DEVICEID****"]}'

 

Any joy? Not very optimistic that it changes anything since I tried that sample app few days ago and didn't have to do anything except put my API key in there and it worked.

 

Also print out your json to console. Make sure you have your device ID in it and then validate it with http://jsonlint.com/ to make sure its good.



[TOPIC: post.html]
#8

chinmay5

[GLOBAL: userInfoPane.html]
chinmay5
  • Observer

  • 21 posts
  • Corona SDK

Hi jonjonsson,

 

Thanks for your reply, it worked. Finally push notifications are working on my android phone :).

But still there is a problem with the icon of the notification, it is showing a triangle with exclamation mark in it. Do we have to add any icon for google notifications in the app so that the app icon will appear in push notifications?

 

Attached Thumbnails

  • Screenshot_2013-06-12-13-48-23.png


[TOPIC: post.html]
#9

jonjonsson

[GLOBAL: userInfoPane.html]
jonjonsson
  • Corona Geek

  • 1,051 posts
  • Corona SDK

Good to hear. There are a few posts about the triangle icon. Here is one: http://developer.coronalabs.com/forum/2012/12/05/custom-icon-local-notifications-android



[TOPIC: post.html]
#10

chinmay5

[GLOBAL: userInfoPane.html]
chinmay5
  • Observer

  • 21 posts
  • Corona SDK

Thanks again jonjjosson. It worked for me again :).

 



[TOPIC: post.html]
#11

jalemanyf

[GLOBAL: userInfoPane.html]
jalemanyf
  • Enthusiast

  • 71 posts
  • Corona SDK

I have got the same problem with the sample code... Please, could you tell me how do you solved it? Thanks in advance!

 

Regards,

 

Josep Alemany

 

My code is the same of the sample:

 

-- Project: GooglePushNotifications
--
-- File name: main.lua
--
-- Author: Corona Labs Inc.
--
-- This sample app demonstrates how to send and receive push notifications via the
-- Google Cloud Messaging service (aka: GCM).
-- See the "build.settings" file to see what Android permissions are required.
-- See the "config.lua" file on how to register for push notifications with Google.
-- See the following website on how to set up your app for Google's push notification system.
--
-- Limitations: This sample app only works on an Android device with "Google Play" installed.
--
-- Sample code is MIT licensed, see http://www.coronalabs.com/links/code/license
-- Copyright © 2012 Corona Labs Inc. All Rights Reserved.
--
--    Supports Graphics 2.0
---------------------------------------------------------------------------------------
 
local centerX = display.contentCenterX
local centerY = display.contentCenterY
local _W = display.contentWidth
local _H = display.contentHeight
 
-- A Google API Key is needed to send push notifications. It is not needed to receive notifications.
-- This key can be obtained from the Google API Console here:  https://code.google.com/apis/console
local googleApiKey = "*************"   -- NOTE: Here I have done the steps and I have the ApiKey from Google console.
 
-- A Google registration ID is also needed to send push notifications.
-- This key will be obtained by the notification listener below after this app has successfully
-- registered with Google. See the "config.lua" file on how to register this app with Google.
local googleRegistrationId = "************"   -- NOTE2: The same here, I have the Id and I have changed it on the conflig.lua
 
 
-- Show the status bar so that we can easily access the received notifications.
display.setStatusBar(display.DefaultStatusBar)
 
-- Set up the background.
local background = display.newRect(centerX, centerY, display.contentWidth, display.contentHeight)
background:setFillColor(0.5, 0, 0)
 
-- Display instructions.
local message = "Tap the screen to push a notification"
local textField = display.newText(message, 0, centerY, native.systemFont, 18)
textField:setFillColor(1, 1, 1)
textField.x = centerX
 
 
-- Called when a sent notification has succeeded or failed.
local function onSendNotification(event)
    local errorMessage = nil
 
    -- Determine if we have successfully sent the notification to Google's server.
    if event.isError then
        -- Failed to connect to the server.
        -- This typically happens due to lack of Internet access.
        errorMessage = "Failed to connect to the server."
 
    elseif event.status == 200 then
        -- A status code of 200 means that the notification was sent succcessfully.
        print("Notification was sent successfully.")
 
    elseif event.status == 400 then
        -- There was an error in the sent notification's JSON data.
        errorMessage = event.response
 
    elseif event.status == 401 then
        -- There was a user authentication error.
        errorMessage = "Failed to authenticate the sender's Google Play account."
 
    elseif (event.status >= 500) and (event.status <= 599) then
        -- The Google Cloud Messaging server failed to process the given notification.
        -- This indicates an internal error on the server side or the server is temporarily unavailable.
        -- In this case, we are supposed to silently fail and try again later.
        errorMessage = "Server failed to process the request. Please try again later."
    end
 
    -- Display an error message if there was a failure.
    if errorMessage then
        native.showAlert("Notification Error", errorMessage, { "OK" })
    end
end
 
-- Sends the given JSON message to the Google Cloud Messaging server to be pushed to Android devices.
local function sendNotification(jsonMessage)
    -- Do not continue if a Google API Key was not provided.
    if not googleApiKey then
        return
    end
 
    -- Print the JSON message to the log.
    print("--- Sending Notification ----")
    print(jsonMessage)
 
    -- Send the push notification to this app.
    local parameters =
    {
        headers =
        {
            ["Authorization"] = "key=" .. googleApiKey,
            ["Content-Type"] = "application/json",
        },
        body = jsonMessage,
    }
    network.request(url, "POST", onSendNotification, parameters)
end
 
-- Sends a push notification when the screen has been tapped.
local function onTap(event)
    -- Do not continue if this app has not been registered for push notifications yet.
    if not googleRegistrationId then
        return
    end
 
    -- Set up a JSON message to send a push notification to this app.
    -- The "registration_ids" tells Google to whom this push notification should be delivered to.
    -- The "alert" field sets the message to be displayed when the notification has been received.
    -- The "sound" field is optional and will play a sound file in the app's ResourceDirectory.
    -- The "custom" field is optional and will be delivered by the notification event's "event.custom" property.
    local jsonMessage =
[[
{
    "registration_ids": ["]] .. tostring(googleRegistrationId) .. [["],
    "data":
    {
        "alert": "Hello World!",
        "sound": "notification.wav",
        "custom":
        {
            "boolean": true,
            "number": 123.456,
            "string": "Custom data test.",
            "array": [ true, false, 0, 1, "", "This is a test." ],
            "table": { "x": 1, "y": 2 }
        }
    }
}
]]
    sendNotification(jsonMessage)
end
Runtime:addEventListener("tap", onTap)
 
-- Prints all contents of a Lua table to the log.
local function printTable(table, stringPrefix)
    if not stringPrefix then
        stringPrefix = "### "
    end
    if type(table) == "table" then
        for key, value in pairs(table) do
            if type(value) == "table" then
                print(stringPrefix .. tostring(key))
                print(stringPrefix .. "{")
                printTable(value, stringPrefix .. "   ")
                print(stringPrefix .. "}")
            else
                print(stringPrefix .. tostring(key) .. ": " .. tostring(value))
            end
        end
    end
end
 
-- Called when a notification event has been received.
local function onNotification(event)
    if event.type == "remoteRegistration" then
        -- This device has just been registered for Google Cloud Messaging (GCM) push notifications.
        -- Store the Registration ID that was assigned to this application by Google.
        googleRegistrationId = event.token
 
        -- Display a message indicating that registration was successful.
        local message = "This app has successfully registered for Google push notifications."
        native.showAlert("Information", message, { "OK" })
 
        -- Print the registration event to the log.
        print("### --- Registration Event ---")
        printTable(event)
 
    else
        -- A push notification has just been received. Print it to the log.
        print("### --- Notification Event ---")
        printTable(event)
    end
end
 
-- Set up a notification listener.
Runtime:addEventListener("notification", onNotification)
 
-- Print this app's launch arguments to the log.
-- This allows you to view what these arguments provide when this app is started by tapping a notification.
local launchArgs = ...
print("### --- Launch Arguments ---")
printTable(launchArgs)



[topic_controls]
[/topic_controls]