简体   繁体   中英

Push notification getting mutiple times in android

I have created a mobile application by using Eclipse.

The server sends push notifications via GCM (in Php).

Upon installation of the APK for the first time, it sends one push notification, which is working correctly. For the seconds time (same APP on the same device) it sends twice, and third time, three times and so on.

I have discovered the problem is caused by adding more IDs of same device. So if I manually delete all the IDs and install the APK again, it will work fine.

$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registatoin_ids,'data' => $message,); $headers = array( 'Authorization: key=' . 'asbjadbdb','Content-Type: application/json');        
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {  die('Curl failed: ' . curl_error($ch));}
curl_close($ch);
echo $result;

Android side

protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                sendNotification(false,"Send error: " + extras.toString(),null,null,null);
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                sendNotification(false,"Deleted messages on server: "
                        + extras.toString(),null,null,null);
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {
//              sendNotification("Message Received from Google GCM Server:\n\n"
//                      + extras.get(ApplicationConstants.MSG_KEY));
                String name=extras.getString("name");
                String address=extras.getString("address");;

                sendNotification(true,name,address);

            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

This is how I managed to work with Push notification via GCM using PHP.

The server is a complex REST server but right now you need to understand only a few parts of it.

Receive and store a Push token

You need a Push token in order to identify on which device GCM should send the push. Hence you need to store it but keep in mind that it might change thus, if that happens, you application needs to send the new one to the server and it needs to be changed in your database.

Send the Push notification

To send a push notification I recover the Push token from database and then use the PushSender class to actually send the push notification

Retrieve push token with a query from my MySql server.

Usage of the PushSender class:

$push = new PushSender('The push title','The message',$push_token]);
$ret = $push->sendToAndroid();

// Check $ret value for errors or success

The PushSender class:

Class PushSender {

    private $title;
    private $message;
    private $pushtoken;

    private static $ANDROID_URL = 'https://android.googleapis.com/gcm/send';
    private static $ANDROID_API_KEY = 'YOUR-API-KEY';

    public function __construct($title, $message, $pushtoken){

        $this->title = $title;
        $this->message = $message;
        $this->pushtoken = $pushtoken;
    }

    public function sendToAndroid(){

        $fields = array(
            'registration_ids' => array($this->pushtoken),
            'data' => array( "title"=>$this->title, "message" => $this->message ),
        );

        $headers = array(
            'Authorization: key=' . self::$ANDROID_API_KEY,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, self::$ANDROID_URL);
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER , false );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST , false );

        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch);

        if( curl_errno($ch) ){
            curl_close($ch);
            return json_encode(array("status"=>"ko","payload"=>"Error: ".curl_error($ch)));
        }

        curl_close($ch);
        return $result;
    }
}

Receive the push notification in Android via a Service.

public class PushListenerService extends GcmListenerService {
    @Override
    public void onMessageReceived(String from, Bundle data) {

        String message = data.getString("message");

        // Do whatever you need to do
        // Then send the notification
        sendNotification(message);
}

private void sendNotification(String message) {

    Intent intent = new Intent(this, YourClass.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.an_icon)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(Helpers.getString(R.string.push_notification_message))
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    try{
        notificationBuilder
                .setLargeIcon(Bitmap.createBitmap(((BitmapDrawable)getDrawable(R.drawable.your_icon)).getBitmap()));

    }catch (NullPointerException e) {
        e.printStackTrace();
    }

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM