Home Menu

Menu



Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android


 
Herramientas
  #1  
Viejo 26/06/14, 21:28:45
Avatar de ctkd17
ctkd17 ctkd17 no está en línea
Usuario poco activo
Mensajes: 37
 
Fecha de registro: feb 2012
Mensajes: 37
Modelo de smartphone: Sony xperia neo V
Versión de ROM: CROM kk v5.9 20140413
Tu operador: Pepephone
Mencionado: 0 comentarios
Tagged: 0 hilos
Problema Google Cloud Message

Muy buenas a todos!

Estoy haciendo una APP que usa gcm y me encuentro con dos problemas gordos:

1- Tarda en llegarme los mensajes desde el servidor:
Tengo comprobado en mi servidor que se envían bastante rápido así que se puede descartar que el problema este en el servidor, lo que me lleva a pensar que, o es de google o es mio de la app.

2- Pasado un tiempo, pierdo el registro de google:
Esto lo se por que en el servidor veo el motivo del fallo: NotRegistred


Comentar que no en todas las peticiones REST que hago recojo el resultado, pues hay ocasines en las que no me sirve de nada.
Os dejo aqui mi manifest, el .java desde el que me registro y el .java en el que recojo el mensaje push:

Manifest:
Código:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.partec.app">

    <uses-feature android:name="android.hardware.usb.host"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.partec.app.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.partec.app.permission.C2D_MESSAGE" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


        <activity
            android:name="com.partec.app.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.BOOT_COMPLETED" />
            </intent-filter>

            <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/usb"/>

        </activity>



        <service
            android:name="com.partec.app.ServicioProtocolo"
            android:enabled="true" >
        </service>

        <service
            android:name="com.partec.app.ServicioEnvio"
            android:enabled="true" >
        </service>

        <service
            android:name="com.partec.app.ServicioComServer"
            android:enabled="true" >
        </service>

        <service
            android:name="com.partec.app.ServicioRegInBack"
            android:enabled="true" >
        </service>


        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <receiver android:name=".BootReciever" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <receiver
            android:name= ".GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.partec.app"/>
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" android:enabled="true"/>


    </application>

</manifest>
Registro:

Código:
public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i("Master/ComServer","onStartCommand");


        gcm = GoogleCloudMessaging.getInstance(this);
        boolean stop = false;
        int cont_stop=0;
        regid=getRegistrationId(context);

        registerInBackground();

        startService(new Intent(ServicioComServer.this, ServicioRegInBack.class));

        while(stop==false){
            regid = getRegistrationId(context);
            if(regid.isEmpty()==false || cont_stop>1000){
                Log.i("Server", "iGoogle:"+regid);
                stop=true;
                cont_stop=0;
            }else{
                cont_stop++;
            }
        }

                new AsyncTask<Object, Object, Object>() {
                    @Override
                    protected Object doInBackground(Object... params) {
                    
                    boolean stop= false;    
                        
                    HttpPost post;
                    JSONObject respJSON = null;
                    
                    while(stop==false){
                        respJSON = null;
                        String id_virtual = getId(context);
    
                        if (!id_virtual.isEmpty()) {
                            post = new HttpPost("http://www.web-system.eu/ws/master-save/"+ id_virtual + "/" + regid);
                            Log.i("SERVER","Hay idvirtual:"+id_virtual);
                            idMaster=id_virtual;
                        } else {
                            post = new HttpPost("http://www.web-system.eu/ws/master-save/00/"+ regid);
                            Log.i("SERVER","no hay ID virtual");
                        }
                        post.setHeader("content-type", "application/json");
                        HttpResponse resp;
                        try {
                            resp = clienteh.execute(post);
                            Log.i("Master/ComSerer","Peticion registro enviada");
    
                            String respStr = EntityUtils.toString(resp.getEntity());
                            respJSON = new JSONObject(respStr);
    
                        } catch (ClientProtocolException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
    
                        if (respJSON != null) {
                            try {
                                String resultado = respJSON.getString("result");
                                
                                if(resultado.equals("0")){
                                    Log.i("Server","ID no valido");
                                    setID("", context);
                                    startService(new Intent(ServicioComServer.this, ServicioComServer.class));
                                    
                                }else{
                                
                                String id_master_nuevo = respJSON.getString("data");
    
                                if (!id_virtual.equals(id_master_nuevo)) {
                                    setID(id_master_nuevo, context);
                                    idMaster=id_master_nuevo;
                                    Log.i("SERVER","Nuevo ID guardado");
                                }
                                
                                Log.i("Id-Master",id_master_nuevo);
                                stop=true;
                                }
                            } catch (NumberFormatException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        
                        }
                    return respJSON;
                    }
                }.execute(null, null, null);
                
                
                

            
            
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {

        sendBroadcast(com_error);
        super.onDestroy();

    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
                Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i("Server", "App version changed.");
            return "";
        }
        return registrationId;
    }
    
    private String getId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String regID = prefs.getString("ID_VIRTUAL","");
        if (regID.isEmpty()) {
            Log.i("Server", "Registration id virtual not found");
            return "";
        }
        
        return regID;
    }
    
    private boolean setID(String id, Context context){
        SharedPreferences prefs = getSharedPreferences(ServicioComServer.class.getSimpleName(),Context.MODE_PRIVATE);
        
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("ID_VIRTUAL",id);
        editor.commit();
        
        return true;
    }

    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences,
        // but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(ServicioComServer.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }

    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    private void registerInBackground() {
        new AsyncTask<Object, Object, Object>() {

            @Override
            protected Object doInBackground(Object... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);
                    msg = "Device registered, registration ID=" + regid;
                    Log.i("Server-regb", msg);

                    storeRegistrationId(context, regid);
                } catch (final IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    Log.e("Server-regb", msg);
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                }
                return msg;

            }
        }.execute(null, null, null);
    }

    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i("Server", "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();

    }

}
Código:
GCMBroadcast:

