En el post anterior mostré como probar los ejemplos que google puso de GCM en android con app-engine java y comenté que no hay ejemplo en app-engine python, ahora vamos a explicar como implementarlo en python.
Antes de seguir con este post, si no hiciste andar los ejemplos del post anterior te recomiendo que lo leas para entender de que hablamos en este post.
Teniendo los ejemplos funcionado, ahora vamos a explicar como lo implementamos en python, tomamos como base la siguiente arquitectura de los ejemplos:
Como muestra la imagen, cuando iniciamos el ejemplo en android, realiza la siguiente lógica:
Inicia la aplicacion android
- Se registra en el servicio GCM de google
- Si el registro se realizó con éxito el servicio GCM le retorna una key única que identifica el device
- El device al recibir (asyncronico) la key de autorización, la guarda en una share preference y la envía a nuestro servidor para que este la guarde
- Muestra en la pantalla
Como el servidor ya tiene la key del dispositivo, este ya puede enviar un request utilizando esa key al servicio GCM. entonces cuando hacemos click en: Send Mensaje, el servidor hace un request (https://android.googleapis.com/gcm/send) por https con las siguientes variables:
En HTTP header:
Authorization
: key=YOUR_API_KEY
Content-Type
: application/json
(for JSON); application/x-www-form-urlencoded;charset=UTF-8 (
for plain text.)
En HTTP body (se puede enviar en formato json o texto plano, nosotros vamos a ver json)
registration_ids (string con los ID de los devices que van a recibir el mensaje)
data (datos a enviar en formato json)
Nota: Se pueden enviar otras variables según la necesitad ver aqui
Ejemplo json:
Content-Type:application/json Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA { "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...", "data" : { ... }, }
La Respuesta pude ser:
200 – Message was processed successfully
400 – Only applies for JSON requests. Indicates that the request could not be parsed as JSON
401 – There was an error authenticating the sender account
500 – There was an internal error in the GCM server while trying to process the request
503 – Indicates that the server is temporarily unavailable
Todos estos datos estan en la doc oficial: aqui
Entonces armemos el request en AppEngine python!
Para hacerlo mas corto, voy a asumir que ya probaron el ejemplo del post anterior y tienen el ID del device que le mando el servicio GCM al dispositivo
Si ejecutaron el demo, pueden ir al sistema de archivo de android, data > data > com.google.android.gcm.demo.app > shared_pref y sacar el archivo com.google.android.gcm.xml (dentro de ese xml se encuentra el id)
Teniendo el id del dispositivo, podemos hacer un ejemplo muy reducido de como enviarle un mensaje al device:
class SendMessage(webapp.RequestHandler): self.response.headers['Content-Type'] = 'text/html' self.response.set_status( 200,"OK" ) self.response.out.write('<html>') self.response.out.write('<head>') self.response.out.write('<title>') self.response.out.write('Push') self.response.out.write('</title>') self.response.out.write('</head>') self.response.out.write('<body>') Bodyfields = { "data": {"sms":"sms python!!"}, "registration_ids": ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."] } result = urlfetch.fetch(url="https://android.googleapis.com/gcm/send", payload=simplejson.dumps(BodyFields), method=urlfetch.POST, headers={'Content-Type': 'application/json','Authorization': 'key=AIzaSyCh9nJI...'}) self.response.out.write('Server response, status: ' + result.content ) self.response.out.write('</body>') self.response.out.write('</htnl>') application = webapp.WSGIApplication( [('/', StartPage), ('/sender',SendMessage), debug=True)
Arrancamos el server de desarrollo de appengine y ya podemos hacer un test de enviar un mensaje a la app demo android
Nota: esto es solo un ejemplo muy reducido sin tener en cuenta ningún control, pero es la base para empezar a utilizar GCM en appengine python
la app demo en android, solo muestra por pantalla que llego un mensaje, pero no muestra que mensaje, para ver el mensaje agrear en el fuente: GCMIntentService.java
@Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message"); String message = getString(R.string.gcm_message); String data = intent.getStringExtra("sms") // nueva linea message += " menssage: " + data; //nueva linea displayMessage(context, message); // notifies user generateNotification(context, message); }
Cuando ejecuten en el browser: iplocal:puerto/sender, deberíamos ver el mensaje en android («menssage: sms python!!»)!!
Fuentes:
[…] « Como compilar el kernel o un módulo en ubuntu Ejemplo GCM en AppEngine (python) […]
[…] Here’s another question with some code. Google Cloud Messaging HTTP Error 400: Bad Request and a blogpost (in not english, i think spanish. but there some sample code) https://pforray.wordpress.com/2012/07/05/ejemplo-gcm-en-appengine-python/ […]
https://www.facebook.com//phoenixbailbonds/?_fb_noscript=1
What do you guys think? Is BTC: cours du bitcoin en direct there an element of of bias- circa speaking, around shoes, around clothe codes- at investment banks that prevents students from poorer backgrounds from succeeding? Or take banks straight befit the latest aim of activists who want to find bent everywhere?
Time, he hears more simple questions from other football players, like, “Are there carnal coins?” Or teammates disposition appeal to, “What is the contrariety dispute between Tout savoir sur la crypto: cours du bitcoin en temps reel this and a stock? Or this and a bond?” According to Sherman: “None of us in actuality grew up with monetary literacy.” Because of this, in the good old days, a grouping of players maintain been enchanted drop of before monetary advisors.
Бензотрейд магазин – динамично растущая коммерческая компания, действующая на Российском экономическом рынке более 7долгих лет.
Вам нужны садовые инструменты и техника для сада, но не понимаете,какая конкретно надежнее и где её купить сегодня? Мы вам можем предложить найти наш интернет магазин Бензотрейд. В магазине пребольшущий подборка ДВИГАТЕЛИ. Когда лично вы решили купить сегодня Насосы скважинные БЕНЗОТРЕЙД магазин предоставим вам все модели товара.
Магазин бензотрейд это то место где можно купить все для дома начиная с КУЛЬТИВАТОРЫ и заканчивая ТЕПЛОВЫМ ОБОРУДОВАНИЕМ.
Получить садовую технику а также приборы в указанном интернет магазине на портале можно по будням и по не рабочим дням(суббота и воскресенье) Доставка каждого купленного оборудования при закупки от 9 тысяч рублей осуществляется по городу бесплатно. Мы готовы предоставить сертификат гарантии на все изделия, те что присутствует в нашем магазине товаров для дома. Отправление агрегатов по месту выполняется в течении суток до пяти рабочих дней после оформления и оплаты товара. Сроки зависят от места доставки, данную информацию уточнит менеджер магазина Бензотрейд.
Стоит также подчеркнуть, что в компании «БензоТрейд» Вам всегда гарантирован индивидуальный подход и помощь высоквалифицированных специалистов, вне зависимости от предмета покупки. Будь то сварка или пила, виброплита, вибротрамбовка или триммер Вам всегда обеспечено обслуживание высшего уровня.
дровоколы partner от фирменного магазина – официальный сайт partner Поволжье
Are you looking free sexual hookup women for one night stand on your near me area? Find dating girls. Meet here plenty of women that are online who are seeking guys for free sex and fuck tonight. A great deal of singles available close to you for gender, flirt, romance, get laid and no string attached relationship.
click here