推送通知在android中获得多次


Push notification getting mutiple times in android

我使用Eclipse创建了一个移动应用程序。

服务器通过GCM(Php)发送推送通知。

首次安装APK后,它会发送一个推送通知,该通知工作正常。对于秒时间(同一设备上的同一应用程序),它发送两次,第三次,三次,依此类推

我发现问题是由添加相同设备的更多ID引起的。因此,如果我手动删除所有ID并再次安装APK,它将正常工作。

$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;

安卓侧

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);
    }

这就是我如何使用PHP通过GCM处理Push通知的方法。

服务器是一个复杂的REST服务器,但现在您只需要了解其中的几个部分

接收并存储Push token

您需要一个Push token来确定GCM应该在哪个设备上发送推送。因此,您需要存储它,但请记住它可能会发生更改,因此,如果发生这种情况,您的应用程序需要将新的发送到服务器,并且需要在数据库中进行更改。

发送Push notification

为了发送推送通知,我从数据库中恢复Push token,然后使用PushSender类实际发送push notification

使用来自MySql服务器的查询检索push token

PushSender类的用法:

$push = new PushSender('The push title','The message',$push_token]);
$ret = $push->sendToAndroid();
// Check $ret value for errors or success

PushSender类:

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;
    }
}

通过服务在Android中接收push notification

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());
}