package com.partec.app;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

import static android.support.v4.content.WakefulBroadcastReceiver.startWakefulService;

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        ComponentName comp =
                new ComponentName(context.getPackageName(),
                        GCMIntentService.class.getName());

        Log.i("ENbrod", "Mensaje!");

        startWakefulService(context,(intent.setComponent(comp)));

        setResultCode(Activity.RESULT_OK);
    }
}
GCMIntentService:

Código:
package com.partec.app;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.util.StringTokenizer;

/**
 * Created by root on 23/04/14.
 */
public class GCMIntentService extends IntentService {
    private static final int NOTIF_ALERTA_ID = 1;

    public GCMIntentService() {
        super("GCMIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);
        Bundle extras = intent.getExtras();
        String mensaje;

        Log.i("Master/GCMIntent","Ejecucion intent service");

        if (!extras.isEmpty()) {
            Log.i("Partec-Reciver", "Llego mensaje!");


            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                mensaje = extras.getString("message");
                //mostrarNotification(mensaje);
                analizaMensaje(mensaje);

            }
        }

        GCMBroadcastReceiver.completeWakefulIntent(intent);

        return;
    }

    private void mostrarNotification(String msg) {
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(android.R.drawable.stat_sys_warning)
                        .setContentTitle("Notificación Master-Debuger")
                        .setContentText("Mensaje: "+msg);

        Intent notIntent = new Intent(this, MainActivity.class);
        PendingIntent contIntent = PendingIntent.getActivity(this, 0, notIntent, 0);

        mBuilder.setContentIntent(contIntent);

        mNotificationManager.notify(NOTIF_ALERTA_ID, mBuilder.build());
    }

