Android Tutorial Android push notification (GCM) framework and tutorial

Discussion in 'Tutorials & Examples' started by Erel, Jul 3, 2012.

  1. marcick

    marcick Well-Known Member Licensed User

    I'll start this way and see.
    I wish you a happy new year ! :sign0008:
     
  2. marcick

    marcick Well-Known Member Licensed User

    As I suspected ... this service does not suit my needings.
    I did a test sending one message every 15 seconds, but after 20 message or so, they stop be delivered.
    It is not very clear to me how it is managed but is explained in "Throttling message chapter" (I cut and paste before the text).
    I need to find another method that does not put any kind of limit because I need realtime communication.
    If anybody else wants to do some other test or have any idea ...
    Marco
     
  3. Valounours

    Valounours Member Licensed User

    Hello,

    It's possible to send all device in one time with cmd ?

    Thank's

    Valounours

    P.S : I'm french sorry for my english.:sign0013:
     
  4. Erel

    Erel Administrator Staff Member Licensed User

    You will need to create a small script that calls -GetAll and then sends a message to each device (I think that someone has created such a batch file and posted it in the forum).
     
  5. touchring

    touchring New Member

    I'm considering using Basic4Android and GCM. Is it possible to bring the application (for both stopped and running state) to the foreground automatically without the user clicking on the push notification?

    Also, it is possible to know if and also when a message has been delivered to the phone?

    Thank you.
     
    Last edited: Jan 8, 2013
  6. Erel

    Erel Administrator Staff Member Licensed User

    Yes. The service will start automatically when a message arrives. You can then call StartActivity to show an activity.

    The desktop tool returns Success if the device id is correctly registered and the message was process correctly. If the device is turned off or not available then GCM service will try to send it later. You can set the time_to_live to 0 and then the message will either be sent immediately or fail.
     
  7. touchring

    touchring New Member


    Hi Erel, thank you for your reply.
     
  8. mading1309

    mading1309 Member Licensed User

    Free MySQL service www.000webhost.com/

    Hi

    Thanks to Erl for this tutorial

    I was successful using the MQSQL database on the B4A server
    When I switched to the free Hosting Free Web Hosting with PHP, MySQL and cPanel, No Ads for MySQL service the Push service does not run.

    After some checks and thanks for the JAVA Source, I found out that an ECHO command of the PHP script are some lines attached containing HTML code calling a javascript

    APA91bFIF6d_6hPEEKHcYtGbDQqi- ... O9n8xZ9mg
    <!-- Hosting24 Analytics Code -->
    <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
    <!-- End Of Analytics Code -->

    The first line is the registration ID, the following lines must be removed that the Push service works again.

    I modified the JAVA desktop application
    In the method call of object RequestResult I add at the end before return the result the following code to remove the Hosting24 attachment

    // In case some free providers add java script call
    // for echo or print commands in PHP
    // use only 1st line for ID
    if (rr.text.length()>0) {
    t=rr.text.split("\n");
    rr.text = t[0];
    }

    With this changes of the JAVA application the PUSH services works also with the free hosting service of Free Web Hosting with PHP, MySQL and cPanel, No Ads

    I attached my modified JAVA application
     

    Attached Files:

  9. kanaida

    kanaida Active Member Licensed User

    Hey guys, I got the sample working pretty quickly. Works great. I'm just wondering exactly how this registration thing works... I mean what's the deal with the name?

    What I wanted to do was have 2 buttons. 1 to register automatically using the phone/tablet's unique Id. Then link all the devices to the user by grouping them all by the Gmail address of the user. After that the application would never be manually opened by the user ever again unless he wanted to disconnect his device from the service. (pretty much how chrome2phone works). I'm just not exactly sure how I would do that. To start I tried moving all the code to the service module, but I got compile errors that didn't make sense for things like:

    If Register Then <- A compile error here saying it's expecting a '('

    ....

    End If

    Nothing that really made sense. Maybe it's related to using B4A 2.5, not sure.
     
  10. Erel

    Erel Administrator Staff Member Licensed User

    Can you post the full service code?
     
  11. Brookalino

    Brookalino Member Licensed User

    Hi mading1309

    I am getting the same error that you got above : Push Service does not run.
    I created a new database on the Free Web Hosting with PHP, MySQL and cPanel, No Ads as above..
    But I'm confused.. where does the modified C2DM.java file go?

    This is where i am at..
    I ran the original PushExample and everything worked fine..
    Registered names, sent messages, received messages... no problem.


    I then modified the PushExample with my server info, my API info, passwords etc..
    I run the modified example and i can register names etc...
    (I checked my server database and they are there)

    I run the cmd prompt... 'b4a_gcm.bat getall ' and i can see the names that are registered...


    I then try to send a message and keep getting the error :

    [​IMG]

    I have looked everywhere for a solution and it's driving me up the wall!! :BangHead::BangHead::BangHead:

    Any help would be greatly appreciated..

    Thanks

    Brookalino
     
  12. Brookalino

    Brookalino Member Licensed User

    Just wanted to reply to the above post.
    I searched high and low for the solution to my problem with no luck.

    I then used a different webhost and everything worked fine.:D
     
  13. mading1309

    mading1309 Member Licensed User

    Hi Brookalino

    I am just back from Malaysia trip
    Sorry for the delayed reply
    During the day I'll check your error
     
  14. Brookalino

    Brookalino Member Licensed User

    Thanks mading..
    As you may have noticed from the above post i just used a new webhost and everything worked as intended.

    I'm now stuck on how to send a message from App to APP without using the b4a_gcm.bat file.

    If you have any suggestions or ideas, it would be appreciated very much.

    Oh.. and i hope you enjoyed Malaysia!! :)

    :cool:
     
  15. spyboy79

    spyboy79 Member Licensed User

    Hi,
    first of all sorry for my english! :sign0188:

    thanks for this great library, is wonderful!
    I've integrated GCM functions in my app but there is a problem (tested with Android S1 2.3.6 and S3 4.1.2, the same problem)

    I run my app by icon and with app open or closed by home key or by function "Activity.Finish", pushs works well.

    But if I reboot phone or, with app closed, the system kill the not used app, then I have a crash when a push is sent from server.

    Log from phone after crash say this:

    java.lang.RuntimeException: Unable to create service movida.x3.pushservice: java.lang.RuntimeException: java.lang.NullPointerException
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:1959)
    at android.app.ActivityThread.access$2500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:989)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3687)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.RuntimeException: java.lang.NullPointerException
    at movida.x3.main.initializeProcessGlobals(main.java:692)
    at movida.x3.pushservice.onCreate(pushservice.java:30)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:1949)
    ... 10 more
    Caused by: java.lang.NullPointerException
    at movida.x3.main._process_globals(main.java:1175)
    at movida.x3.main.initializeProcessGlobals(main.java:680)
    ... 12 more


    The problem is the same if I force app close with app manager.

    For a test, I also set "start at boot" the pushservice module but something go crash at the phone reboot.

    what is wrong?

    PS: the pushservice code:

    Code:
    'Service module
    'Version 0.9
    Sub Process_Globals
       
    Private hc As HttpClient
       
    Private hcInit As Boolean
       hcInit = 
    False
       
    Private RegisterTask, UnregisterTask As Int
       RegisterTask = 
    1
       UnregisterTask = 
    2
       
    Private Num_notify As Int
       Num_notify=
    0
    End Sub

    Sub Service_Create
       
    If hcInit = False Then
          hc.Initialize(
    "hc")
          hcInit = 
    True
       
    End If      
    End Sub

    Sub Service_Start (StartingIntent As Intent)
       
    Select StartingIntent.Action
          
    Case "com.google.android.c2dm.intent.REGISTRATION"
             HandleRegistrationResult(StartingIntent)
          
    Case "com.google.android.c2dm.intent.RECEIVE"
             MessageArrived(StartingIntent)
       
    End Select
    End Sub

    Sub MessageArrived (Intent As Intent)
       
    Dim From, CollapseKey, Data, Msg As String
       
    If Intent.HasExtra("from"Then From = Intent.GetExtra("from")
       
    If Intent.HasExtra("data"Then Data = Intent.GetExtra("data")
       
    If Intent.HasExtra("msg"Then Msg = Intent.GetExtra("msg")
       
    If Intent.HasExtra("collapse_key"Then CollapseKey = Intent.GetExtra("collapse_key")
       
    'qui dovrei riuscire a recuperare gli altri tag

       
    'Here you should handle the new message:
       Log("New message arrived: " & Data)
       
    'ToastMessageShow("New message: " & Data, True)
       Dim n As Notification
       n.Initialize
       n.Light = 
    False
       n.Vibrate = 
    False
       n.Icon = 
    "icon"
       n.SetInfo(
    "Movida Salento", Msg, elenco_eventi_push) 'Change Main to "" if this code is in the main module.
       n.notify(Num_notify)
       Num_notify=Num_notify+
    1
    End Sub


    Sub RegisterDevice (Unregister As Boolean)
       
    Dim i As Intent
       
    If Unregister Then      
          i.Initialize(
    "com.google.android.c2dm.intent.UNREGISTER""")
          
    'Main.Token_App = i.GetExtra("registration_id")
       Else
          i.Initialize(
    "com.google.android.c2dm.intent.REGISTER""")
          i.PutExtra(
    "sender", Main.SenderId)
       
    End If
       
    Dim r As Reflector
       
    Dim i2 As Intent
       i2 = r.CreateObject(
    "android.content.Intent")
       
    Dim pi As Object
       pi = r.RunStaticMethod(
    "android.app.PendingIntent""getBroadcast", _
          
    Array As Object(r.GetContext, 0, i2, 0), _
          
    Array As String("android.content.Context""java.lang.int""android.content.Intent""java.lang.int"))
       i.PutExtra(
    "app", pi)
       
    StartService(i)
    End Sub

    Sub HandleRegistrationResult(Intent As Intent)
       
    If Intent.HasExtra("error"Then
          
    Log("Error: " & Intent.GetExtra("error"))
          
    ToastMessageShow("Error: " & Intent.GetExtra("error"), True)
       
    Else If Intent.HasExtra("unregistered"Then
          
    If hcInit = False Then hc.Initialize("hc")
          
    Dim req As HttpRequest
          req.InitializeGet(Main.BoardUrl & 
    "?op=unregister&id_app=" & Main.ID_App & "&device_password=" & Main.DeviceBoardPassword & _
             
    "&name=" & Main.DeviceName & "&id_user=" & Main.imei & Main.androidID & "&regId="'Empty id is sent here. This will cause the board to delete this name.
          hc.Execute(req, UnregisterTask)
       
    Else If Intent.HasExtra("registration_id"Then
          
    If hcInit = False Then hc.Initialize("hc")
          
    Dim rid As String
          rid = 
    Intent.GetExtra("registration_id")
          
    'ToastMessageShow(rid, True) 'roba mia
          Dim req As HttpRequest
          req.InitializeGet(Main.BoardUrl & 
    "?op=register&id_app=" & Main.ID_App & "&device_password=" & Main.DeviceBoardPassword & _
             
    "&name=" & Main.DeviceName & "&id_user=" & Main.imei & Main.androidID & "&regId=" & rid)
          hc.Execute(req, RegisterTask)
       
    End If
    End Sub

    Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
       
    Select TaskId
          
    Case RegisterTask
             
    ToastMessageShow("Notifiche abilitate. "False)
          
    Case UnregisterTask
             
    ToastMessageShow("Notifiche disabilitate. "False)
       
    End Select
       Response.Release
    End Sub
    Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
       
    Dim errorMsg As String
       errorMsg = 
    "Code=" & StatusCode & ", " & Reason
       
    If Response <> Null Then
          
    Try
             errorMsg = errorMsg & 
    ", " & Response.GetString("UTF8")
          
    Catch
             
    Log("Failed to read error message.")
          
    End Try
          Response.Release
       
    End If
       
    ToastMessageShow(errorMsg, True)
       
    Log(errorMsg)
    End Sub

    Sub Service_Destroy

    End Sub
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    Can you post Sub Process_Globals of the main activity (this is where the error happens)?
     
  17. spyboy79

    spyboy79 Member Licensed User

    Hi Erel,
    thank you for help :)

    Code:
    Sub Process_Globals
       
    'These global variables will be declared once when the application starts.
       'These variables can be accessed from all modules.
       Dim Schermo_Larghezza, Schermo_Altezza, Img_Header_Height As Int
       
    Dim TMP_Rapporto As Double
       Schermo_Larghezza = 
    Activity.Width 
       Schermo_Altezza = 
    Activity.Height
       
       
    Dim base_server, Nome_App, ID_App, Versione As String 
       
    Dim pagina_xml, immagini_slider As String 
       
    Dim Max_Eventi As Int
       
    Dim ID_Schermata_Precedente As Int
       
       
    Dim tmrAnimation As Timer
       
    Dim currentPanelBeforePaused As Int
       
       
    'variabili push
       Public DeviceBoardPassword, BoardUrl, SenderId, DeviceName, Token_App As String
       
    'DeviceBoardPassword = "34f34fkj02d3"
       BoardUrl = "http://**************.it/android_get.php"
       
    'Set this field to matcht he project ID in Google Console.
       SenderId = "100681******"
       DeviceName = 
    "ttx"
       
       
    Dim pID As PhoneId
       
    Dim imei As String
       
    Dim phn As Phone
       
    Dim androidID As String

    End Sub
     
  18. spyboy79

    spyboy79 Member Licensed User

    Erel!
    Error found!

    I removed "Schermo_Larghezza = Activity.Width" and "Schermo_Altezza = Activity.Height" from Process_Global and now seems works perfect
     
  19. taunusbaer01

    taunusbaer01 Member Licensed User

    with php 5.2.17 runs the php script

    hallo at all,
    here one info to all they dont know why the mysql DB are emty.

    I search to day in all threads and in my projekt environment where are the error why the DB in mysql leavs empty.

    I change the PHP version from 4.1.2 to 5.2.17 and then it runs.

    Thanks Erl for this dokumentation

    Uwe
     
  20. sorex

    sorex Expert Licensed User

    Howdy,

    I've been reading this push tutorial and wondered if this could be used to sync a database aswell?

    like first initiate a local copy that you bulk insert and when that's done use these push notification to add new content when it's added on the server.

    It will take less traffic but is it worth the trouble as it doesn't appear to be easy or is it not suitable at all for this? (device>db still needs plain http posts too)
     
Loading...