0

I'm trying to develop a mobile web app with phonegap build and implementing push notifications through amazon SNS.
I'm currently testing on android and i managed to make the notifications work while the app is in background or in foreground but if i completely kill the app the notifications are not received. As soon as i launch the app it receives the 'pending' notifications.
I did extensive searches but didn't found a solution, since i receive the notification in background and foreground and i don't receive any error from AWS, i think the registration of the device and the server side are correct.

How can i receive notifications in the standard status bar even if the app is completely shut down ?

Here's some code:

CLIENT

    jQuery(document).ready(function($) {
        document.addEventListener("deviceready", onDeviceReady, false);
    });

    function onDeviceReady(){ 
      pushNotificationFlow(); 
      function pushNotificationFlow(){
        var pushNotification = window.plugins.pushNotification;
        window.GCMsenderID = '123456789';

        if(isMobile.Android()){

            //android
            pushNotification.register(successHandler, errorHandler,{"senderID": window.GCMsenderID,"ecb":"onNotificationGCM"});
        }
        else{

            //ios
            pushNotification.register(tokenHandler, errorHandler,{
            "badge":"true",
            "sound":"true",
            "alert":"true",
            "ecb":"onNotificationAPNS" });
        }
        function tokenHandler (result) {

            var idUser=getLocalUser();
            if ( result.length > 0 ){
                $.post('http://myserver.com/my_serverside_registration.php', {
                    token: result,
                    shop: window.shop,
                    type: 'APNS',
                    id_user: idUser
                },function( data ) {

                });
            }

        }
        function successHandler (result) {

        }
        function errorHandler (error) {

        }
    }
function onNotificationGCM (e) {

    $.post('http://pointcard.stayted.com/pushTest.php', {
            log: JSON.stringify(e) 
        });

    switch( e.event )
    {
        case 'registered':
            if ( e.regid.length > 0 )
            {
                var idUser=getLocalUser();

                $.post('http://myserver.com/my_serverside_registration.php', {
                    token: e.regid,
                    shop: window.shop,
                    type: 'GCM',
                    id_user: idUser
                },function( data ) {

                });
            }
            break;

        case 'message':
            // this is the actual push notification. its format depends on the data model from the push server

            alert('message = '+e.message+' msgcnt = '+e.msgcnt);
            break;

        case 'error':

            break;

        default:

            break;
    }
}
function onNotificationAPNS (e) {

    if ( e.alert )
    {
            chocolatApp.addNotification({
                title: 'mytitle',
                message: e.alert,
                media: '<img width="44" height="44" style="border-radius:100%" src="dist/img/appIcon.png">'
            });
    }

    if ( e.sound )
    {
        var snd = new Media(e.sound);
        snd.play();
    }

    if ( e.badge )
    {
        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, e.badge);
    }}

SERVER

    //create amazon SNS client
    require_once dirname(__FILE__).'/vendor/autoload.php';
    use Aws\Sns\SnsClient;

    $message = 'test message '.date('d/m/Y G:i',time());
    $title= 'mytitle';

    $AWS_apiKey = 'my_apiKey';
    $AWS_apiSecret = 'my_apiSecret';
    $region = 'region';
    $topicArn = 'my_topicArn';
    $endpointArn = 'my_endpointArn';

    // Instantiate with your AWS credentials
    $client = SnsClient::factory(array(
            'credentials' => array(
                'key'    => $AWS_apiKey,
                'secret' => $AWS_apiSecret,
            ),
            'region'  => $region
        ));

    //Publish
    try{
        $array = array(
            //'TopicArn' => $topicArn,
            'TargetArn' => $endpointArn,
            // Message is required
            'Message' => json_encode(array(
                'default' => 'default',
                'APNS' => json_encode(array(
                    'aps' => array(
                        'alert' =>  $message,
                        "sound" => "default",
                    ),
                )),
                'APNS_SANDBOX' => json_encode(array(
                    'aps' => array(
                        'alert' =>  $message,
                        "sound" => "default",
                    ),
                )),
                'GCM' => json_encode(array(
                    'data' => array(
                        'message' => $message,
                        'title' => $title,
                    )
                )),
            )),
            'MessageStructure' => 'json',
            'MessageAttributes' => array(
                // Associative array of custom 'String' key names
                'String' => array(
                    // DataType is required
                    'DataType' => 'String',
                    'StringValue' => 'String'
                    //'BinaryValue' => 'String',
                ),
            ),
        );
        $messageID = $client->publish($array);

    }catch (\Exception $e) {
        $error = $e->getMessage();
    }

    if(!empty($error)){
        $alert.="<div class=\"alert alert-danger\">
            <strong>Error</strong>: ".print_r($error,true)."
        </div>";
    }
    elseif(!empty($message) AND empty($alert) ){
        $alert.="<div class=\"alert alert-success\">
            <strong>Ok.</strong> success.
        </div>";
    }
}

EDIT: I'm refering to closing the app from 'recents' not about force stopping it from settings -> apps

Riccardo
  • 346
  • 2
  • 17
  • 1
    Possible duplicate of [GCM push notification works after app Force Stop?](http://stackoverflow.com/questions/20838415/gcm-push-notification-works-after-app-force-stop) – AL. May 20 '16 at 07:39
  • 1
    It's the expected android behavior to not receive if the app is totally dead, since Android 3.1. See the linked post's accepted answer. Cheers! :) – AL. May 20 '16 at 07:40
  • 1
    I implemented push notifications with Google Cloud Messaging and I'm getting the messages even if the application is completely shut down. Maybe you can try to set the time-to-live on server side of your message to 0 or another variable. In case of GCM you have to implement a GCMListenerService and that one keeps running even if the app is completely shut down. EDIT: depends on what you mean by completely closed, if you force shutdown in setting it won't work but if you just kill it in the "recent apps" it should still work. – Allinone51 May 20 '16 at 07:41
  • I'm not interested on app stopped from settings, i mean app killed from "recent apps" – Riccardo May 20 '16 at 08:59

2 Answers2

2

Try using some readily available platforms for Push Notifications from server side like PubNub: https://www.pubnub.com/blog/2015-06-23-getting-started-with-gcm-android-push-notifications-and-pubnub/ https://www.pubnub.com/blog/2015-06-24-sending-receiving-android-push-notifications-with-gcm-google-cloud-messaging/ I am also using them, they work fine.

1

try using

<uses-permission android:name="android.permission.WAKE_LOCK" />
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203