    private void analizaMensaje(String mensaje) {
        String comando;
        String parametro;
        parseByte p = new parseByte();

        StringTokenizer tokenizer;

        Intent com_actbd = new Intent();
        com_actbd.setAction(MainActivity.broadcastActualizaBD.ACTION_RESP);
        com_actbd.addCategory(Intent.CATEGORY_DEFAULT);


        Intent com_envio = new Intent();
        com_envio.setAction(ServicioEnvio.broadcastEnvio.ACTION_RESP);
        com_envio.addCategory(Intent.CATEGORY_DEFAULT);



        tokenizer = new StringTokenizer(mensaje, "-");

        comando = tokenizer.nextToken();
        parametro = tokenizer.nextToken();

        if (!comando.isEmpty()) {
            Log.i("Dentro de Analzia","isEmpty false");
            if (comando.equals("LC")) {
                if(parametro.isEmpty()){
                    return;
                }else{

                   com_envio.putExtra("id",p.stringToByte(parametro));
                   com_envio.putExtra("trama",new byte[]{0x01,p.stringToByte(parametro), 0x00, 0x02, 0x31, 0x05});
                   com_envio.putExtra("cambio",false);
                   com_envio.putExtra("comando", comando);
                   sendBroadcast(com_envio);

                }

            } else if (comando.equals("BC")) {
                if(parametro.isEmpty()){
                    return;
                }else{

                    com_envio.putExtra("id",p.stringToByte(parametro));
                    com_envio.putExtra("trama",new byte[]{0x01,p.stringToByte(parametro), 0x00, 0x02, 0x03, 0x05});
                    com_envio.putExtra("cambio",true);
                    com_envio.putExtra("comando",comando);
                    sendBroadcast(com_envio);
                    com_actbd.putExtra("comando",parametro);
                    com_actbd.putExtra("modo","BC");
                    sendBroadcast(com_actbd);

                }
            } else if (comando.equals("RC")) {
                        /*AQUI IMPLEMENTAMOS RESERVAR CERRADURA*/
            }else if (comando.equals("CO")) {
                if(parametro.isEmpty()){
                    return;
                }else{

                    com_envio.putExtra("id",p.stringToByte(parametro));
                    com_envio.putExtra("trama",new byte[]{0x01,p.stringToByte(parametro), 0x00, 0x02, 0x15, 0x05});
                    com_envio.putExtra("cambio",true);
                    com_envio.putExtra("comando",comando);
                    sendBroadcast(com_envio);
                    com_actbd.putExtra("comando","update poste set estado = 'OCUPADO' where id_cerr="+parametro+";");
                    com_actbd.putExtra("modo","");
                    sendBroadcast(com_actbd);

                }
            } else if (comando.equals("OB")) {
                if(parametro.isEmpty()){
                    return;
                }else{

                    com_envio.putExtra("id",parametro);
                    com_envio.putExtra("trama",new byte[]{0x01,p.stringToByte(parametro), 0x00, 0x05, 0x04});
                    com_envio.putExtra("cambio",false);
                    com_envio.putExtra("comando",comando);
                    sendBroadcast(com_envio);

                }
            } else if (comando.equals("BM")) {
                com_envio.putExtra("id","-1");
                com_envio.putExtra("trama",new byte[]{0x01,p.stringToByte(parametro), 0x00, 0x05, 0x04});
                com_envio.putExtra("cambio",false);
                com_envio.putExtra("comando",comando);
                sendBroadcast(com_envio);
            }
        }else{

            Log.i("Dentro de Analiza","isEmpty true");
            return;
        }
    }
}
De antemano pedir gracias a toda la comunidad, que sois mu grandes!!!

Un saludo!
Responder Con Cita


  #2  
Viejo 28/06/14, 18:19:16
Avatar de ctkd17
ctkd17 ctkd17 no está en línea
Usuario poco activo
Mensajes: 37
 
Fecha de registro: feb 2012
Mensajes: 37
Modelo de smartphone: Sony xperia neo V
Versión de ROM: CROM kk v5.9 20140413
Tu operador: Pepephone
Mencionado: 0 comentarios
Tagged: 0 hilos
Ya he solucionado el problema, o mejor dicho descubierto las causas:

Resulta que GCM no funciona bien con conexiones WIFI y de ahí el problema.

Un saludo!
Responder Con Cita
Respuesta

Estás aquí
Regresar   HTCMania > Todo sobre Android > Programación y Desarrollo para Android


Reglas de Mensajes
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Las caritas están On
Código [IMG] está On
Código HTML está Off

Saltar a Foro



Hora actual: 02:45:51 (GMT +2)

Cookies
Powered by vBulletin™
Copyright © vBulletin Solutions, Inc. All rights reserved.
 
HTCMania: líderes desde el 2007